Beispiel #1
0
        /// <summary>
        /// 收到信息的函数
        /// 并匹配相应指令
        /// </summary>
        public async void GetChat(RegexCommand cmdType)
        {
            if (PCREventArgs == null || Sender == null)
            {
                return;
            }
            switch (cmdType)
            {
            //查询公会排名
            case RegexCommand.GetGuildRank:
                //以群名为查询名
                if (PCREventArgs.Message.RawText.Length <= 6)
                {
                    var groupInfo = await QQGroup.GetGroupInfo();

                    if (groupInfo.apiStatus != APIStatusType.OK)
                    {
                        await QQGroup.SendGroupMessage("调用onebot API时发生错误");

                        Log.Error("api error", $"调用onebot API时发生错误 Status={groupInfo.apiStatus}");
                        return;
                    }

                    await KyoukaRank(DBHelper.GetGuildName(PCREventArgs.SourceGroup));
                }
                else     //手动指定
                {
                    await KyoukaRank(PCREventArgs.Message.RawText.Substring(6));
                }

                break;
            }
        }
Beispiel #2
0
        private async void SendLocalPic(Hso hso)
        {
            string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath());
            if (picNames.Length == 0)
            {
                await QQGroup.SendGroupMessage("机器人管理者没有在服务器上塞色图\r\n你去找他要啦!");

                return;
            }

            Random randFile     = new Random();
            string localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}";

            Log.Debug("发送图片", localPicPath);
            await QQGroup.SendGroupMessage(hso.CardImage
                                           ?CQCode.CQCardImage(localPicPath)
                                           : CQCode.CQImage(localPicPath));
        }
Beispiel #3
0
        /// <summary>
        /// 签到
        /// </summary>
        private void SignIn()
        {
            ConsoleLog.Info("收到消息", "慧酱签到");
            SuiseiDBHelper suiseiDB = new SuiseiDBHelper(Sender, SuiseiEventArgs);

            suiseiDB.SignIn();
            SuiseiData userData = suiseiDB.UserData; //数据库查询到的用户数据

            //签到成功判断
            if (userData.ChatDate == suiseiDB.TriggerTime && suiseiDB.IsExists) //今天已经签到过了
            {
                QQGroup.SendGroupMessage("neeeeeeee\nmooooooo\n今天已经贴过了");
            }
            else //签到
            {
                suiseiDB.FavorRateUp();
                QQGroup.SendGroupMessage("奇怪的好感度增加了!\n当前好感度为:", userData.FavorRate);
            }
        }
        private async void GetGuildRank(string[] commandArgs)
        {
            //检查参数
            switch (Utils.CheckForLength(commandArgs, 1))
            {
            case LenType.Illegal:
                await BiliWikiRank(QQGroup.GetGroupInfo().Name);

                break;

            case LenType.Legitimate:
                await BiliWikiRank(commandArgs[1]);

                break;

            default:
            case LenType.Extra:
                QQGroup.SendGroupMessage("有多余参数");
                return;
            }
        }
Beispiel #5
0
 /// <summary>
 /// 下载图片保存到本地
 /// </summary>
 /// <param name="url">目标URL</param>
 /// <param name="receivePath">接收文件的地址</param>
 private void DownloadFileFromURL(string url, string receivePath)
 {
     try
     {
         int      progressPercentage = 0;
         long     bytesReceived      = 0;
         DateTime flashTime          = DateTime.Now;
         Console.WriteLine("开始从网络下载文件");
         WebClient client = new WebClient();
         //文件下载
         client.DownloadProgressChanged += (sender, args) =>
         {
             if (progressPercentage != args.ProgressPercentage)
             {
                 progressPercentage = args.ProgressPercentage;
                 ConsoleLog
                 .Debug("Download Pic", $"Downloading {args.ProgressPercentage}% " +
                        $"({(args.BytesReceived - bytesReceived) / 1024.0 / (DateTime.Now - flashTime).TotalSeconds}KB/s) ");
                 flashTime     = DateTime.Now;
                 bytesReceived = args.BytesReceived;
             }
         };
         //文件下载完成
         client.DownloadFileCompleted += (sender, args) =>
         {
             ConsoleLog.Info("Hso", "下载数据成功,发送图片");
             QQGroup.SendGroupMessage(CQApi.CQCode_Image(receivePath));
             ConsoleLog.Debug("file", Path.GetFileName(receivePath));
         };
         client.DownloadFileAsync(new Uri(url), receivePath);
     }
     catch (Exception e)
     {
         ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}");
     }
 }
        /// <summary>
        /// 从比利比利源查询排名
        /// </summary>
        private Task BiliWikiRank(string guildName)
        {
            string response;

            //获取响应
            try
            {
                //获取查询结果
                ConsoleLog.Info("NET", $"尝试查询{guildName}会站排名");
                QQGroup.SendGroupMessage("查询中...");
                response =
                    HTTPUtils
                    .GetHttpResponse($"https://tools-wiki.biligame.com/pcr/getTableInfo?type=search&search={HttpUtility.UrlEncode(guildName)}&page=0");
            }
            catch (Exception e)
            {
                QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员");
                ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e));
                //阻止下一步处理
                return(Task.CompletedTask);
            }
            //JSON数据处理
            try
            {
                if (string.IsNullOrEmpty(response))
                {
                    QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题");
                    ConsoleLog.Error("JSON数据读取错误", "从网络获取的文本为空");
                    return(Task.CompletedTask);
                }
                ConsoleLog.Debug("获取JSON成功", response);
                JArray responseJArray = JArray.Parse(response);
                //对返回值进行判断
                if (responseJArray.Count == 0)
                {
                    QQGroup.SendGroupMessage("未找到任意公会\n请检查是否查询的错误的公会名或公会排名在70000之后");
                    ConsoleLog.Info("JSON处理成功", "所查询列表为空");
                    return(Task.CompletedTask);
                }
                if (responseJArray.Count > 1)
                {
                    QQGroup.SendGroupMessage("查询到多个公会,可能存在重名或关键词错误");
                }


                if (responseJArray[0] is JObject rankData)
                {
                    string rank       = rankData["rank"]?.ToString();
                    string totalScore = rankData["damage"]?.ToString();
                    string leaderName = rankData["leader_name"]?.ToString();
                    ConsoleLog.Info("JSON处理成功", "向用户发送数据");
                    QQGroup.SendGroupMessage("查询成功!\n" +
                                             $"公会:{guildName}\n" +
                                             $"排名:{rank}\n" +
                                             $"总分数:{totalScore}\n" +
                                             $"会长:{leaderName}\n" +
                                             "如果查询到的信息有误,有可能关键词错误或公会排名在70000之后");
                }
            }
            catch (Exception e)
            {
                QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题");
                ConsoleLog.Error("JSON数据读取错误", $"从网络获取的JSON格式无法解析{ConsoleLog.ErrorLogBuilder(e)}");
                return(Task.CompletedTask);
            }
            return(Task.CompletedTask);
        }
        private void KyoukaRank(string guildName)
        {
            //网络响应
            string response;

            //获取网络响应
            try
            {
                //初始化查询JSON
                JObject clanInfoJson = new JObject
                {
                    ["clanName"] = guildName,
                    ["history"]  = 0
                };
                ConsoleLog.Info("NET", "尝试查询结果");
                //获取查询结果
                QQGroup.SendGroupMessage("查询中...");
                response =
                    HTTPUtils.PostHttpResponse("https://service-kjcbcnmw-1254119946.gz.apigw.tencentcs.com/name/0",
                                               clanInfoJson,
                                               "Windows", "application/json", "https://kengxxiao.github.io/Kyouka/", 3000, "BOT");
            }
            catch (Exception e)
            {
                QQGroup.SendGroupMessage($"哇哦~发生了网络错误,请联系机器人所在服务器管理员\n{e.Message}");
                ConsoleLog.Error("网络发生错误", e);
                //阻止下一步处理
                return;
            }
            //JSON数据处理
            try
            {
                if (string.IsNullOrEmpty(response))
                {
                    QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题");
                    ConsoleLog.Error("JSON数据读取错误", "从网络获取的文本为空");
                    return;
                }
                ConsoleLog.Info("获取JSON成功", response);
                JObject responseJObject = JObject.Parse(response);
                if (responseJObject["full"] == null)
                {
                    QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题");
                    ConsoleLog.Error("JSON数据读取错误", "从网络获取的JSON格式可能有问题");
                    return;
                }
                //在有查询结果时查找值
                if (!responseJObject["full"].ToString().Equals("0"))
                {
                    if (!responseJObject["full"].ToString().Equals("1"))
                    {
                        QQGroup.SendGroupMessage("查询到多个公会,可能存在重名或关键词错误");
                    }
                    string rank       = responseJObject["data"]?[0]?["rank"]?.ToString();
                    string totalScore = responseJObject["data"]?[0]?["damage"]?.ToString();
                    string leaderName = responseJObject["data"]?[0]?["leader_name"]?.ToString();
                    ConsoleLog.Info("JSON处理成功", "向用户发送数据");
                    QQGroup.SendGroupMessage("查询成功!\n" +
                                             $"公会  |{guildName}\n" +
                                             $"排名  |{rank}\n" +
                                             $"总分数|{totalScore}\n" +
                                             $"会长  |{leaderName}\n" +
                                             "如果查询到的信息有误,有可能关键词错误或公会排名在20060之后");
                }
                else
                {
                    QQGroup.SendGroupMessage("未找到任意公会\n请检查是否查询的错误的公会名或公会排名在20060之后");
                    ConsoleLog.Info("JSON处理成功", "所查询列表为空");
                }
            }
            catch (Exception e)
            {
                QQGroup.SendGroupMessage($"在处理数据时发生了错误,请请向开发者反馈问题\n{e.Message}");
                ConsoleLog.Error("JSON数据读取错误", e);
            }
        }
Beispiel #8
0
        /// <summary>
        /// <para>从色图源获取色图</para>
        /// <para>不会支持R18的哦</para>
        /// </summary>
        /// <param name="hso">hso配置实例</param>
        private async Task GiveMeSetu(Hso hso)
        {
            string  localPicPath;
            JObject response;

            ConsoleLog.Debug("源", hso.Source);
            //本地模式
            if (hso.Source == SetuSourceType.Local)
            {
                string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath());
                if (picNames.Length == 0)
                {
                    await QQGroup.SendGroupMessage("机器人管理者没有在服务器上塞色图\r\n你去找他要啦!");

                    return;
                }
                Random randFile = new Random();
                localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}";
                ConsoleLog.Debug("发送图片", localPicPath);
                await QQGroup.SendGroupMessage(hso.CardImage
                                               ?CQCode.CQCardImage(localPicPath)
                                               : CQCode.CQImage(localPicPath));

                return;
            }
            //网络部分
            try
            {
                ConsoleLog.Info("NET", "尝试获取色图");
                await QQGroup.SendGroupMessage("正在获取色图中...");

                string apiKey;
                string serverUrl;
                //源切换
                switch (hso.Source)
                {
                case SetuSourceType.Mix:
                    Random randSource = new Random();
                    if (randSource.Next(1, 100) > 50)
                    {
                        serverUrl = "https://api.lolicon.app/setu/";
                        apiKey    = hso.LoliconApiKey ?? string.Empty;
                    }
                    else
                    {
                        serverUrl = "https://api.yukari.one/setu/";
                        apiKey    = hso.YukariApiKey ?? string.Empty;
                    }
                    break;

                case SetuSourceType.Yukari:
                    serverUrl = "https://api.yukari.one/setu/";
                    apiKey    = hso.YukariApiKey ?? string.Empty;
                    break;

                case SetuSourceType.Lolicon:
                    serverUrl = "https://api.yukari.one/setu/";
                    apiKey    = hso.YukariApiKey ?? string.Empty;
                    break;

                default:
                    await QQGroup.SendGroupMessage("发生了未知错误");

                    ConsoleLog.Error("Hso", "发生了未知错误");
                    return;
                }
                //向服务器发送请求
                ReqResponse reqResponse = await Requests.GetAsync(serverUrl, new ReqParams
                {
                    Timeout = 3000,
                    Params  = new Dictionary <string, string>
                    {
                        { "apikey", apiKey }
                    }
                });

                if (reqResponse.StatusCode != HttpStatusCode.OK)
                {
                    ConsoleLog.Error("Net", $"{serverUrl} return code {(int)reqResponse.StatusCode}");
                    await HsoEventArgs.SourceGroup.SendGroupMessage($"哇哦~发生了网络错误[{reqResponse.StatusCode}],请联系机器人所在服务器管理员");

                    return;
                }
                response = reqResponse.Json();
                ConsoleLog.Debug("Get Json", response);
            }
            catch (Exception e)
            {
                //网络错误
                await QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员");

                ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e.InnerException));
                return;
            }
            //json处理
            try
            {
                if ((int)response["code"] == 0)
                {
                    //图片链接
                    string picUrl = response["data"]?[0]?["url"]?.ToString() ?? "";
                    ConsoleLog.Debug("获取到图片", picUrl);
                    //本地图片存储路径
                    localPicPath = $"{IOUtils.GetHsoPath()}/{Path.GetFileName(picUrl)}".Replace('\\', '/');
                    if (File.Exists(localPicPath)) //检查是否已缓存过图片
                    {
                        await QQGroup.SendGroupMessage(hso.CardImage
                                                       ?CQCode.CQCardImage(localPicPath)
                                                       : CQCode.CQImage(localPicPath));
                    }
                    else
                    {
                        //文件名处理(mirai发送网络图片时pixivcat会返回403暂时无法使用代理发送图片
                        //QQGroup.SendGroupMessage(CQApi.Mirai_UrlImage(picUrl));

                        //检查是否有设置代理
                        if (!string.IsNullOrEmpty(hso.PximyProxy))
                        {
                            string[]      fileNameArgs    = Regex.Split(Path.GetFileName(picUrl), "_p");
                            StringBuilder proxyUrlBuilder = new StringBuilder();
                            proxyUrlBuilder.Append(hso.PximyProxy);
                            //图片Pid部分
                            proxyUrlBuilder.Append(hso.PximyProxy.EndsWith("/") ? $"{fileNameArgs[0]}" : $"/{fileNameArgs[0]}");
                            //图片Index部分
                            proxyUrlBuilder.Append(fileNameArgs[1].Split('.')[0].Equals("0") ? string.Empty : $"/{fileNameArgs[1].Split('.')[0]}");
                            ConsoleLog.Debug("Get Proxy Url", proxyUrlBuilder);
                            DownloadFileFromURL(proxyUrlBuilder.ToString(), localPicPath, hso.UseCache, hso.CardImage);
                        }
                        else
                        {
                            DownloadFileFromURL(picUrl, localPicPath, hso.UseCache, hso.CardImage);
                        }
                    }
                    return;
                }
                if (((int)response["code"] == 401 || (int)response["code"] == 429) &&
                    hso.Source == SetuSourceType.Lolicon)
                {
                    ConsoleLog.Warning("API Token 失效", $"code:{response["code"]}");
                }
                else
                {
                    ConsoleLog.Warning("没有找到图片信息", "服务器拒绝提供信息");
                }
                await QQGroup.SendGroupMessage("哇奧色图不见了\n请联系机器人服务器管理员");
            }
            catch (Exception e)
            {
                ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}");
            }
        }
Beispiel #9
0
        /// <summary>
        /// 下载图片保存到本地
        /// </summary>
        /// <param name="url">目标URL</param>
        /// <param name="receivePath">接收文件的地址</param>
        /// <param name="useCache">是否启用本地缓存</param>
        /// <param name="cardImg">使用装逼大图</param>
        private void DownloadFileFromURL(string url, string receivePath, bool useCache, bool cardImg)
        {
            try
            {
                int      progressPercentage = 0;
                long     bytesReceived      = 0;
                DateTime flashTime          = DateTime.Now;
                Console.WriteLine(@"开始从网络下载文件");
                WebClient client = new WebClient();
                //文件下载
                client.DownloadProgressChanged += (sender, args) =>
                {
                    if (progressPercentage == args.ProgressPercentage)
                    {
                        return;
                    }
                    progressPercentage = args.ProgressPercentage;
                    ConsoleLog
                    .Debug("Download Pic", $"Downloading {args.ProgressPercentage}% " +
                           $"({(args.BytesReceived - bytesReceived) / 1024.0 / ((DateTime.Now - flashTime).TotalMilliseconds / 1000)}KB/s) ");
                    flashTime     = DateTime.Now;
                    bytesReceived = args.BytesReceived;
                };
                //文件下载完成
                client.DownloadFileCompleted += async(sender, args) =>
                {
                    ConsoleLog.Info("Hso", "下载数据成功,发送图片");
                    var(code, _) = await QQGroup.SendGroupMessage(cardImg
                                                                  ?CQCode.CQCardImage(receivePath)
                                                                  : CQCode.CQImage(receivePath));

                    ConsoleLog.Debug("file", Path.GetFileName(receivePath));
                    if (code == APIStatusType.OK)
                    {
                        ConsoleLog.Info("Hso", "色图发送成功");
                    }
                    else
                    {
                        ConsoleLog.Error("Hso", $"色图发送失败 code={(int) code}");
                        await QQGroup.SendGroupMessage($"哇奧色图不见了\r\n色图发送失败了\r\nAPI ERROR [{code}]");
                    }
                    //检查是否出现空文件
                    if (code == APIStatusType.OK || !File.Exists(receivePath))
                    {
                        return;
                    }
                    FileInfo file = new FileInfo(receivePath);
                    ConsoleLog.Debug("File Size Check", file.Length);
                    if (file.Length != 0)
                    {
                        return;
                    }
                    ConsoleLog.Error("Hso", "色图下载失败");
                    //删除下载失败的文件
                    try
                    {
                        file.Delete();
                    }
                    catch (Exception e)
                    {
                        ConsoleLog.Error("IO", ConsoleLog.ErrorLogBuilder(e));
                    }
                };
                client.DownloadDataCompleted += async(sender, args) =>
                {
                    ConsoleLog.Info("Hso", "下载数据成功,发送图片");
                    try
                    {
                        StringBuilder ImgBase64Str = new StringBuilder();
                        ImgBase64Str.Append("base64://");
                        ImgBase64Str.Append(Convert.ToBase64String(args.Result));
                        var(code, _) = await QQGroup.SendGroupMessage(cardImg
                                                                      ?CQCode.CQCardImage(ImgBase64Str.ToString())
                                                                      : CQCode.CQImage(ImgBase64Str.ToString()));

                        if (code == APIStatusType.OK)
                        {
                            ConsoleLog.Info("Hso", "色图发送成功");
                        }
                        else
                        {
                            ConsoleLog.Error("Hso", $"色图发送失败 code={(int) code}");
                            await QQGroup.SendGroupMessage($"哇奧色图不见了\r\n色图发送失败了\r\nAPI ERROR [{code}]");
                        }
                        ConsoleLog.Debug("base64 length", ImgBase64Str.Length);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                };
                if (useCache)
                {
                    client.DownloadFileAsync(new Uri(url), receivePath);
                }
                else
                {
                    client.DownloadDataAsync(new Uri(url));
                }
            }
            catch (Exception e)
            {
                ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}");
            }
        }
Beispiel #10
0
        /// <summary>
        /// <para>从色图源获取色图</para>
        /// <para>不会支持R18的哦</para>
        /// </summary>
        /// <param name="setuSource">源类型</param>
        /// <param name="loliconToken">lolicon token</param>
        /// <param name="yukariToken">yukari token</param>
        private Task GiveMeSetu(SetuSourceType setuSource, string loliconToken = null, string yukariToken = null)
        {
            string        localPicPath;
            string        response;
            StringBuilder urlBuilder = new StringBuilder();

            ConsoleLog.Debug("源", setuSource);
            //源选择
            switch (setuSource)
            {
            //混合源
            case SetuSourceType.Mix:
                Random randSource = new Random();
                if (randSource.Next(1, 100) > 50)
                {
                    urlBuilder.Append("https://api.lolicon.app/setu/");
                    if (!string.IsNullOrEmpty(loliconToken))
                    {
                        urlBuilder.Append($"?token={loliconToken}");
                    }
                    ConsoleLog.Debug("色图源", "Lolicon");
                }
                else
                {
                    urlBuilder.Append("https://api.yukari.one/setu/");
                    if (!string.IsNullOrEmpty(yukariToken))
                    {
                        urlBuilder.Append($"?token={yukariToken}");
                    }
                    ConsoleLog.Debug("色图源", "Yukari");
                }
                break;

            //lolicon
            case SetuSourceType.Lolicon:
                urlBuilder.Append("https://api.lolicon.app/setu/");
                if (!string.IsNullOrEmpty(loliconToken))
                {
                    urlBuilder.Append($"?token={loliconToken}");
                }
                ConsoleLog.Debug("色图源", "Lolicon");
                break;

            //Yukari
            case SetuSourceType.Yukari:
                urlBuilder.Append("https://api.yukari.one/setu/");
                if (!string.IsNullOrEmpty(yukariToken))
                {
                    urlBuilder.Append($"?token={yukariToken}");
                }
                ConsoleLog.Debug("色图源", "Yukari");
                break;

            case SetuSourceType.Local:
                string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath());
                Random   randFile = new Random();
                localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}";
                ConsoleLog.Debug("发送图片", localPicPath);
                QQGroup.SendGroupMessage(CQApi.CQCode_Image(localPicPath));
                return(Task.CompletedTask);
            }
            //网络部分
            try
            {
                ConsoleLog.Info("NET", "尝试获取色图");
                QQGroup.SendGroupMessage("正在获取色图中...");
                response = HTTPUtils.GetHttpResponse(urlBuilder.ToString());
                ConsoleLog.Debug("Get Json", response);
                if (string.IsNullOrEmpty(response))//没有获取到任何返回
                {
                    ConsoleLog.Error("网络错误", "获取到的响应数据为空");
                    HsoEventArgs.FromGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员");
                    return(Task.CompletedTask);
                }
            }
            catch (Exception e)
            {
                //网络错误
                QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员");
                ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e));
                return(Task.CompletedTask);
            }
            //json处理
            try
            {
                JObject picJson = JObject.Parse(response);
                if ((int)picJson["code"] == 0)
                {
                    //图片链接
                    string picUrl = picJson["data"]?[0]?["url"]?.ToString() ?? "";
                    ConsoleLog.Debug("获取到图片", picUrl);
                    //本地图片存储路径
                    localPicPath = $"{IOUtils.GetHsoPath()}/{Path.GetFileName(picUrl)}";
                    if (File.Exists(localPicPath)) //检查是否已缓存过图片
                    {
                        QQGroup.SendGroupMessage(CQApi.CQCode_Image(localPicPath));
                    }
                    else
                    {
                        //文件名处理(mirai发送网络图片时pixivcat会返回403暂时无法使用代理发送图片
                        //QQGroup.SendGroupMessage(CQApi.Mirai_UrlImage(picUrl));
                        DownloadFileFromURL(picUrl, localPicPath);
                    }
                    return(Task.CompletedTask);
                }
                if (((int)picJson["code"] == 401 || (int)picJson["code"] == 429) &&
                    setuSource == SetuSourceType.Lolicon)
                {
                    ConsoleLog.Warning("API Token 失效", $"code:{picJson["code"]}");
                }
                else
                {
                    ConsoleLog.Warning("没有找到图片信息", "服务器拒绝提供信息");
                }
                QQGroup.SendGroupMessage("哇奧色图不见了\n请联系机器人服务器管理员");
                return(Task.CompletedTask);
            }
            catch (Exception e)
            {
                ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}");
                return(Task.CompletedTask);
            }
        }
Beispiel #11
0
        /// <summary>
        /// 此方法暂时弃用改用比利比利源
        /// </summary>
        private async ValueTask KyoukaRank(string guildName)
        {
            //网络响应
            JToken response;

            //获取网络响应
            try
            {
                //获取查询结果
                Log.Info("NET", $"尝试查询[{guildName}]会站排名");
                await QQGroup.SendGroupMessage($"正在查询公会[{guildName}]的排名...");

                ReqResponse reqResponse =
                    await Requests.PostAsync("https://service-kjcbcnmw-1254119946.gz.apigw.tencentcs.com/name/0",
                                             new ReqParams
                {
                    Timeout  = 3000,
                    PostJson = new JObject
                    {
                        ["clanName"] = guildName,
                        ["history"]  = 0
                    },
                    Header = new Dictionary <HttpRequestHeader, string>
                    {
                        { HttpRequestHeader.Referer, "https://kengxxiao.github.io/Kyouka/" }
                    },
                    CustomHeader = new Dictionary <string, string>
                    {
                        { "Custom-Source", "AntiRainBot" }
                    }
                });

                //判断响应
                if (reqResponse.StatusCode != HttpStatusCode.OK)
                {
                    await
                    QQGroup
                    .SendGroupMessage($"哇哦~发生了网络错误,请联系机器人所在服务器管理员\r\n{reqResponse.StatusCode}({(int) reqResponse.StatusCode})");

                    Log.Error("网络发生错误", $"Code[{(int) reqResponse.StatusCode}]");
                    //阻止下一步处理
                    return;
                }

                //读取返回值
                response = reqResponse.Json();
                //判断空数据
                if (response == null || !response.Any())
                {
                    await QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题");

                    Log.Error("JSON数据读取错误", "从网络获取的文本为空");
                    return;
                }

                Log.Info("获取JSON成功", response);
            }
            catch (Exception e)
            {
                await QQGroup.SendGroupMessage($"哇哦~发生了网络错误,请联系机器人所在服务器管理员\n{e.Message}");

                Log.Error("网络发生错误", e);
                //阻止下一步处理
                return;
            }

            //JSON数据处理
            try
            {
                if (response["full"] == null)
                {
                    await QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题");

                    Log.Error("JSON数据读取错误", "从网络获取的JSON格式可能有问题");
                    return;
                }

                //在有查询结果时查找值
                if (!response["full"].ToString().Equals("0"))
                {
                    if (!response["full"].ToString().Equals("1"))
                    {
                        await QQGroup.SendGroupMessage("查询到多个公会,可能存在重名或关键词错误");
                    }
                    Log.Info("JSON处理成功", "向用户发送数据");
                    long.TryParse(response["ts"]?.ToString() ?? "0", out long updateTimeStamp);
                    await QQGroup.SendGroupMessage("查询成功!\n",
                                                   $"公会:{guildName}\n",
                                                   $"排名:{response["data"]?[0]?["rank"]}\n",
                                                   $"总分数:{response["data"]?[0]?["damage"]}\n",
                                                   $"会长:{response["data"]?[0]?["leader_name"]}\n",
                                                   $"数据更新时间:{updateTimeStamp.ToDateTime():MM-dd HH:mm:ss}\n",
                                                   "如果查询到的信息有误,有可能关键词错误或公会排名在20060之后");
                }
                else
                {
                    await QQGroup.SendGroupMessage("未找到任意公会\n请检查是否查询的错误的公会名或公会排名在20060之后");

                    Log.Info("JSON处理成功", "所查询列表为空");
                }
            }
            catch (Exception e)
            {
                await QQGroup.SendGroupMessage($"在处理数据时发生了错误,请请向开发者反馈问题\n{e.Message}");

                Log.Error("JSON数据读取错误", e);
            }
        }
Beispiel #12
0
        // private async void GetGuildRank(string[] commandArgs)
        // {
        //     //TODO 修改为可切换源的分发方法
        // }

        /// <summary>
        /// 从比利比利源查询排名
        /// </summary>
        private async ValueTask BiliWikiRank(string guildName)
        {
            JArray response;

            //获取响应
            try
            {
                //获取查询结果
                Log.Info("NET", $"尝试查询[{guildName}]会站排名");
                await QQGroup.SendGroupMessage($"正在查询公会[{guildName}]的排名...");

                ReqResponse reqResponse = await Requests.GetAsync("https://tools-wiki.biligame.com/pcr/getTableInfo",
                                                                  new ReqParams
                {
                    Timeout = 3000,
                    Params  = new Dictionary <string, string>
                    {
                        { "type", "search" },
                        { "search", guildName },
                        { "page", "0" }
                    }
                });

                //判断响应
                if (reqResponse.StatusCode != HttpStatusCode.OK)
                {
                    await
                    QQGroup
                    .SendGroupMessage($"哇哦~发生了网络错误,请联系机器人所在服务器管理员\r\n{reqResponse.StatusCode}({(int) reqResponse.StatusCode})");

                    Log.Error("网络发生错误", $"Code[{(int) reqResponse.StatusCode}]");
                    //阻止下一步处理
                    return;
                }

                //读取返回值
                response = new JArray(reqResponse.Text);
                Log.Info("获取JSON成功", response);
            }
            catch (Exception e)
            {
                await QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员");

                Log.Error("网络发生错误", Log.ErrorLogBuilder(e));
                //阻止下一步处理
                return;
            }

            //JSON数据处理
            try
            {
                //对返回值进行判断
                if (response.Count == 0)
                {
                    await QQGroup.SendGroupMessage("未找到任意公会\n请检查是否查询的错误的公会名或公会排名在70000之后");

                    Log.Info("JSON处理成功", "所查询列表为空");
                    return;
                }

                JArray  dataArray = JArray.Parse(response.First?.ToString() ?? "[]");
                JObject rankData  = dataArray[0].ToObject <JObject>();
                if (dataArray.Count > 1)
                {
                    await QQGroup.SendGroupMessage("查询到多个公会,可能存在重名或关键词错误");
                }
                if (rankData == null || rankData.Count == 0)
                {
                    await QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题");

                    Log.Error("JSON数据读取错误", "从网络获取的文本为空");
                    return;
                }

                string rank       = rankData["rank"]?.ToString();
                string totalScore = rankData["damage"]?.ToString();
                string leaderName = rankData["leader_name"]?.ToString();
                Log.Info("JSON处理成功", "向用户发送数据");
                await QQGroup.SendGroupMessage("查询成功!\n" +
                                               $"公会:{guildName}\n" +
                                               $"排名:{rank}\n" +
                                               $"总分数:{totalScore}\n" +
                                               $"会长:{leaderName}\n" +
                                               "如果查询到的信息有误,有可能关键词错误或公会排名在70000之后");
            }
            catch (Exception e)
            {
                await QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题");

                Log.Error("JSON数据读取错误", $"从网络获取的JSON格式无法解析{Log.ErrorLogBuilder(e)}");
            }
        }
Beispiel #13
0
        /// <summary>
        /// <para>从色图源获取色图</para>
        /// <para>不会支持R18的哦</para>
        /// </summary>
        /// <param name="hso">hso配置实例</param>
        private async Task GiveMeSetu(Hso hso)
        {
            JToken response;

            Log.Debug("源", hso.Source);
            //本地模式
            if (hso.Source.Equals("Local"))
            {
                SendLocalPic(hso);
                return;
            }

            //网络部分
            try
            {
                Log.Info("NET", "尝试获取色图");
                await QQGroup.SendGroupMessage("正在获取色图中...");

                string apiKey;
                string serverUrl;
                //源切换
                switch (hso.Source)
                {
                case "Mix":
                    Random randSource = new Random();
                    if (randSource.Next(1, 100) > 50)
                    {
                        serverUrl = "https://api.lolicon.app/setu/";
                        apiKey    = hso.LoliconApiKey ?? string.Empty;
                    }
                    else
                    {
                        serverUrl = "https://api.yukari.one/setu/";
                        apiKey    = hso.YukariApiKey ?? string.Empty;
                    }

                    break;

                case "Yukari":
                    serverUrl = "https://api.yukari.one/setu/";
                    apiKey    = hso.YukariApiKey ?? string.Empty;
                    break;

                case "Lolicon":
                    serverUrl = "https://api.yukari.one/setu/";
                    apiKey    = hso.YukariApiKey ?? string.Empty;
                    break;

                default:
                    serverUrl = hso.Source;
                    apiKey    = string.Empty;
                    break;
                }

                //向服务器发送请求
                Log.Debug("hso api server", serverUrl);
                var reqResponse = await Requests.GetAsync(serverUrl, new ReqParams
                {
                    Timeout = 3000,
                    Params  = new Dictionary <string, string>
                    {
                        { "apikey", apiKey }
                    },
                    isCheckSSLCert = hso.CheckSSLCert
                });

                if (reqResponse.StatusCode != HttpStatusCode.OK)
                {
                    Log.Error("Net", $"{serverUrl} return code {(int) reqResponse.StatusCode}");
                    await HsoEventArgs.SourceGroup
                    .SendGroupMessage($"哇哦~发生了网络错误[{reqResponse.StatusCode}],请联系机器人所在服务器管理员");

                    return;
                }

                response = reqResponse.Json();
            }
            catch (Exception e)
            {
                //网络错误
                await QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员");

                Log.Error("网络发生错误", $"{Log.ErrorLogBuilder(e)}\r\n\r\n{Utils.GetInnerExceptionMessages(e)}");
                return;
            }

            //json处理
            try
            {
                if (!int.TryParse(response["code"]?.ToString() ?? "-100", out int retCode) && retCode != 0)
                {
                    Log.Error("Hso",
                              retCode == -100
                                  ? "Server response null message"
                                  : $"Server response code {retCode}");
                    await QQGroup.SendGroupMessage("哇奧色图不见了\n请联系机器人服务器管理员");

                    return;
                }

                //图片链接
                string picUrl = response["data"]?[0]?["url"]?.ToString() ?? "";
                Log.Debug("获取到图片", picUrl);
                //本地图片存储路径
                string localPicPath = $"{IOUtils.GetHsoPath()}/{Path.GetFileName(picUrl)}".Replace('\\', '/');
                if (File.Exists(localPicPath)) //检查是否已缓存过图片
                {
                    await QQGroup.SendGroupMessage(HsoMessageBuilder(response["data"]?[0], hso.CardImage,
                                                                     localPicPath));
                }
                else
                {
                    //检查是否有设置代理
                    if (!string.IsNullOrEmpty(hso.PximyProxy))
                    {
                        string[]      fileNameArgs    = Regex.Split(Path.GetFileName(picUrl), "_p");
                        StringBuilder proxyUrlBuilder = new StringBuilder();
                        proxyUrlBuilder.Append(hso.PximyProxy);
                        //图片Pid部分
                        proxyUrlBuilder.Append(hso.PximyProxy.EndsWith("/")
                                                   ? $"{fileNameArgs[0]}"
                                                   : $"/{fileNameArgs[0]}");
                        //图片Index部分
                        proxyUrlBuilder.Append(fileNameArgs[1].Split('.')[0].Equals("0")
                                                   ? string.Empty
                                                   : $"/{fileNameArgs[1].Split('.')[0]}");
                        Log.Debug("Get Proxy Url", proxyUrlBuilder);
                        DownloadPicFromURL(proxyUrlBuilder.ToString(), response["data"]?[0], localPicPath, hso.UseCache,
                                           hso.CardImage);
                    }
                    else
                    {
                        DownloadPicFromURL(picUrl, response["data"]?[0], localPicPath, hso.UseCache, hso.CardImage);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("色图下载失败", $"网络下载数据错误\n{Log.ErrorLogBuilder(e)}");
            }
        }