public static CQCode GetIllustPic(Pixiv_PID info) { string path = Path.Combine(Environment.CurrentDirectory, "data", "image", "LoliconPic", $"{info.data.id}.jpg"); string pathcqcode = Path.Combine("LoliConPic", $"{info.data.id}.jpg"); using (HttpWebClient http = new HttpWebClient()) { http.TimeOut = 5000; try { if (!File.Exists(path)) { string url = string.Empty; url = info.data.imageUrls[0].original.Replace("pximg.net", "pixiv.cat"); http.DownloadFile(url, path); CommonHelper.AntiHX(path); MainSave.CQLog.Info("插画详情", "图片下载成功,正在尝试发送"); } } catch (Exception e) { MainSave.CQLog.Info("插画详情", $"图片下载失败,错误信息:{e.Message}"); return(CQApi.CQCode_Image("Error.jpg")); } } return(CQApi.CQCode_Image(pathcqcode)); }
public string Handler(CQGroupMessageEventArgs e, Base_SQLHelper.SQLHelperData b) { if (SQL.UserExists(b, e.FromQQ)) { SQL.AddFavorEveryChat(b, e.FromQQ); } return(CQApi.CQCode_Image("pixiv/" + new Base_FileHelper().RandomGetImg("data/image/pixiv")).ToString()); }
private string GetResultStr(bool sendImg = false) { string rs; int star3Count = 0; int star2Count = 0; int star1Count = 0; int pigStone = 0; string star3Name = string.Empty; if (GetResult.ContainsKey(1) && GetResult[1] != null) { foreach (var temp in GetResult[1]) { star1Count += temp.Value; pigStone += temp.Value; } } if (GetResult.ContainsKey(2) && GetResult[1] != null) { foreach (var temp in GetResult[2]) { star2Count += temp.Value; pigStone += temp.Value * 10; } } if (GetResult.ContainsKey(3) && GetResult[3] != null) { int i = 1; foreach (var temp in GetResult[3]) { star3Count += temp.Value; pigStone += temp.Value * 50; star3Name += temp.Key + "×" + temp.Value + (i++ % 3 == 0?"\n":" "); } } string ImgP = string.Empty; CQCode imgC = null; if (sendImg) { ImgP = GetResultImg(); if (ImgP != null) { imgC = CQApi.CQCode_Image(ImgP); ImgP = imgC.ToSendString(); } else { ImgP = string.Empty; } } return(rs = "素敵な仲間が増えますよ!\n" + ImgP + MyString.str["恭喜骑士君获得"] + "\n" + star3Name + "\n" + "★★★×" + star3Count + "★★×" + star2Count + "★×" + star1Count + "\n" + MyString.str["获得母猪石×"] + pigStone); }
public FunctionResult Progress(CQGroupMessageEventArgs e) { FunctionResult result = new FunctionResult { Result = true, SendFlag = true, }; SendText sendText = new SendText { SendID = e.FromGroup, }; //检查额度限制 if (QuotaHelper.QuotaCheck(e.FromGroup, e.FromQQ) is false) { return(result); } try { string tagName = e.Message.Text.Substring(GetOrderStr().Length).Trim(); var searchResult = TagSearch(tagName); if (searchResult.Count > 0 && searchResult[0] != 0) { int id = searchResult.OrderBy(x => Guid.NewGuid().ToString()).First(); var pic = YandeRePic.GetYandePic(id); Directory.CreateDirectory(Path.Combine(MainSave.ImageDirectory, "YandeRePic")); e.FromGroup.SendGroupMessage(pic.ToString()); using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { string fileName = Path.Combine(MainSave.ImageDirectory, "YandeRePic", $"{pic.ID}.jpg"); if (File.Exists(fileName) is false) { http.DownloadFile(pic.PicLargeURL, fileName); } } sendText.MsgToSend.Add(CQApi.CQCode_Image(Path.Combine("YandeRePic", $"{pic.ID}.jpg")).ToSendString()); } else { sendText.MsgToSend.Add("没有找到结果呢,请查看是否使用了正确的tag名称"); } } catch (Exception exc) { e.CQLog.Info("YandeReTag解析出错", $"错误信息: {exc.Message} 错误位置: {exc.StackTrace}"); sendText.MsgToSend.Add("解析出错,查看日志获取详细信息"); } result.SendObject.Add(sendText); return(result); }
public string Handler(CQGroupMessageEventArgs e, Base_SQLHelper.SQLHelperData b) { if (e.FromGroup.SetGroupMemberBanSpeak(e.FromQQ, TimeSpan.FromHours(2))) { if (SQL.UserExists(b, e.FromQQ)) { SQL.AddFavorEveryChat(b, e.FromQQ); } return(CQApi.CQCode_Image("sm/cai.jpg").ToString()); } return("臣妾做不到啊"); }
public string Handler(CQGroupMessageEventArgs e, Base_SQLHelper.SQLHelperData b) { WebClient _Dl = new WebClient(); String Filename = "rand/" + new Random().Next(10000, 99999).ToString() + ".jpg"; try { _Dl.DownloadFile("http://ssr0.cn:8000/ACG", "data/image/" + Filename); return(CQApi.CQCode_Image(Filename).ToString()); } catch { return("下载出错力"); } }
public FunctionResult Progress(CQGroupMessageEventArgs e) { FunctionResult result = new FunctionResult { Result = true, SendFlag = true, }; SendText sendText = new SendText { SendID = e.FromGroup, }; //检查额度限制 if (QuotaHelper.QuotaCheck(e.FromGroup, e.FromQQ) is false) { return(result); } try { int yandeID = Convert.ToInt32(e.Message.Text.Split(' ')[1]); var t = GetYandePic(yandeID); Directory.CreateDirectory(Path.Combine(MainSave.ImageDirectory, "YandeRePic")); e.FromGroup.SendGroupMessage(t.ToString()); using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { string fileName = Path.Combine(MainSave.ImageDirectory, "YandeRePic", $"{t.ID}.jpg"); if (File.Exists(fileName) is false) { http.DownloadFile(t.PicLargeURL, fileName); } } sendText.MsgToSend.Add(CQApi.CQCode_Image(Path.Combine("YandeRePic", $"{t.ID}.jpg")).ToSendString()); } catch (Exception exc) { e.CQLog.Info("YandeReID解析出错", $"错误信息: {exc.Message} 错误位置: {exc.StackTrace}"); sendText.MsgToSend.Add("解析出错,查看日志获取详细信息"); } result.SendObject.Add(sendText); return(result); }
private static string MakeCQImage(PicMessage.Grouppic item) { string md5 = GenerateMD5(item.FileMd5).ToUpper(); string path = $"data\\image\\{md5}.cqimg"; if (!File.Exists(path)) { IniConfig ini = new IniConfig(path); ini.Object.Add(new ISection("image")); ini.Object["image"]["md5"] = item.FileMd5; ini.Object["image"]["size"] = item.FileSize; ini.Object["image"]["url"] = item.Url; ini.Save(); } return(CQApi.CQCode_Image(md5).ToSendString()); }
public string Handler(CQGroupMessageEventArgs e, Base_SQLHelper.SQLHelperData b) { String _Order = e.Message.Text.Trim(); String _Tag = _Order.Contains("#") ? _Order.Substring(_Order.IndexOf("#") + 1).Trim():""; String Page = _Tag == "" ? new Random().Next(300).ToString():"1"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://konachan.net/post.json?limit=30&tags=underwear " + _Tag + "&page=" + Page); request.UserAgent = UA; request.Proxy = proxy; Img Infos; try { String raw = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.GetEncoding("UTF-8")).ReadToEnd(); var data = JsonConvert.DeserializeObject <Img[]>(raw); while (true) { Infos = data[new Random().Next(data.Length)]; if (Infos.rating != "e" && Infos.score > 40) { request = (HttpWebRequest)WebRequest.Create(Infos.sample_url); break; } } request.UserAgent = UA; request.Proxy = proxy; Stream FileStream = request.GetResponse().GetResponseStream(); String Filename = "rand/" + Infos.id.ToString() + "." + Infos.sample_url.Split(new char[] { '.' }).Last(); FileStream LocalImg = new FileStream("data/image/" + Filename, FileMode.OpenOrCreate, FileAccess.Write); byte[] Buff = new byte[512]; int Count = 0; while ((Count = FileStream.Read(Buff, 0, Buff.Length)) > 0) { LocalImg.Write(Buff, 0, Count); } FileStream.Close(); LocalImg.Close(); return(CQApi.CQCode_Image(Filename).ToString() + (Infos.author != "" ? "作者:" + Infos.author + "\n" : "") + (Infos.source != ""?"来源:" + Infos.source:"")); } catch { return(ErrMsg); } }
private SendText CustomAPI_Image(string orderText) { SendText sendText = new SendText(); try { //尝试拉取图片,若有多个相同的接口则随机来一个 CustomObject item = CustomAPIOrderList.Where(x => x.Order == orderText) .OrderBy(x => Guid.NewGuid().ToString()).FirstOrDefault(); sendText.HandlingFlag = item.AutoRevoke; //以后要用的路径,先生成一个 string targetdir = Path.Combine(Environment.CurrentDirectory, "data", "image", "CustomAPIPic", item.Order); if (!Directory.Exists(targetdir)) { Directory.CreateDirectory(targetdir); } string imagename = DateTime.Now.ToString("yyyyMMddHHss") + ".jpg"; string fullpath = Path.Combine(targetdir, imagename); using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { http.DownloadFile(item.URL, fullpath); } MainSave.CQLog.Info("自定义接口", $"图片下载成功,尝试发送"); //GetSetu.AntiHX(fullpath); string imagepath = Path.Combine("CustomAPIPic", item.Order, imagename); sendText.MsgToSend.Add(CQApi.CQCode_Image(imagepath).ToSendString()); return(sendText); } catch (Exception exc) { sendText.MsgToSend.Add("自定义接口调用失败"); MainSave.CQLog.Info("自定义接口", $"调用失败,错误信息:{exc.Message}"); return(sendText); } }
/// <summary> /// 本地图片拉取 /// </summary> /// <param name="ls"></param> /// <param name="e"></param> /// <returns></returns> public static SendText LocalPic_Image(string orderText, long GroupID, long QQID) { SendText result = new SendText(); CustomObject item = LocalPicOrderList.Where(x => x.Order == orderText) .OrderBy(_ => Guid.NewGuid()).First(); result.HandlingFlag = item.AutoRevoke; try { DirectoryInfo directoryInfo = new DirectoryInfo(item.Path); FileInfo[] fileInfos = directoryInfo.GetFiles("*.*") .Where(x => x.FullName.EndsWith("jpg") || x.FullName.EndsWith("gif") || x.FullName.EndsWith("png") || x.FullName.EndsWith("bmp") || x.FullName.EndsWith("webp") || x.FullName.EndsWith("tif") || x.FullName.EndsWith("tga")).ToArray(); //随机取一个 var picinfo = fileInfos.OrderBy(_ => Guid.NewGuid()).First(); string picpathOrigin = picinfo.FullName; if (!Directory.Exists(MainSave.ImageDirectory + "\\LocalPic")) { Directory.CreateDirectory(MainSave.ImageDirectory + "\\LocalPic"); } string picpathFinal = MainSave.ImageDirectory + "\\LocalPic\\" + picinfo.Name; if (!File.Exists(picpathFinal)) { File.Copy(picpathOrigin, picpathFinal); } MainSave.CQLog.Info("本地图片接口", $"图片获取成功,尝试发送"); CommonHelper.AntiHX(picpathFinal); string imageCQCodePath = Path.Combine("LocalPic", picinfo.Name); result.MsgToSend.Add(CQApi.CQCode_Image(imageCQCodePath).ToSendString()); return(result); } catch (Exception exc) { result.MsgToSend.Add("本地图片接口调用失败"); MainSave.CQLog.Info("本地图片接口", $"调用失败,错误信息:{exc.Message}"); if (item.Usestrict) { QuotaHelper.PlusMemberQuota(GroupID, QQID); } return(result); } }
public void GroupMemberIncrease(object sender, CQGroupMemberIncreaseEventArgs e) { List <Group> grouList = ReadXml.GetGroupsData(); foreach (Group group in grouList) { if (e.FromGroup.Id == long.Parse(group.GroupNo)) { var picture = CQApi.CQCode_Image(group.ImageName).ToSendString(); var at = CQApi.CQCode_At(e.BeingOperateQQ).ToSendString(); //发送群消息 e.CQApi.SendGroupMessage(e.FromGroup, at + group.Text + (group.IsSendImage ? picture : string.Empty)); e.Handler = true; return; } } }
/// <summary> /// 收到群消息 /// </summary> /// <param name="sender">消息来源</param> /// <param name="e">事件参数</param> public void GroupMessage(object sender, CQGroupMessageEventArgs e) { CQCode cqat = e.FromQQ.CQCode_At(); //QQMessage msg = new QQMessage(e.Message.CQApi, e.Message.Id, "人精建造"); if (e.Message.Text.Length > 6 && e.Message.Text.IndexOf("人形建造", 0, 5) == 0) { try { gflelements_list = Action_MakeTdoll(e.Message); int[] index_list = new int[BUILD_NUM]; for (int i = 0; i < BUILD_NUM; i++) { index_list[i] = gflelements_list[i].Index; } CombineGraph cg = new CombineGraph(index_list); cg.CombineAvator(); CQCode cqimg = CQApi.CQCode_Image("new.png"); e.FromGroup.SendGroupMessage(cqat, cqimg); } catch (Exception) { return; } } else { //e.FromGroup.SendGroupMessage(cqat, e.Message.Text, e.Message); return; } e.Handler = true; }
public static CQCode GetSearchPic(Datum info) { string path = Path.Combine(Environment.CurrentDirectory, "data", "image", "LoliconPic", $"{info.id}.jpg"); var b = Path.GetDirectoryName(path); if (!Directory.Exists(b)) { Directory.CreateDirectory(b); } string pathcqcode = Path.Combine("LoliConPic", $"{info.id}.jpg"); using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { try { if (!File.Exists(path)) { string url = info.imageUrls[0].original.Replace("pximg.net", "pixiv.cat"); http.DownloadFile(url, path); CommonHelper.AntiHX(path); MainSave.CQLog.Info("搜索详情", "图片下载成功,正在尝试发送"); } } catch (Exception e) { MainSave.CQLog.Info("搜索详情", $"图片下载失败,错误信息:{e.Message}\n{e.StackTrace}"); return(CQApi.CQCode_Image("Error.jpg")); } } return(CQApi.CQCode_Image(pathcqcode)); }
/// <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> /// <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); } }
/// <summary> /// 生成图片,返回图片CQ码路径 /// </summary> /// <param name="cp">存放池子信息的对象</param> /// <param name="ls">抽卡结果数组</param> /// <param name="Diamond">目标水晶数目</param> /// <returns></returns> public string GeneratePic(PoolInfo cp, List <PoolContent> ls, int Diamond) { try { int x, y; x = 160; y = 190; //$@"{dir}\装备卡\框\抽卡背景.png" Image background = Image.FromFile(cp.BackgroundImg); Image img = null; Random rd = new Random(); foreach (var item in ls) { img = GenerateCard(item); background = CombinImage(background, img, x, y); if (x < 1960) { x += 300; } else { if (y == 190) { x = 160; y = 530; } else { break; } } } background = CombinImage(background, Image.FromFile(cp.InfoPicPath), 126, 960); //金币 int money = rd.Next(100000, 100000000); Image img_1 = Money(money); int Width_Gold = 1620 + (164 - img_1.Width) / 2; background = CombinImage(background, img_1, Width_Gold, Height_1); //水晶 Image img_2 = this.Diamond(Diamond); int Width_Diamond = 1975 + (111 - img_2.Width) / 2; background = CombinImage(background, img_2, Width_Diamond, Height_1); //体力 int ap_Max = rd.Next(154, 165); int ap = rd.Next(0, ap_Max); Image img_3 = AP(ap, ap_Max); int Width_AP = 1319 + (127 - img_3.Width) / 2; background = CombinImage(background, img_3, Width_AP, Height_1); //水印 Point p = new Point(1471, 813); Font font = new Font("汉仪丫丫体简", 15F); Color color = Color.FromArgb(0, 0, 0); background = AddText2Image(background, "Powered by @水银之翼", p, font, color); string name = GetDate(); if (!Directory.Exists($@"{CQSave.ImageDirectory}\\装备结果")) { Directory.CreateDirectory($@"{CQSave.ImageDirectory}\\装备结果"); } ini = new IniConfig(dir + "\\Config.ini"); ini.Load(); if (ini.Object["ExtraConfig"]["ImageFormat"].GetValueOrDefault("jpg") == "jpg") { background.Save($@"{CQSave.ImageDirectory}\\装备结果\{name}.jpg", ImageFormat.Jpeg); return(CQApi.CQCode_Image($"装备结果\\{name}.jpg").ToSendString()); } else { background.Save($@"{dir}\\装备结果\{name}.png"); return(CQApi.CQCode_Image($"装备结果\\{name}.png").ToSendString()); } } catch (Exception e) { CQSave.CQLog.Info("抽卡图片生成", $"生成错误,错误信息:{e.Message}"); return(null); } }
/// <summary> /// 获取图片 /// </summary> /// <param name="ordertext">除指令外的控制文本</param> /// <returns></returns> public static SendText GetSetuPic(string ordertext, out string objectTostring) { SendText result = new SendText(); objectTostring = String.Empty; using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { try { IniConfig ini = MainSave.ConfigMain; string url = api; //拼接Url if (PublicVariables.Lolicon_ApiSwitch) { url = api + $"apikey={PublicVariables.Lolicon_ApiKey}"; } url += GetOrderText(ordertext); if (url.Contains("r18=1") && ini.Object["R18"]["R18PicRevoke"] == "1") { GetLoliconPic.RevokeState = true;//用于后续撤回 } string json = ""; try { json = http.DownloadString(url); } catch (Exception e) { MainSave.CQLog.Info("Error", e.Message); result.MsgToSend.Add(e.Message); result.HandlingFlag = false; return(result); } //检查路径是否存在 if (!Directory.Exists(MainSave.ImageDirectory + @"\LoliconPic\")) { Directory.CreateDirectory(MainSave.ImageDirectory + @"\LoliconPic\"); } //反序列化json Setu deserialize = JsonConvert.DeserializeObject <Setu>(json); objectTostring = deserialize.ToString(); if (deserialize.code != 0)//非成功调用 { MainSave.CQLog.Info("非正常返回", json); result.MsgToSend.Add("非正常返回"); result.HandlingFlag = false; return(result); } //获取Data数组信息 var pic = deserialize.data[0]; string path = Path.Combine(MainSave.ImageDirectory, "LoliconPic", $"{pic.pid}.jpg"); if (!File.Exists(path)) { http.CookieCollection = new CookieCollection(); http.DownloadFile(pic.url, path); CommonHelper.AntiHX(path); } result.MsgToSend.Add(CQApi.CQCode_Image(@"\LoliconPic\" + pic.pid + ".jpg").ToSendString()); return(result); } catch (Exception e) { MainSave.CQLog.Info("Error", $"发生错误的对象{e.Source} , 发送错误: {e.Message}\n{e.StackTrace}"); result.MsgToSend.Add(e.Message); result.HandlingFlag = false; return(result); } } }
/// <summary> /// SauceNao调用 /// </summary> /// <param name="cqcode">图片CQ码</param> /// <param name="e"></param> public static void SauceNao_Call(CQCode cqcode, CQGroupMessageEventArgs e) { string url = "https://saucenao.com/search.php?output_type=2&api_key=56faa0cddf50860330a295e0c331be7c4b4c021f&db=999&numres=3&url="; url += CommonHelper.GetImageURL(cqcode.ToSendString()); using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { try { Directory.CreateDirectory(MainSave.ImageDirectory + "SauceNaotemp"); var result = JsonConvert.DeserializeObject <SauceNao_Result.SauceNAO>(http.DownloadString(url)); if (result == null || result.results == null || result.results.Count == 0) { e.CQLog.Info("SauceNao识图", "拉取结果失败,建议重试"); e.FromGroup.SendGroupMessage("诶嘿,网络出了点小差~"); return; } e.CQLog.Info("SauceNao识图", "结果获取成功,正在拉取缩略图"); int count = 1; result.results = result.results.Take(1).ToList(); string str = result.ToString(); foreach (var item in result.results) { try { string filename = Guid.NewGuid().ToString().ToString(); http.DownloadFile(item.header.thumbnail, $@"{MainSave.ImageDirectory}\SauceNaotemp\{filename}.jpg"); str = str.Replace($"{{{count}}}", CQApi.CQCode_Image($@"\SauceNaotemp\{filename}.jpg").ToSendString()); } catch { str = str.Replace($"{{{count}}}", item.header.thumbnail); } finally { count++; } } e.FromGroup.SendGroupMessage(str); List <int> ls = result.results.Where(x => x.data.pixiv_id.HasValue).Select(x => x.data.pixiv_id.Value).ToList(); if (ls.Count != 0) { e.FromGroup.SendGroupMessage("有Pixiv图片信息,尝试拉取原图..."); foreach (var item in ls) { try { http.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; if (!File.Exists($@"{MainSave.ImageDirectory}\LoliconPic\${item}.jpg")) { dynamic jObject = JObject.Parse(http.UploadString("https://api.pixiv.cat/v1/generate", $"p={item}")); string pixiv_url = string.Empty; try { var urllist = jObject.original_urls_proxy; pixiv_url = urllist[0]; e.FromGroup.SendGroupMessage("此图为多P图片,选择第一P下载"); MainSave.CQLog.Info("SauceNao识图", "此图为多P图片,选择第一P下载"); } catch { pixiv_url = jObject.Value <string>("original_url_proxy"); } if (!Directory.Exists($@"{MainSave.ImageDirectory}\LoliconPic")) { Directory.CreateDirectory($@"{MainSave.ImageDirectory}\LoliconPic"); } http.DownloadFile(pixiv_url, $@"{MainSave.ImageDirectory}\LoliconPic\{item}.jpg"); MainSave.CQLog.Info("SauceNao识图", $"pid={item}的图片下载成功,尝试发送"); } QQMessage staues = e.FromGroup.SendGroupMessage(CQApi.CQCode_Image($@"\LoliconPic\{item}.jpg")); } catch (Exception exc) { e.FromGroup.SendGroupMessage($"pid={item}的图片拉取失败,错误信息:{exc.Message}"); } } } } catch (Exception exc) { e.CQLog.Info("SauceNao搜图", $"搜索失败,错误信息:{exc.Message}在{exc.StackTrace}"); e.FromGroup.SendGroupMessage($"拉取失败,错误信息:{exc.Message}"); } try { string path = $@"{MainSave.ImageDirectory}\SauceNaotemp"; if (Directory.Exists(path)) { Directory.Delete(path, true); } } catch { } } }
private void getNewChapter(object sender, System.EventArgs e) { lock (lockObj) { //获取更新的书籍信息 List <Book> bookList = ReadXml.GetBooksData(); //遍历每一本书籍 foreach (Book book in bookList) { //起点最新章节 Chapter newChapter = getCatalog(book.Id); //本地存储的最新章节 Chapter latestChapter = readLatestChapter(book.Code); //如果起点的最新章节发布时间要大于本地的最新章节发布时间,说明已更新 if (latestChapter == null || DateTime.Parse(newChapter.ChapterTime) > DateTime.Parse(latestChapter.ChapterTime)) { foreach (Group g in book.Group) { CQApi.SendGroupMessage(long.Parse(g.GroupNo), (g.IsAtAll ? CQApi.CQCode_AtAll().ToSendString() + "\n" : string.Empty) + (g.IsSendImage ? CQApi.CQCode_Image(g.ImageName).ToSendString() + "\n" : string.Empty) + "最新章节:\"" + newChapter.ChapterName + "\" \n发布时间:" + newChapter.ChapterTime + " \n本章字数:" + newChapter.WordNumber); } //把最新章节信息写入本地 writeLatestChapter(newChapter, book.Code); } //本次获取的最新章节名称 LogHelper.WriteMsgInLog("书名:" + book.Name + ",章节名称:" + newChapter.ChapterName, book.Code); } } }
/// <summary> /// Json解析拉取 /// </summary> /// <param name="ls"></param> /// <param name="e"></param> /// <returns></returns> public static SendText JsonDeserize_Image(string orderText, long GroupID, long QQID) { SendText result = new SendText(); try { //尝试拉取图片,若有多个相同的接口则随机来一个 JsonToDeserize item = JsonOrderList.Where(x => x.Order == orderText) .OrderBy(x => Guid.NewGuid().ToString()).FirstOrDefault(); result.HandlingFlag = item.AutoRevoke; //以后要用的路径,先生成一个 string targetdir = Path.Combine(Environment.CurrentDirectory, "data", "image", "JsonDeserizePic", item.Order); if (!Directory.Exists(targetdir)) { Directory.CreateDirectory(targetdir); } string imagename = DateTime.Now.ToString("yyyyMMddHHss") + ".jpg"; string fullpath = Path.Combine(targetdir, imagename); using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { string url = item.url, jsonpath = item.picPath; string json = Encoding.UTF8.GetString(http.DownloadData(url)).Replace('', ' '); JObject jObject = JObject.Parse(json); if (!string.IsNullOrEmpty(item.Text)) { string str = item.Text; var c = Regex.Matches(item.Text, "<.*?>"); foreach (var item2 in c) { string path = item2.ToString().Replace("<", "").Replace(">", ""); str = str.Replace(item2.ToString(), jObject.SelectToken(path).ToString()); } MainSave.CQApi.SendGroupMessage(GroupID, str); } if (string.IsNullOrEmpty(jsonpath)) { MainSave.CQLog.Warning("Json解析接口", $"jsonPath为空,发生在 {item.url} 接口中"); return(null); } url = jObject.SelectToken(jsonpath).ToString(); http.CookieCollection = new System.Net.CookieCollection(); http.DownloadFile(url, fullpath); } MainSave.CQLog.Info("Json解析接口", $"图片下载成功,尝试发送"); //GetSetu.AntiHX(fullpath); string imagepath = Path.Combine("JsonDeserizePic", item.Order, imagename); result.MsgToSend.Add(CQApi.CQCode_Image(imagepath).ToSendString()); return(result); } catch (Exception exc) { result.MsgToSend.Add("Json解析接口调用失败"); MainSave.CQLog.Info("Json解析接口", $"调用失败,错误信息:{exc.Message}"); return(result); } }
public static void SendHimages(this string command, bool fAllowR18, Action RecordLimit, Action RecordCD, Func <object, QQMessage> SendMessage, Action <QQMessage> RevokeHimage) { string strGetHttpResponse; if (RobotInfo.UserHImageCmd.Contains(command)) { strGetHttpResponse = $@"https://api.lolicon.app/setu/?{ (RobotInfo.Size1200 ? "size1200=true" : "") }"; } else { //分割请求接口所需的参数 long lImgCount = 1; string keyword = ""; string size1200 = ""; string strR18 = "0"; #region -- R18 -- Regex rxR18 = new Regex(RobotInfo.HImageR18Cmd); foreach (Match mchR18 in rxR18.Matches(command)) { strR18 = "1"; command = command.Replace(mchR18.Value, ""); //无论是否允许R18都现将命令中的R18移除, 避免和数量混淆 } if (!fAllowR18) //如果不允许R18 { strR18 = "0"; } #endregion -- R18 -- #region -- 色图数量 -- ; string strCount = command.GetRege(RobotInfo.HImageBeginCmd, RobotInfo.HImageCountCmd, RobotInfo.HImageUnitCmd); if (!long.TryParse(strCount, out lImgCount) && !string.IsNullOrEmpty(strCount)) { lImgCount = strCount.Chinese2Num(); } if (string.IsNullOrEmpty(strCount)) { lImgCount = 1; } if (lImgCount == 0) { return; } if (lImgCount > 10) { lImgCount = 10; } #endregion -- 色图数量 -- #region -- 关键词 -- string strKeyword = command.GetRege(RobotInfo.HImageUnitCmd, RobotInfo.HImageKeywordCmd, RobotInfo.HImageEndCmd); if (!string.IsNullOrWhiteSpace(strKeyword)) { if (strKeyword.EndsWith("的")) { strKeyword = strKeyword.Substring(0, strKeyword.Length - 1); } keyword = "&keyword=" + strKeyword; } #endregion -- 关键词 -- if (RobotInfo.Size1200) { size1200 = "&size1200=true"; } strGetHttpResponse = $@"https://api.lolicon.app/setu/?num={lImgCount}&r18={strR18}{keyword}{size1200}"; } string resultValue = DataHelper.GetHttpResponse(strGetHttpResponse); JObject jo = (JObject)JsonConvert.DeserializeObject(resultValue); JToken jt = jo["data"]; if (jo["code"].ToString() == "1") { SendMessage(RobotInfo.NoResult); return; } IEnumerable <ImageUrl> enumImg = jt.Select(i => new ImageUrl(i["p"].ToString(), i["pid"].ToString(), RobotInfo.Accelerate ? RobotInfo.AccelerateUrl + i["url"].ToString() : i["url"].ToString())); if (enumImg == null) { return; } StringBuilder sbAddress = new StringBuilder(); foreach (var item in enumImg) { sbAddress.AppendLine(@"https://www.pixiv.net/artworks/" + item.ID + $" (p{item.P})"); } if (string.IsNullOrEmpty(sbAddress.ToString())) { return; } QQMessage msgUrl = SendMessage(sbAddress.ToString()); if (msgUrl.IsSuccess && RobotInfo.LimitType == "Frequency") { RecordLimit?.Invoke(); } RecordCD?.Invoke(); foreach (var pair in enumImg) { string imgPath = pair.ID + "_" + pair.P + ".png"; if (!File.Exists(imgPath) || new FileInfo(imgPath).Length == 0) { string strImageSafeName = Path.Combine(Application.StartupPath, "data", "image", imgPath); Image img = Image.FromStream(WebRequest.Create(pair.URL).GetResponse().GetResponseStream()); img.Save(strImageSafeName); img.Dispose(); RuntimeHelper.DownloadedImagesName.Add(strImageSafeName); } QQMessage msgImg; if (RobotInfo.AntiShielding) { Bitmap temp = new Bitmap(Path.Combine(Application.StartupPath, "data", "image", imgPath)); Bitmap bmp = new Bitmap(temp); temp.Dispose(); bmp.AntiShielding(); string antiPath = pair.ID + "_" + pair.P + "_AntiShielding" + ".png"; string strImageSafeName = Path.Combine(Application.StartupPath, "data", "image", antiPath); bmp.Save(strImageSafeName); msgImg = SendMessage(CQApi.CQCode_Image(antiPath)); if (msgImg.IsSuccess && RobotInfo.LimitType == "Count") { RecordLimit?.Invoke(); } if (RobotInfo.LimitType == "Frequency") { RecordLimit?.Invoke(); } try { File.Delete(strImageSafeName); } catch { RuntimeHelper.DownloadedImagesName.Add(strImageSafeName); } } else { msgImg = SendMessage(CQApi.CQCode_Image(imgPath)); } RevokeHimage?.Invoke(msgImg); } }
public static IllustInfo GetHotSearch(string keyword) { using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, Referer = "https://pixivic.net/" }) { string url = $"https://pix.ipv4.host/illustrations?illustType=illust&searchType=original&maxSanityLevel=6&page={new Random().Next(1, 6)}&keyword={HttpTool.UrlEncode(keyword)}&pageSize=10"; string returnstr = string.Empty; try { string authCode = PublicVariables.PixivicAuth; if (string.IsNullOrEmpty(authCode)) { MainSave.CQLog.Info("未填写授权码", "搜图需要在数据目录的Config.ini文件内,Config字段的PixivicAuth值内填入获取到的授权码"); throw new Exception(); } http.Encoding = Encoding.UTF8; http.Headers.Add("authorization", authCode); returnstr = http.DownloadString(url); Pixiv_HotSearch hotSearch = JsonConvert.DeserializeObject <Pixiv_HotSearch>(returnstr); IllustInfo illustInfo = new IllustInfo(); Datum info; if (hotSearch.data.Count != 0) { if (PublicVariables.R18_Flag is false) { var result = hotSearch.data.Where(x => !x.tags.Any(y => y.name.Contains("R-18"))) .OrderBy(x => Guid.NewGuid().ToString()); info = result.FirstOrDefault(); if (info != null) { if (result.Count() != hotSearch.data.Count) { if (hotSearch.data.Count != 0) { MainSave.CQLog.Info("R18拦截", $"拦截了 {hotSearch.data.Count - result.Count()} 个搜索结果"); } } illustInfo = new IllustInfo() { IllustText = Pixiv_HotSearch.GetSearchText(info), IllustCQCode = Pixiv_HotSearch.GetSearchPic(info), IllustUrl = info.imageUrls[0].original.Replace("pximg.net", "pixiv.cat") }; } else { if (hotSearch.data.Count != 0) { MainSave.CQLog.Info("R18拦截", $"拦截了 {hotSearch.data.Count} 个搜索结果"); } illustInfo = new IllustInfo() { IllustText = "设置内限制级图片,不予显示", IllustCQCode = new CQCode(CQFunction.Image, new KeyValuePair <string, string>("file", "Error.jpg")) }; return(illustInfo); } } else { info = hotSearch.data.OrderBy(x => Guid.NewGuid().ToString()).First(); illustInfo = new IllustInfo() { IllustText = Pixiv_HotSearch.GetSearchText(info), IllustCQCode = Pixiv_HotSearch.GetSearchPic(info), IllustUrl = info.imageUrls[0].original.Replace("pximg.net", "pixiv.cat"), R18_Flag = info.tags.Any(x => x.name.Contains("R-18")) }; } } else { illustInfo = new IllustInfo() { IllustText = "搜索结果为空", IllustCQCode = CQApi.CQCode_Image("Error.jpg") }; } return(illustInfo); } catch (Exception e) { if (!Directory.Exists(MainSave.AppDirectory + "error\\" + "hotsearch\\")) { Directory.CreateDirectory(MainSave.AppDirectory + "error\\" + "hotsearch\\"); } IniConfig ini = new IniConfig(MainSave.AppDirectory + "error\\" + "hotsearch\\" + $"{DateTime.Now:yyyyMMddHHss}.log"); ini.Object["Error"]["Message"] = e.Message; ini.Object["Error"]["StackTrace"] = e.StackTrace; ini.Object["Error"]["Object"] = returnstr; ini.Save(); MainSave.CQLog.Info("搜索详情", $"解析失败,错误信息:{e.Message}"); IllustInfo illustInfo = new IllustInfo() { IllustText = "解析失败,无法获取热门搜索", IllustCQCode = CQApi.CQCode_Image("Error.jpg") }; return(illustInfo); } } }
/// <summary> /// 主处理函数,负责主要流程即注册所有消息处理函数->缓存->发送处理函数返回的回复 /// </summary> /// <param name="e"></param> /// <returns></returns> public bool handle(CQGroupMessageEventArgs e) { if (!IsInit) { init(); } _GroupID = e.FromGroup; if (BlockList.Contains(_GroupID)) { return(false); //处于屏蔽列表不处理任何信息 } if (!GroupState.GroupState.ContainsKey(_GroupID)) //若缓存中不存在此群 { GroupState.AddNewGroupToList(_GroupID); //将群加入缓存 Base_SQLHelper.SQLHelperData _new = new Base_SQLHelper.SQLHelperData(); _new.Connection = new SQLiteConnection("Data Source=data/db/" + _GroupID.ToString() + ".db"); _new.command = new SQLiteCommand(); SQLPool[_GroupID] = _new; if (GroupConfig.HasConfig(_GroupID))//若存在对应ConfigINI文件则读入相关固化配置 { GroupState.GroupState[_GroupID].AllowRepeat = GroupConfig.AllowRepeat(_GroupID); GroupState.GroupState[_GroupID].AllowReply = GroupConfig.AllowReply(_GroupID); GroupState.GroupState[_GroupID].AllowR18 = GroupConfig.AllowR18(_GroupID); GroupState.GroupState[_GroupID].Admin = GroupConfig.GetAllAdmin(_GroupID); if (GroupConfig.Allowdd(_GroupID)) { dd.Add(e); } if (!GroupConfig.IsListen(_GroupID))//ConfigINI中记录为BlackList则加入屏蔽列表并退出 { BlockList.Add(_GroupID); return(false); } } else { GroupConfig.NewGroupConfig(_GroupID);//不存在ConfigINI文件则新建 } //return false;//缓存中未命中的情况下第一次不会发任何信息 } if (!GroupState.GroupState[_GroupID].AllowReply) { return(false); //不允许回复直接退出 } //正式命令处理部分 Msg = e.Message.Text.Trim(); if (rand.Next(100) > 95) {//随机无意义表情包 _GroupID.SendGroupMessage(CQApi.CQCode_Image("sm/" + new Base_FileHelper().RandomGetImg("data/image/sm"))); return(true); } if (Msg.Length < 21) {//无AT的短语句匹配注册命令 //匹配短语 //首先尝试获取称呼,若存在称呼则删去后再匹配 if (SQL.UserExists(SQLPool[_GroupID], e.FromQQ) && Msg.Contains(SQL.GetCalled(SQLPool[_GroupID], e.FromQQ))) { //TODO... } if (SimpleContainer.IsRegistered <IMsgHandler>(Msg)) { Reply = SimpleContainer.Resolve <IMsgHandler>(Msg).Handler(e, SQLPool[_GroupID]); if (Reply != "") { _GroupID.SendGroupMessage(Reply); return(true); } } } else //被AT后的处理 { if (Msg.Substring(0, 21) == @"[CQ:at,qq=3178223002]" && Msg.Length >= 22) { String Order = Msg.Substring(22).Trim(); //_GroupID.SendGroupMessage(Order.Substring(0, Order.IndexOf("#") - 1)); if (Order.Contains("#") && Order.IndexOf("#") > 0) { Order = Order.Substring(0, Order.IndexOf("#")); } if (OrderContainer.IsRegistered <IMsgHandler>(Order)) { Reply = OrderContainer.Resolve <IMsgHandler>(Order).Handler(e, SQLPool[_GroupID]); if (Reply != "") { _GroupID.SendGroupMessage(Reply); return(true); } } //return false; _GroupID.SendGroupMessage(CQApi.CQCode_Image("sm/EYHQ.jpg")); return(true); } } ///复读机部分 if (GroupState.GroupState[_GroupID].AllowRepeat) { if (GroupState.GroupState[_GroupID].LastRep != e.Message) { if (GroupState.GroupState[_GroupID].FromQQ != e.FromQQ && GroupState.GroupState[_GroupID].Msg == e.Message) { _GroupID.SendGroupMessage(e.Message); GroupState.GroupState[_GroupID].LastRep = e.Message; return(true); } } GroupState.GroupState[_GroupID].FromQQ = e.FromQQ; GroupState.GroupState[_GroupID].Msg = e.Message; } return(false); }
/// <summary> /// 获取图片详情及原图 /// </summary> /// <param name="id">图片的Pid</param> /// <returns></returns> public static IllustInfo GetIllustInfo(int id) { using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { string url = $"https://pix.ipv4.host/illusts/{id}"; string returnstr = string.Empty; try { string authCode = PublicVariables.PixivicAuth; if (string.IsNullOrEmpty(authCode)) { MainSave.CQLog.Info("未填写授权码", "搜图需要在数据目录的Config.ini文件内,Config字段的PixivicAuth值内填入获取到的授权码"); throw new Exception(); } http.Encoding = Encoding.UTF8; http.Headers.Add("authorization", authCode); returnstr = http.DownloadString(url); Pixiv_PID infobase = JsonConvert.DeserializeObject <Pixiv_PID>(returnstr); bool r18_Flag = infobase.data.tags.Any(x => x.name.Contains("R-18")); if (r18_Flag && !PublicVariables.R18_Flag) { IllustInfo R18Pic = new IllustInfo() { IllustText = "设置内限制级图片,不予显示", IllustCQCode = new CQCode(CQFunction.Image, new KeyValuePair <string, string>("file", "Error.jpg")) }; return(R18Pic); } IllustInfo illustInfo = new IllustInfo() { IllustText = Pixiv_Illust.GetIllustReturnText(infobase), IllustCQCode = Pixiv_Illust.GetIllustPic(infobase), R18_Flag = r18_Flag }; illustInfo.IllustUrl = infobase.data.imageUrls[0].original.Replace("pximg.net", "pixiv.cat"); return(illustInfo); } catch (Exception e) { if (!Directory.Exists(MainSave.AppDirectory + "error\\" + "IllustInfo\\")) { Directory.CreateDirectory(MainSave.AppDirectory + "error\\" + "IllustInfo\\"); } IniConfig ini = new IniConfig(MainSave.AppDirectory + "error\\" + "IllustInfo\\" + $"{DateTime.Now:yyyyMMddHHss}.log"); ini.Object["Error"]["Message"] = e.Message; ini.Object["Error"]["StackTrace"] = e.StackTrace; ini.Object["Error"]["Object"] = returnstr; ini.Save(); MainSave.CQLog.Info("图片详情", $"解析失败,错误信息:{e.Message}"); IllustInfo illustInfo = new IllustInfo() { IllustText = "图片解析失败,作品不存在或被删除", IllustCQCode = CQApi.CQCode_Image("Error.jpg") }; return(illustInfo); } } }
public static void Poster() { posthead: Random r = new Random(Guid.NewGuid().GetHashCode()); try { if (Event_GroupMessage.ProtectCount >= 3) { Log($"trapped in bug:{ReportBUGTime},{GetTickCount()}"); if (ReportBUGTime > 0) { if (GetTickCount() >= ReportBUGTime) { Log($"Unlimited network:{Event_GroupMessage.ProtectCount}/ ms", ConsoleColor.Red); ReportBUGTime = 0; string bugr = $"{DateTime.Now.ToString()}\n" + "机器人在处理消息时发现消息流量异常,可能机器人进程被长时间挂起。" + "为了避免机器人继续处理消息导致暴走,已经切断消息处理。" + "请持有32766级别以上权限的用户发送.bugclose解除切断。" + $"\n异常消息流量:{Event_GroupMessage.ProtectCount}条/毫秒\n\n若无人协助,则切断将在{Event_GroupMessage.ProtectCount * 10}秒后解除。"; new QQ(pCQ, 1361778219).SendPrivateMessage(bugr); List <GroupInfo> gi = pCQ.GetGroupList(); foreach (GroupInfo gii in gi) { //gii.Group.SendGroupMessage(bugr); } } } Event_GroupMessage.ProtectCount--; Thread.Sleep(10000); goto posthead; } if (r.Next(0, 1000) == 88) { if (DateTime.Now.Hour >= 7 && DateTime.Now.Hour < 24) { List <GroupInfo> lg = pCQ.GetGroupList(); Event_GroupMessage.Artifical(lg[r.Next(0, lg.Count)].Group); } } //OSU if (LastOSUTime == DateTime.Now.Hour && DateTime.Now.Minute == 30) { Storage ignore = new Storage("ignore"); if (ignore.getkey("577344771", "artist") == "√") { goto NoPOSU; } LastOSUTime = (DateTime.Now.Hour + 1) % 24; Group droid = new Group(pCQ, 577344771); List <GroupMemberInfo> gml = droid.GetGroupMemberList(); GroupMemberInfo gmi = gml[r.Next(0, gml.Count)]; long qq = gmi.QQ.Id; string targett = MessagePoster.ptList[r.Next(0, MessagePoster.ptList.Count)]; ScriptDrawer.Draw("C:\\DataArrange\\PTemple\\" + targett + ".txt", MessagePoster.workpath + "\\data\\image\\" + targett + ".png", "[qq]", qq.ToString(), "[nick]", gmi.Nick, "[card]", gmi.Card == "" ? gmi.Nick : gmi.Card, "[sex]", gmi.Sex.ToString(), "[age]", gmi.Age.ToString(), "[group]", "577344771" ); droid.SendGroupMessage("现在是 " + DateTime.Now.Hour + "时30分 不整,恭喜幸运小朋友:" + CQApi.CQCode_At(qq) + "\n" + CQApi.CQCode_Image(targett + ".png")); } NoPOSU: //BlackDied if (DateTime.Now.Hour == 24 || DateTime.Now.Hour == 0) { if (DateTime.Now.Month == 3 && DateTime.Now.Day == 27) { if (!HasSendDie) { List <GroupInfo> gi = pCQ.GetGroupList(); foreach (GroupInfo gii in gi) { gii.Group.SendGroupMessage("今天。是黑嘴去世" + (DateTime.Now.Year - 2015) + "周年的日子。在这里打扰了大家,非常抱歉。\n黑嘴,名字来源于本机作者的一只狗,这只狗在本机作者的精神支柱上有很大的作用【虽然这听起来很荒唐】,它也渐渐在本机主人的脑子里逐渐扭曲抽象成了一种精神依靠。\n祝你在天堂快乐,黑嘴。 -3.27\n不接受任何对此条消息的议论。"); } HasSendDie = true; } } } //Moring Protection Storage sys = new Storage("system"); if (DateTime.Now.Hour >= 3 && DateTime.Now.Hour <= 5) { if (sys.getkey("root", "sleep") != "zzz") { sys.putkey("root", "sleep", "zzz"); QQ master = new QQ(pCQ, 1361778219); master.SendPrivateMessage("主人晚安~"); Console.Clear(); Log("[SLEEP] zzzzzzz"); logid = Guid.NewGuid().ToString(); //Application.Restart(); //System.Diagnostics.Process.Start(workpath + "\\CQA.exe", "/account 3529296290"); //System.Environment.Exit(0); } Thread.Sleep(1000); goto posthead; } if (sys.getkey("root", "sleep") == "zzz") { Log("[WAKE UP] ouch"); QQ master = new QQ(pCQ, 1361778219); master.SendPrivateMessage("主人早上好~"); sys.putkey("root", "sleep", "!!"); } Group g; //Say try { for (int i = 0; i < delays.Count; i++) { resay: delaymsg dm = delays[i]; if (GetTickCount() >= dm.time) { if (dm.voice == true) { SpeechSynthesizer reader = new SpeechSynthesizer(); string fname = GetTickCount().ToString(); reader.SetOutputToWaveFile( workpath + "\\data\\record\\say_" + fname + ".wav", new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono) ); reader.Rate = -2 + new Random(Guid.NewGuid().GetHashCode()).Next(0, 4); reader.Volume = 100; //reader.SelectVoice("Microsoft Lili"); PromptBuilder builder = new PromptBuilder(); builder.AppendText(dm.msg); Log("Speak started at :" + GetTickCount()); reader.Speak(builder); Log("Speak successfully :" + GetTickCount()); reader.Dispose(); if (dm.kind == 0) { new Group(pCQ, dm.group).SendGroupMessage(CQApi.CQCode_Record("say_" + fname + ".wav")); } else { new QQ(pCQ, dm.group).SendPrivateMessage(CQApi.CQCode_Record("say_" + fname + ".wav")); } } else { Log("Send successfully."); if (dm.kind == 0) { new Group(pCQ, dm.group).SendGroupMessage(dm.msg); } else { new QQ(pCQ, dm.group).SendPrivateMessage(dm.msg); } } delays.Remove(dm); goto resay; } } } catch { } //Undertale if (UT.targetg != 0) { if (GetTickCount() - UT.tick >= 20000) { g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, UT.targetg); if (UT.winstr == "") { g.SendGroupMessage("nobody passed round" + UT.round + ",answer:" + UT.role); } else { g.SendGroupMessage("answer:" + UT.role + "\n" + UT.winstr); } if (UT.round == 5) { string playstr = ""; for (int i = 0; i < UT.ps.Count; i++) { playstr = playstr + CQApi.CQCode_At(UT.ps[i].qq) + " " + (int)(UT.ps[i].score * 10) / 10 + " points\n"; } UT.targetg = 0; g.SendGroupMessage("game closed\n" + playstr); } else { UT.nextRound(); UT.tick = GetTickCount(); g.SendGroupMessage("round " + UT.round + "(result:20s later):" + UT.dialog); } } } //Hot Poster string fstr = ""; string estr = ""; string[] qtemp; HotMsg hhmsg = new HotMsg(); for (int s = 0; s < Manager.mHot.data.Count; s++) { hhmsg = (HotMsg)Manager.mHot.data[s]; if (DateTime.Now.Hour >= 22 && hhmsg.hasup == false && TenClockLock == false) { TenClockLock = true; Log("Annouce:" + hhmsg.group, ConsoleColor.Green); qtemp = hhmsg.banqq.Split(';'); for (int i = 0; i < qtemp.Length - 1; i++) { estr = estr + CQApi.CQCode_At(Convert.ToInt64(qtemp[i])); } qtemp = hhmsg.qq.Split(';'); for (int i = 0; i < qtemp.Length - 1; i++) { fstr = fstr + CQApi.CQCode_At(Convert.ToInt64(qtemp[i])); } hhmsg.hasup = true; g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, Convert.ToInt64(hhmsg.group)); g.SendGroupMessage(hhmsg.msg); Manager.mHot.data[s] = hhmsg; } } //Homework network string f = "0"; if (File.Exists("C:\\DataArrange\\homeworklock.bin")) { f = File.ReadAllText("C:\\DataArrange\\homeworklock.bin", Encoding.UTF8); } if (Convert.ToInt64(f) == 1) { Log("New homework recevied !", ConsoleColor.Green); f = File.ReadAllText("C:\\DataArrange\\homework.bin", Encoding.UTF8); g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, 817755769); g.SendGroupMessage("[今日作业推送消息]\n" + f + "\n————来自黑嘴稽气人的自动推送"); File.WriteAllText("C:\\DataArrange\\homeworklock.bin", "0"); } f = ""; if (File.Exists("C:\\DataArrange\\announcer.bin")) { f = File.ReadAllText("C:\\DataArrange\\announcer.bin", Encoding.UTF8); } if (f != "") { Log("Announce:" + f, ConsoleColor.Green); string[] p = f.Split('\\'); long gr = 0; if (p[0] == "class") { gr = 817755769; } if (p[0] == "inter") { gr = 554272507; } g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, gr); switch (p[1]) { case ("hlesson"): f = "今天上午的网课出炉啦~\n地址:{url}\n往期网课精彩回顾:https://space.bilibili.com/313086171/channel/detail?cid=103565 ".Replace("{url}", p[2]); break; case ("lesson"): f = "今天全天的网课出炉啦~\n地址:{url}\n往期网课精彩回顾:https://space.bilibili.com/313086171/channel/detail?cid=103565 ".Replace("{url}", p[2]); break; case ("default"): f = p[2]; break; default: Log("Unkown announce .", ConsoleColor.Red); return; } g.SendGroupMessage("[通知]\n" + f + "\n————来自黑嘴稽气人的自动推送"); File.WriteAllText("C:\\DataArrange\\announcer.bin", ""); } } catch (Exception err) { Log(err.StackTrace + "\n" + err.Message, ConsoleColor.Red); } Thread.Sleep(1000); goto posthead; }
/// <summary> /// 将消息中的东西替换为CQ码 /// </summary> /// <param name="message">原始消息</param> /// <returns></returns> public static string Start(ReceiveMessage message) { string result = string.Empty; string msg = message.CurrentPacket.Data.Content; switch (message.CurrentPacket.Data.MsgType) { case "AtMsg": { TextMessage textMessage = JsonConvert.DeserializeObject <TextMessage>(msg); result = textMessage.Content; GroupMemberList ls = JsonConvert.DeserializeObject <GroupMemberList>(WebAPI.GetGroupMemberList(message.CurrentPacket.Data.FromGroupId)); foreach (var item in textMessage.UserID) { GroupMemberList.Memberlist mem = ls.MemberList.Where(x => x.MemberUin == item).First(); foreach (var pro in mem.GetType().GetProperties()) { if (string.IsNullOrEmpty(pro.GetValue(mem).ToString())) { pro.SetValue(mem, null); } } string originStr = "@" + (mem.AutoRemark ?? mem.GroupCard ?? mem.NickName); result = result.Replace(originStr, CQApi.CQCode_At(item).ToSendString()); } break; } case "TextMsg": result = msg; break; case "PicMsg": { PicMessage picMessage = JsonConvert.DeserializeObject <PicMessage>(message.CurrentPacket.Data.Content); if (!Directory.Exists("data\\image")) { Directory.CreateDirectory("data\\image"); } result = picMessage.Content; foreach (var item in picMessage.GroupPic) { string md5 = GenerateMD5(item.FileMd5).ToUpper(); string path = $"data\\image\\{md5}.cqimg"; if (!File.Exists(path)) { IniConfig ini = new IniConfig(path); ini.Object.Add(new ISection("image")); ini.Object["image"]["md5"] = item.FileMd5; ini.Object["image"]["size"] = item.FileSize; ini.Object["image"]["url"] = item.Url; ini.Save(); } result += CQApi.CQCode_Image(md5); } break; } case "VoiceMsg": { if (!Directory.Exists("data\\record\\")) { Directory.CreateDirectory("data\\record\\"); } JObject json = JObject.Parse(msg); string url = json["Url"].ToString(); string MD5 = GenerateMD5(url); string path = "data\\record\\" + MD5 + ".silk"; if (!File.Exists(path)) { IniConfig ini = new IniConfig(path); ini.Object.Add(new ISection("record")); ini.Object["record"]["url"] = url; ini.Save(); } result = CQApi.CQCode_Record(MD5 + ".silk").ToString(); break; } } result = Regex.Replace(result, "\\[表情(\\d*)\\]", "[CQ:face,id=$1]"); foreach (var a in result) { if (a == '\ud83d' && result.IndexOf(a) != result.Length - 1) { string str = a.ToString() + result[result.IndexOf(a) + 1].ToString(); string text = ""; foreach (var item in Encoding.UTF32.GetBytes(str)) { text += item.ToString("x"); } result = result.Replace(str, CQApi.CQCode_Emoji(Convert.ToInt32(text, 16)).ToString()); break; } } return(result); }