public bool GetCookies() { try { using (HttpWebClient httpWebClient = new HttpWebClient()) { //string address = string.Format("http://ptlogin2.qq.com/jump?ptlang=2052&clientuin={0}&clientkey={1}&u1=http%3A%2F%2Fqzone.qq.com&ADUIN={0}&ADSESSION={2}&ADTAG=CLIENT.QQ.5365_.0&ADPUBNO=26405", // QQ, Util.ToHex(TXProtocol.ClientKey, "", "{0}"), Util.GetTimeMillis(DateTime.Now)); string address = $"https://ssl.ptlogin2.qq.com/jump?pt_clientver=5593&pt_src=1&keyindex=9&ptlang=2052&clientuin={QQ}&clientkey={Util.ToHex(TXProtocol.BufServiceTicketHttp, "", "{0}")}&u1=https:%2F%2Fuser.qzone.qq.com%2F417085811%3FADUIN=417085811%26ADSESSION={Util.GetTimeMillis(DateTime.Now)}%26ADTAG=CLIENT.QQ.5593_MyTip.0%26ADPUBNO=26841&source=namecardhoverstar"; httpWebClient.Headers["User-Agent"] = _ua; string text = Encoding.UTF8.GetString(httpWebClient.DownloadData(address)); QQCookies = httpWebClient.Cookies; CookieCollection cookies = QQCookies.GetCookies(new Uri("http://qq.com")); if (cookies["skey"] != null) { string value = cookies["skey"].Value; if (!string.IsNullOrWhiteSpace(value)) { QQSKey = value; Bkn = Util.GetBkn(value); QQGtk = Util.GET_GTK(value); return(true); } } } } catch (Exception ex) { MessageLog("获取skey失败:" + ex.Message); } return(false); }
/// <summary> /// 向服务器发送 HTTP GET 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="timeout">超时时间</param> /// <param name="proxy">代理 <see cref="HttpWebClient"/> 的 <see cref="WebProxy"/></param> /// <returns></returns> public static byte[] Get(string url, WebProxy proxy) { HttpWebClient httpWebClient = new HttpWebClient(); httpWebClient.TimeOut = 5000; httpWebClient.Proxy = proxy; httpWebClient.AllowAutoRedirect = true; httpWebClient.AutoCookieMerge = true; byte[] result = httpWebClient.DownloadData(new Uri(url)); return(result); }
/// <summary> /// 测试接口是否能用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Test_Click(object sender, RoutedEventArgs e) { //获取按钮的父容器以获取Path元素 var parent = VisualTreeHelper.GetParent((UIElement)sender); string url = ((TextBox)VisualTreeHelper.GetChild(parent, 3)).Text; string path; //Path元素在父容器中是[4]个 var c = JsonSaves.Find(x => x.url == url); if (c == null) { path = ""; } else { path = c.picPath; } try { using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { string json = Encoding.UTF8.GetString(http.DownloadData(url)).Replace('', ' '); string picpath = MainSave.ImageDirectory + "\\JsonDeserizePic\\" + Guid.NewGuid() + ".png"; if (!Directory.Exists(MainSave.ImageDirectory + "\\JsonDeserizePic")) { Directory.CreateDirectory(MainSave.ImageDirectory + "\\JsonDeserizePic"); } JObject jObject = JObject.Parse(json); url = jObject.SelectToken(path).ToString(); http.CookieCollection = new System.Net.CookieCollection(); http.DownloadFile(url, picpath); parentwindow.SnackbarMessage_Show($"接口测试通过", 1); Process.Start(picpath); } } catch (Exception exc) { MainSave.CQLog.Info("Json解析", exc.Message, exc.StackTrace); parentwindow.SnackbarMessage_Show($"接口测试失败,查看日志获取详细信息", 1); } }
public bool GetQunCookies() { try { using (var httpWebClient = new HttpWebClient()) { var address = string.Format( "https://ssl.ptlogin2.qq.com/jump?pt_clientver=5509&pt_src=1&keyindex=9&clientuin={0}&clientkey={1}&u1=http%3A%2F%2Fqun.qq.com%2Fmember.html%23gid%3D168209441", QQ, Util.ToHex(TXProtocol.BufServiceTicketHttp /*QunKey*/, "", "{0}"), Util.GetTimeMillis(DateTime.Now)); httpWebClient.Headers["User-Agent"] = UA; var result = Encoding.UTF8.GetString(httpWebClient.DownloadData(address)); QunCookies = httpWebClient.Cookies; var cookies = QunCookies.GetCookies(new Uri("http://qun.qq.com")); if (cookies["skey"] != null && !string.IsNullOrWhiteSpace(cookies["skey"].Value)) { QQSkey = cookies["skey"].Value; Bkn = Util.GetBkn(cookies["skey"].Value); } var value2 = cookies["p_skey"].Value; if (!string.IsNullOrWhiteSpace(value2)) { QunPSkey = cookies["p_skey"].Value; QunGtk = Util.GET_GTK(value2); } return(true); } } catch (Exception ex) { MessageLog("获取skey失败:" + ex.Message); } return(false); }
public static ISongList GetPlatformSongList(MusicSource type, string url) { //url正则取id分析 ISongList result; try { if (type == MusicSource.Netease) { string id = new Regex("(?<=playlist\\?id=)[0-9]+").Match(url).Value; string requestUrl = "http://blog.ylz1.cn/page/music/api.php"; byte[] data = HttpWebClient.Post(requestUrl, Encoding.UTF8.GetBytes($"types=playlist&id={id}")); JObject jobj = JObject.Parse(Encoding.UTF8.GetString(data)); result = JsonConvert.DeserializeObject <NeteaseList>(jobj["playlist"].ToString()); //音乐写入 List <NeteaseMusic> musics = new List <NeteaseMusic>(); JArray playlist = JArray.Parse(jobj["playlist"]["tracks"].ToString()); foreach (var info in playlist) { //读取歌手数组 JArray ja = JArray.Parse(info["ar"].ToString()); List <string> artists = new List <string>(); foreach (var item in ja.Children()) { artists.Add(item["name"].ToString()); } //写入返回结果 musics.Add(new NeteaseMusic { Id = info["id"].ToString(), artist = artists.ToArray(), Name = info["name"].ToString(), Album = info["al"]["name"].ToString(), CoverId = info["al"]["pic_str"].ToString() }); } result.Musics = musics.ToArray(); } else if (type == MusicSource.Tencent) { //获取重定向location WebHeaderCollection whc = new WebHeaderCollection(); HttpWebClient.Get(url, "", ref whc, false); //获取location中的id string id = new Regex("(?<=id=)[0-9]+").Match(whc[HttpResponseHeader.Location]).Value; //发出请求 string requestUrl = $"https://api.qq.jsososo.com/songlist?id={id}"; byte[] data = HttpWebClient.Get(requestUrl); JObject jobj = JObject.Parse(Encoding.UTF8.GetString(data)); result = JsonConvert.DeserializeObject <TencentList>(jobj["data"].ToString()); //音乐写入 List <TencentMusic> musics = new List <TencentMusic>(); JArray playlist = JArray.Parse(jobj["data"]["songlist"].ToString()); foreach (var info in playlist) { musics.Add(JsonConvert.DeserializeObject <TencentMusic>(info.ToString())); } result.Musics = musics.ToArray(); } else { //获取歌单信息 HttpWebClient request = new HttpWebClient(); request.UserAgent = "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36"; request.AllowAutoRedirect = true; request.AutoCookieMerge = true; byte[] tmpData = request.DownloadData(new Uri(url)); string tmpR = new Regex("(?<=<script>)([\\s\\S]*?)(?=<\\/script>)").Match(Encoding.UTF8.GetString(tmpData).Replace(" ", "")).Value; string json = new Regex("(?<=phpParam=)([\\s\\S]*)(?=;)").Match(tmpR).Value; result = JsonConvert.DeserializeObject <KugouList>(json); //酷狗这歌单太乱了,需要多种方式实现 if (result is null) { //方式一 result = new KugouList { Id = Guid.NewGuid().ToString(), CoverUrl = "", Title = "酷狗歌单" }; //获取htmldata tmpData = HttpWebClient.Get(url); tmpR = new Regex("(?<=<script>)([\\s\\S]*?)(?=<\\/script>)").Match(Encoding.UTF8.GetString(tmpData).Replace(" ", "")).Value; json = new Regex("(?=\\[)([\\s\\S]*)(?<=\\])").Match(tmpR).Value; JArray playlist = JArray.Parse(json); //音乐写入 List <KugouMusic> musics = new List <KugouMusic>(); foreach (var info in playlist) { //写入返回结果 musics.Add(new KugouMusic { Id = info["hash"].ToString(), Artists = info["author_name"].ToString(), Name = info["song_name"].ToString(), //该项无法获取 Album = "" }); } result.Musics = musics.ToArray(); } else { //方式二 string reqUrl = $"http://m.kugou.com/plist/list/{result.Id}?json=true"; tmpData = HttpWebClient.Get(reqUrl); JToken jobj = JObject.Parse(Encoding.UTF8.GetString(tmpData))["list"]["list"]; int.TryParse(jobj["total"].ToString(), out int total); JArray playlist = JArray.Parse(jobj["info"].ToString()); List <KugouMusic> musics = new List <KugouMusic>(); foreach (var info in playlist) { string[] songName = info["filename"].ToString().Replace(" ", "").Split('-'); if (songName.Length != 2) { continue; } //写入返回结果 musics.Add(new KugouMusic { Id = info["hash"].ToString(), Artists = songName[0], Name = songName[1], Album = info["remark"].ToString() }); } //每一页只有30条,故循环获得 for (int i = 30; i < total; i += 30) { reqUrl = $"http://m.kugou.com/plist/list/{result.Id}?json=true&page={i / 30 + 1}"; tmpData = HttpWebClient.Get(reqUrl); jobj = JObject.Parse(Encoding.UTF8.GetString(tmpData))["list"]["list"]; playlist = JArray.Parse(jobj["info"].ToString()); foreach (var info in playlist) { string[] songName = info["filename"].ToString().Replace(" ", "").Split('-'); if (songName.Length != 2) { continue; } //写入返回结果 musics.Add(new KugouMusic { Id = info["hash"].ToString(), Artists = songName[0], Name = songName[1], Album = info["remark"].ToString() }); } } result.Musics = musics.ToArray(); } } } catch (Exception e) { throw e; } if (result is null) { throw new Exception(); } return(result); }
public int loadPagesCount(String url, Object senser) { ((Button)senser).Text = "加載頁面中..."; ((Button)senser).Enabled = false; int pagesCount = 1; byte[] byteArray; String data = ""; try { HttpWebClient title = new HttpWebClient(new CookieContainer()); title.Encoding = Encoding.UTF8; byteArray = title.DownloadData(url); data = Encoding.UTF8.GetString(byteArray); int first = data.IndexOf("<title>"); int last = data.IndexOf("</title>"); donwloadTile = data.Substring(first + 7, last - first - 7); first = data.IndexOf(">Length:</td><td class=\"gdt2\">"); last = data.IndexOf("pages</t"); string downloadAllCount = data.Substring(first + ">Length:</td><td class=\"gdt2\">".Length, last - first - ">Length:</td><td class=\"gdt2\">".Length); countall = int.Parse(downloadAllCount); Console.WriteLine(countall); } catch (Exception e) { } try { //建立該檔案目錄,若整體長度>260會錯誤! String folder = System.Environment.CurrentDirectory + "\\DownloadFile\\" + donwloadTile; if (folder.Length > 250) { donwloadTile = DateTime.Now.ToString("yyyy-MM-dd-hh-mm"); } donwloadTile = donwloadTile.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "").Replace("E-Hentai Galleries", ""); System.IO.Directory.CreateDirectory(System.Environment.CurrentDirectory + "\\DownloadFile\\" + donwloadTile); } catch (Exception ex) { MessageBox.Show("Please change your dir\n請修正你的檔案目錄\n因目錄總長度大於260字元"); btnGetPages.Enabled = true; btnGetPages.Text = "開始下載"; return(0); } //取得下載頁數 Pages.Clear(); Pages.Enqueue(url); try { int maxPages = 0; for (int i = 1000; i >= 0; i--) { if (data.IndexOf(url + "?p=" + i) != -1) { maxPages = i; break; } } GC.Collect(); for (int i = 1; i <= maxPages; i++) { pagesCount++; Pages.Enqueue(url + "?p=" + i); } GC.Collect(); StatusNow.Text = "成功獲取資料,頁數:" + pagesCount.ToString() + ",正在Trace中..."; //check final / char if ((url[url.Length - 1]) != '/') { url += '/'; } //取得所有p值找最大 GC.Collect(); Console.WriteLine(url); data = spwc.DownloadString(url, Encoding.UTF8); Console.WriteLine(data); data = spwc.DownloadString(url, Encoding.UTF8); // GET NEW SESSION FIX 20160222 ret = spwc.DownloadString(url + "?nw=session", Encoding.UTF8); CookieCollection cookies = cc.GetCookies(new Uri(url)); foreach (Cookie cookie in cookies) { if (cookie.Name == "uconfig") { this.webtoken = cookie.Value; } } } catch (Exception e) { Console.WriteLine(e); } finally { newThread = new System.Threading.Thread(this.ThreadProcLoad); newThread.Start(); } return(pagesCount); }
private void ThreadDownload() { //ProcessBarState.Value = 0; ProcessBarState.Maximum = countall; //Avoid Memory Leak GC.Collect(); while (LinkURL.Count > 0) { //LoagPage HttpWebClient download = new HttpWebClient(new CookieContainer()); download.Encoding = Encoding.UTF8; byte[] byteArray = download.DownloadData(LinkURL.Dequeue()); String data = Encoding.UTF8.GetString(byteArray); if (data.Contains("Download original") && DownloadOrignChk.Checked) { //假如有大圖切到這裡 String downloadOriginal = data.Substring(data.IndexOf("https://e-hentai.org/fullimg.php?")); downloadOriginal = downloadOriginal.Substring(0, downloadOriginal.IndexOf("\"")); downloadOriginal = downloadOriginal.Replace("amp;", ""); //取得Location String str = spwc.DownloadString(downloadOriginal); WebHeaderCollection myWebHeaderCollection = spwc.ResponseHeaders; for (int i = 0; i < myWebHeaderCollection.Count; i++) { if (myWebHeaderCollection.GetKey(i) == "Location") { downloadOriginal = myWebHeaderCollection.Get(i); break; } } if (downloadOriginal.Contains("jpg")) { DownloadFunc(downloadOriginal, folder + donwloadTile + "\\" + (HackListView.Items.Count + 1).ToString() + ".jpg", progressBar1, toolStripStatusLabel1); this.HackListView.Items.Add(new ListViewItem(new String[] { (HackListView.Items.Count + 1).ToString(), downloadOriginal, ".jpg" })); } if (downloadOriginal.Contains("png")) { DownloadFunc(downloadOriginal, folder + donwloadTile + "\\" + (HackListView.Items.Count + 1).ToString() + ".png", progressBar1, toolStripStatusLabel1); this.HackListView.Items.Add(new ListViewItem(new String[] { (HackListView.Items.Count + 1).ToString(), downloadOriginal, ".png" })); } if (downloadOriginal.Contains("gif")) { DownloadFunc(downloadOriginal, folder + donwloadTile + "\\" + (HackListView.Items.Count + 1).ToString() + ".gif", progressBar1, toolStripStatusLabel1); this.HackListView.Items.Add(new ListViewItem(new String[] { (HackListView.Items.Count + 1).ToString(), downloadOriginal, ".gif" })); } } else { //切割圖片網址 Match m; string HRefPattern = "<img id.+?src=[\"'](.+?)[\"'].*?>"; try { m = Regex.Match(data, HRefPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromSeconds(1)); while (m.Success) { if (m.Groups[1].ToString().Contains("jpg")) { DownloadFunc(m.Groups[1].ToString(), folder + donwloadTile + "\\" + (HackListView.Items.Count + 1).ToString() + ".jpg", progressBar1, toolStripStatusLabel1); this.HackListView.Items.Add(new ListViewItem(new String[] { (HackListView.Items.Count + 1).ToString(), m.Groups[1].ToString(), ".jpg" })); } if (m.Groups[1].ToString().Contains("png")) { DownloadFunc(m.Groups[1].ToString(), folder + donwloadTile + "\\" + (HackListView.Items.Count + 1).ToString() + ".png", progressBar1, toolStripStatusLabel1); this.HackListView.Items.Add(new ListViewItem(new String[] { (HackListView.Items.Count + 1).ToString(), m.Groups[1].ToString(), ".png" })); } if (m.Groups[1].ToString().Contains("gif")) { DownloadFunc(m.Groups[1].ToString(), folder + donwloadTile + "\\" + (HackListView.Items.Count + 1).ToString() + ".gif", progressBar1, toolStripStatusLabel1); this.HackListView.Items.Add(new ListViewItem(new String[] { (HackListView.Items.Count + 1).ToString(), m.Groups[1].ToString(), ".gif" })); } m = m.NextMatch(); } } catch (RegexMatchTimeoutException) { Console.WriteLine("The matching operation timed out."); } } ProcessBarState.Value++; if (ProcessBarState.Value == ProcessBarState.Maximum) { MessageBox.Show("FINISH!"); btnGetPages.Enabled = true; btnGetPages.Text = "開始下載"; } } }
private void MainForm_Load(object sender, EventArgs e) { FormBackup = this; Save.FriendsList = JsonConvert.DeserializeObject <FriendsList>(SendRequest($@"{Save.url}v1/LuaApiCaller?qq={Save.curentQQ}&funcname=GetQQUserList&timeout=10", "{\"StartIndex\":0}")); Save.GroupList = JsonConvert.DeserializeObject <GroupList>(SendRequest($@"{Save.url}v1/LuaApiCaller?qq={Save.curentQQ}&funcname=GetGroupList&timeout=10", "{\"NextToken\":\"\"}")); Thread getGroupInfo_Thread = new Thread(() => { foreach (var item in Save.GroupList.TroopList) { item.GroupMemberList = JsonConvert.DeserializeObject <GroupMemberList>(SendRequest($@"{Save.url}v1/LuaApiCaller?qq={Save.curentQQ}&funcname=GetGroupUserList&timeout=10", $"{{\"GroupUin\":{item.GroupId},\"LastUin\":0}}")); } }); getGroupInfo_Thread.Start(); //根据登录时的QQ号 获取QQ昵称 string name = Save.FriendsList.Friendlist.First(x => x.FriendUin == Save.curentQQ).NickName.ToString(); Save.name = name; if (!Directory.Exists("conf")) { Directory.CreateDirectory("conf"); } if (File.Exists(LogHelper.GetLogFilePath()) is false) { LogHelper.CreateDB(); } //读取窗口相关配置 if (File.Exists(@"conf\states.json")) { AppConfig = JObject.Parse(File.ReadAllText(@"conf\states.json")); } //配置文件为空或不包含配置相关键 if (AppConfig.Count == 0 || !AppConfig.ContainsKey("Main")) { JObject config = new JObject { new JProperty("FormX", Left), new JProperty("FormY", Top), new JProperty("ShowWindow", true), new JProperty("TopMost", true), new JProperty("ExpandWindow", false) }; AppConfig.Add(new JProperty("Main", config)); File.WriteAllText(@"conf\states.json", AppConfig.ToString()); } else//存在并读取配置 { Left = Convert.ToInt32(AppConfig["Main"]["FormX"].ToString()); Top = Convert.ToInt32(AppConfig["Main"]["FormY"].ToString()); //不直接给Visable赋值是因为外部调用Show函数会覆盖对Visable的赋值 //所以在调用Show之后需要用标志位恢复对Visable的变化值 ShowFlag = bool.Parse(AppConfig["Main"]["ShowWindow"].ToString()); TopFlag = bool.Parse(AppConfig["Main"]["TopMost"].ToString()); ExpandWindow(bool.Parse(AppConfig["Main"]["ExpandWindow"].ToString())); } //设置窗口透明色, 实现窗口背景透明 this.TransparencyKey = Color.Gray; this.BackColor = Color.Gray; //隐藏日志窗口, 但不关闭 logForm.Text = $"运行日志 - {Save.curentQQ}"; logForm.Show(); logForm.Visible = false; //初始化托盘 NotifyIconHelper._NotifyIcon = notifyIcon; NotifyIconHelper.Init(); NotifyIconHelper.ShowNotifyIcon(); //载入插件 pluginManagment = new PluginManagment(); Thread thread = new Thread(() => { pluginManagment.Init(); }); thread.Start(); //将托盘右键菜单复制一份 pictureBox_Main.ContextMenu = notifyIcon.ContextMenu; //实例化圆形图片框, 实现圆形的头像 HttpWebClient http = new HttpWebClient() { TimeOut = 3000 }; byte[] data = { }; //默认头像,防止网络问题造成空头像出现 Image image = Image.FromFile(@"conf\DefaultPic.jpeg"); try { data = http.DownloadData($"http://q1.qlogo.cn/g?b=qq&nk={Save.curentQQ}&s=640"); MemoryStream ms = new MemoryStream(data); if (ms.Length > 0)//下载成功 { image = Image.FromStream(ms); } else//下载失败 { image = Image.FromFile(@"conf\DefaultPic.jpeg"); } } catch { //网络异常,图片使用默认头像 LogHelper.WriteLog("下载头像超时,重新启动程序可能解决这个问题"); } RoundPictureBox RoundpictureBox = new RoundPictureBox { Size = new Size(43, 43), SizeMode = PictureBoxSizeMode.StretchImage, Left = -1, Top = 0, ContextMenu = notifyIcon.ContextMenu }; if (image != null) { RoundpictureBox.Image = image; } //添加拖动事件 RoundpictureBox.MouseDown += pictureBox_Main_MouseDown; //显示控件, 置顶 this.Controls.Add(RoundpictureBox); RoundpictureBox.BringToFront(); RoundpictureBox.MouseDoubleClick += RoundpictureBox_MouseDoubleClick; Loaded = true; Save.LoginStatus = true; //事件处理 SocketHandler(); //置顶维护时钟,每60秒将窗口重新置顶 Timer.Interval = 60000; Timer.Tick += CheckTopMost; Timer.Start(); }
/// <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); } }
/// <summary> /// 获取魔法少女祈愿信息 /// </summary> /// <returns></returns> public static bool GetMagic() { try { //创建获取公告连接 string url = @"https://www.benghuai.com/news/getNotice"; //创建对象 HttpWebClient httpWebClient = new HttpWebClient(); //将获获取的公告转换为新的对象 NoticeRoot noticeRoot = JsonConvert.DeserializeObject <NoticeRoot>(Encoding.UTF8.GetString(httpWebClient.DownloadData(url))); //获取想要的公告id string princessid = "0"; foreach (Gach item in noticeRoot.Data.Gach) { //如果祈愿标题包含全神祈愿 if (item.title.Contains("魔法少女")) { //获取祈愿的id princessid = item.id; break; } } //创建祈愿公告的id string WishUrl = @"https://www.benghuai.com/news/getNoticeByID?id=" + princessid; //将获取的信息转成对象 QiyuanRoot qiyuanRoot = JsonConvert.DeserializeObject <QiyuanRoot>(Encoding.UTF8.GetString(httpWebClient.DownloadData(WishUrl))); //创建获取祈愿时间正则 string WishTime = @"[0-9月日 :]+~[0-9月日 :]+"; //获取祈愿时间 string PrincessTime = Regex.Match(qiyuanRoot.data.text, WishTime).Value; //判断当前活动日期是否有效 if (GetTi(PrincessTime)) { return(false); } //获取魔法少女祈愿图片 string str = Regex.Match(qiyuanRoot.data.text, @"http://static-image.benghuai.com/hsod2_webview/images/broadcast_top/bannerv2.{3,25}(jpg|JPG|png)").Value; httpWebClient.DownloadFile(str, System.Environment.CurrentDirectory + "\\data\\image\\魔法少女祈愿.jpg"); //写入魔法少女祈愿信息 StringBuilder sb = new StringBuilder(); sb.Append("【活动标题】" + "\n"); sb.Append(qiyuanRoot.data.title + "\n"); sb.Append("【活动时间】" + "\n"); sb.Append(PrincessTime + "\n"); sb.Append("活动期间,在魔法少女的祈愿中,每天都有不同的瞩目装备获得概率特别提升! 每日概率提升装备如下图:"); sb.Append("[CQ:image,file=魔法少女祈愿.jpg]"); //创建配置保存路径 string PrincessPath = Common.CqApi.GetAppDirectory() + "魔法少女祈愿.txt"; //保存内容 SaveDate(PrincessPath, sb, false); return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// 获取全神器祈愿信息 /// </summary> public static bool GetGod() { try { //创建获取公告连接 string url = @"https://www.benghuai.com/news/getNotice"; //创建对象 HttpWebClient httpWebClient = new HttpWebClient(); //将获获取的公告转换为新的对象 NoticeRoot noticeRoot = JsonConvert.DeserializeObject <NoticeRoot>(Encoding.UTF8.GetString(httpWebClient.DownloadData(url))); //获取想要的公告id string princessid = "0"; foreach (Gach item in noticeRoot.Data.Gach) { //如果祈愿标题包含全神祈愿 if (item.title.Contains("全神器")) { //获取祈愿的id princessid = item.id; break; } } //创建祈愿公告的id string WishUrl = @"https://www.benghuai.com/news/getNoticeByID?id=" + princessid; //将获取的信息转成对象 QiyuanRoot qiyuanRoot = JsonConvert.DeserializeObject <QiyuanRoot>(Encoding.UTF8.GetString(httpWebClient.DownloadData(WishUrl))); //创建获取祈愿时间正则 string WishTime = @"[0-9月日 :]+~[0-9月日 :]+"; //获取祈愿时间 string PrincessTime = Regex.Match(qiyuanRoot.data.text, WishTime).Value; //判断当前活动日期是否有效 if (GetTi(PrincessTime)) { return(false); } //保存祈愿图片 httpWebClient.DownloadFile(qiyuanRoot.data.banner_src_url, System.Environment.CurrentDirectory + "\\data\\image\\全神祈愿.jpg"); //创建获取公主装备正则 string PrincessZB = @"[\u4e00-\u9fa5a-zA-Z·-]+</td>"; //创建公主装备数组 List <string> PrincessZBstr = new List <string>(); //往数组添加装备 foreach (var item in Regex.Matches(qiyuanRoot.data.text, PrincessZB)) { PrincessZBstr.Add(item.ToString().Replace("</td>", "")); } //创建配置保存路径 string PrincessPath = Common.CqApi.GetAppDirectory() + "全神祈愿.txt"; //创建保存的内容 StringBuilder sb = new StringBuilder(); //添加内容 sb.Append("【活动标题】" + "\n"); sb.Append(qiyuanRoot.data.title + "\n"); sb.Append("【活动时间】" + "\n"); sb.Append(PrincessTime); sb.Append("[CQ:image,file=全神祈愿.jpg]"); sb.Append("【注目装备】" + "\n"); for (int i = 0; i < PrincessZBstr.Count; i++) { if (i == PrincessZBstr.Count - 1) { sb.Append(PrincessZBstr[i]); } else { sb.Append(PrincessZBstr[i] + "\n"); } } //保存内容 SaveDate(PrincessPath, sb, false); return(true); } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.Append(DateTime.Now.ToString() + "获取全神祈愿信息失败:"); sb.Append(ex.Message); //创建保存路径 string FamiliarPath = Common.CqApi.GetAppDirectory() + "ErrorLog.txt"; //保存数据 SaveDate(FamiliarPath, sb, true); return(true); } }
/// <summary> /// 获取当前魔女祈愿类型 /// </summary> /// <returns></returns> public static string GetNow() { //创建获取公告连接 string url = @"https://www.benghuai.com/news/getNotice"; //创建对象 HttpWebClient httpWebClient = new HttpWebClient(); //将获获取的公告转换为新的对象 NoticeRoot noticeRoot = JsonConvert.DeserializeObject <NoticeRoot>(Encoding.UTF8.GetString(httpWebClient.DownloadData(url))); //获取想要的公告id string princessid = "0"; foreach (Gach item in noticeRoot.Data.Gach) { //如果祈愿标题其中的 if (item.title.Contains("魔女祈愿") || item.title.Contains("使魔祈愿")) { //获取魔女祈愿的id princessid = item.id; break; } } //创建祈愿公告的id string WishUrl = @"https://www.benghuai.com/news/getNoticeByID?id=" + princessid; //将获取的信息转成对象 QiyuanRoot qiyuanRoot = JsonConvert.DeserializeObject <QiyuanRoot>(Encoding.UTF8.GetString(httpWebClient.DownloadData(WishUrl))); //如果当前是使魔祈愿 if (qiyuanRoot.data.title.Contains("使魔祈愿")) { return("使魔祈愿"); } else { return("魔女祈愿"); } }
/// <summary> /// 获取当前魔女祈愿信息并保存 /// </summary> /// <param name="ia"></param> public static void GetWitch() { try { //创建获取公告连接 string url = @"https://www.benghuai.com/news/getNotice"; //创建对象 HttpWebClient httpWebClient = new HttpWebClient(); //将获获取的公告转换为新的对象 NoticeRoot noticeRoot = JsonConvert.DeserializeObject <NoticeRoot>(Encoding.UTF8.GetString(httpWebClient.DownloadData(url))); //获取想要的公告id string princessid = "0"; foreach (Gach item in noticeRoot.Data.Gach) { //如果祈愿标题其中的 if (item.title.Contains("魔女祈愿") || item.title.Contains("使魔祈愿")) { //获取魔女祈愿的id princessid = item.id; break; } } //创建祈愿公告的id string WishUrl = @"https://www.benghuai.com/news/getNoticeByID?id=" + princessid; //将获取的信息转成对象 QiyuanRoot qiyuanRoot = JsonConvert.DeserializeObject <QiyuanRoot>(Encoding.UTF8.GetString(httpWebClient.DownloadData(WishUrl))); //创建获取祈愿时间正则 string WishTime = @"[0-9月日 :]+~[0-9月日 :]+"; //获取祈愿时间 string PrincessTime = Regex.Match(qiyuanRoot.data.text, WishTime).Value; //如果当前是使魔祈愿 if (qiyuanRoot.data.title.Contains("使魔祈愿")) { //保存祈愿图片 httpWebClient.DownloadFile(qiyuanRoot.data.banner_src_url, System.Environment.CurrentDirectory + "\\data\\image\\使魔祈愿.jpg"); //创建获取使魔祈愿信息 List <string> Str = new List <string>(); foreach (var item in Regex.Matches(qiyuanRoot.data.text, @";[\u4e00-\u9fa5a-zA-Z::·-]+&")) { Str.Add(item.ToString().Replace(";", "").Replace("&", "")); } //获取集齐(30|50)颗可合成 List <string> Strke = new List <string>(); foreach (var item in Regex.Matches(qiyuanRoot.data.text, @"集齐(30|50)颗可合成")) { Strke.Add(item.ToString()); } //保存信息 StringBuilder sb = new StringBuilder(); try { sb.Append("【活动标题】" + "\n"); sb.Append(qiyuanRoot.data.title + "\n"); sb.Append("【活动时间】" + "\n"); sb.Append(PrincessTime); sb.Append("[CQ:image,file=使魔祈愿.jpg]"); sb.Append("【第一注目素材:】" + "\n"); sb.Append(Str[0] + " >>>>" + Strke[0] + " >>>>" + Str[1] + "\n"); sb.Append("【第二注目素材:】" + "\n"); sb.Append(Str[2] + " >>>>" + Strke[1] + " >>>>" + Str[3] + "\n"); sb.Append("【其他可能获得】" + "\n"); sb.Append(Str[4] + "\n"); sb.Append(Str[5] + "\n"); sb.Append(Str[6] + "\n"); sb.Append(Str[7] + "\n"); sb.Append(Str[8] + "\n"); sb.Append(Str[9] + "\n"); sb.Append(Str[10] + "\n"); sb.Append(Str[11]); } catch (Exception) { sb.Append("保存使魔祈愿信息失败"); } //创建保存路径 string FamiliarPath = Common.CqApi.GetAppDirectory() + "使魔祈愿.txt"; //保存数据 SaveDate(FamiliarPath, sb, false); } else { //保存祈愿图片 httpWebClient.DownloadFile(qiyuanRoot.data.banner_src_url, System.Environment.CurrentDirectory + "\\data\\image\\魔女祈愿.jpg"); //获取魔女祈愿装备 List <string> Str = new List <string>(); //foreach (var item in Regex.Matches(qiyuanRoot.data.text, @";[\u4e00-\u9fa5a-zA-Z::·-]{3,}(&|<)")) //{ // Str.Add(item.ToString().Replace(";", "").Replace("&", "").Replace("<", "")); //} foreach (var item in Regex.Matches(qiyuanRoot.data.text, @" [\u4e00-\u9fa5a-zA-Z::·-]+ ")) { Str.Add(item.ToString().Replace(" ", "")); } //写入保存内容 StringBuilder sb = new StringBuilder(); try { sb.Append("【活动标题】" + "\n"); sb.Append(qiyuanRoot.data.title + "\n"); sb.Append("【活动时间】" + "\n"); sb.Append(PrincessTime); sb.Append("[CQ:image,file=魔女祈愿.jpg]"); sb.Append("【注目装备】" + "\n"); for (int i = 0; i < Str.Count; i++) { if (i == Str.Count - 1) { sb.Append(Str[i]); } else { sb.Append(Str[i] + "\n"); } } } catch (Exception) { sb.Append("写入魔女祈愿信息失败"); } //创建保存路径 string FamiliarPath = Common.CqApi.GetAppDirectory() + "魔女祈愿.txt"; //保存数据 SaveDate(FamiliarPath, sb, false); } } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.Append(DateTime.Now.ToString() + "获取魔女祈愿信息失败:"); sb.Append(ex.Message); //创建保存路径 string FamiliarPath = Common.CqApi.GetAppDirectory() + "ErrorLog.txt"; //保存数据 SaveDate(FamiliarPath, sb, true); } }