/// <summary> /// 初始化消息机器人 注:必须用异步线程,否则会阻塞主线程 /// </summary> public static void InitWeChatRobot() { bool DownLoadImageResult = DownloadImage(); if (DownLoadImageResult == true) { CommonMethodCallBackHandlers.OnDownLoadQRCodeCompleted(); //下载成功 Login(); CommonDefine.GetMsgSyncKey = GetSyncKey(); while (true) { try { LogWriter.Write(string.Format("获取心跳信息..."), LogPathDefine.WeChatLogPath); KeepHeart(CommonDefine.GetMsgSyncKey); } catch (Exception ex) { LogWriter.Write(string.Format(ex.Message), LogPathDefine.ExceptionLogPath); } } } else { LogWriter.Write(string.Format("下载验证码失败,请重试..."), LogPathDefine.WeChatLogPath); throw new Exception("下载验证码失败,请重试..."); } }
/// <summary> /// 发送消息 /// </summary> /// <param name="Msg">消息体</param> /// <param name="IsAddChatList">是否添加到聊天列表</param> /// <param name="ToName">向谁发送</param> public static bool SendToOtherMsg(string Msg = "", string ToName = "") { string SendMsg = string.Empty; string LocalMsgId = MethodsHelper.GetClientMsgId(); if (!string.IsNullOrWhiteSpace(Msg)) { SendMsg = Msg; } string chaturl = UrlDefine.ChatUrl + CommonDefine.LoginResult.pass_ticket; SendMsgBodyEntity Smbe = new SendMsgBodyEntity() { BaseRequest = new BaseRequestEntity() { DeviceID = MethodsHelper.GetDeviceId(), Uin = CommonDefine.LoginResult.wxuin, Sid = CommonDefine.LoginResult.wxsid, Skey = CommonDefine.LoginResult.skey }, Msg = new SendMsgEntity() { Type = MsgTypeEnum.Text, FromUserName = CommonDefine.BaseContact.User.UserName, ToUserName = ToName, Content = Msg, LocalID = LocalMsgId, ClientMsgId = LocalMsgId } }; string PostData = JsonConvert.SerializeObject(Smbe); string Result = HttpMethods.PostData(chaturl, PostData, CommonDefine.Cookies, Encoding.UTF8, "AcceptEncoding", "gzip, deflate").ContentData.ToString(); SendMsgResultEntity Sre = JsonConvert.DeserializeObject <SendMsgResultEntity>(Result); if (Sre.BaseResponse.Ret == 0) { //消息发送成功 CommonMethodCallBackHandlers.OnSendMsgCompleted(true); return(true); } else { Console.WriteLine("发送失败:" + Result); CommonMethodCallBackHandlers.OnSendMsgCompleted(false); return(false); } }
/// <summary> /// 分析消息结构 /// </summary> /// <param name="MsgList"></param> private static void AnalyseMsg(List <AddMsgListItemEntity> MsgList) { try { //遍历所有消息项 for (int index = 0; index < MsgList.Count; index++) { AddMsgListItemEntity ali = MsgList[index]; //消息体 MsgEntity me = new MsgEntity(); //二次封装 me.IsCanAutoReply = true; // WebwxStatusNotify(ali.FromUserName, ali.ToUserName); if (ali.FromUserName == CommonDefine.BaseContact.User.UserName) { return; } //取得消息来源联系人信息 var CustomName = from item in CommonDefine.ContactsList.MemberList where item.UserName == ali.FromUserName select item; if (CustomName == null || CustomName.ToList().Count <= 0) { //当前联系人列表中找不到此用户 try { //此处进行联系人刷新 RefreshContacts(); CustomName = from item in CommonDefine.ContactsList.MemberList where item.UserName == ali.FromUserName select item; if (CustomName == null || CustomName.ToList().Count <= 0)//未找到消息来源 { return; } } catch (Exception ex) { LogWriter.Write("刷新联系人发生异常,异常信息是:" + ex.Message, LogPathDefine.ExceptionLogPath); } } MemberListItemEntity Mlie = CustomName.ToList().SingleOrDefault(); try { if (Mlie.UserName.Contains("@@")) { //群消息处理 GroupMemberEntity Gme = SelectGroupMumber(ali); if (Gme == null) { //刷新群成员 GetGroupContactsMethod(CommonDefine.ContactsList.MemberList); Gme = SelectGroupMumber(ali); } if (ali.Content.Contains(":")) { string[] a = ali.Content.Split(':'); ali.Content = Gme.NickName + ":" + a[1].Replace("<br/>", ""); } me.GroupMember = Gme; } } catch (Exception ex) { LogWriter.Write("替换群成员名称失败,异常信息为:" + ex.Message, LogPathDefine.ExceptionLogPath); } //消息列表实体 me.MsgOwer = Mlie; me.MsgContent = ali.Content; me.MsgOwerType = MsgOwerTypeEnum.AccepterMsg; me.IsCanAutoReply = Mlie.IsCanAutoReply; #region 储存消息 if (ali.MsgType == (int)MsgTypeEnum.Voice) { me.MsgType = MsgTypeEnum.Voice; //语音消息 string Url = string.Format(UrlDefine.VoiceUrl, ali.MsgId, CommonDefine.LoginResult.skey); string FileId = MethodsHelper.MsgSaveFile(DirectoryDefine.VoiceMsgPath);//获取FileId //根据FileID创建本地的语音对象 List <byte> list = HttpMethods.GetFile(Url, Environment.CurrentDirectory + "\\" + DirectoryDefine.VoiceMsgPath + "\\" + FileId + ".mp3", CommonDefine.Cookies).ContentData as List <byte>; me.MsgTime = DateTime.Now; me.FileId = FileId; me.FilePath = Environment.CurrentDirectory + "\\" + DirectoryDefine.VoiceMsgPath + "\\" + me.FileId + ".mp3"; } else if (ali.MsgType == (int)MsgTypeEnum.Picture) { me.MsgType = MsgTypeEnum.Picture; //图片消息 string Url = string.Format(UrlDefine.ImgUrlBig, ali.MsgId, CommonDefine.LoginResult.skey); string FileId = MethodsHelper.MsgSaveFile(DirectoryDefine.ImageMsgPath);//获取FileId //根据FileID创建本地的语音对象 List <byte> list = HttpMethods.GetFile(Url, Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgPath + "\\" + FileId + ".jpg", CommonDefine.Cookies).ContentData as List <byte>; //获取缩略图 HttpMethods.GetFile(string.Format(UrlDefine.ImgUrl, ali.MsgId, CommonDefine.LoginResult.skey), Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgTempPath + "\\" + FileId + ".jpg", CommonDefine.Cookies); //将下载下来的MP3文件转成Base64进行储存 //string Base64Str = Convert.ToBase64String(list.ToArray()); me.MsgTime = DateTime.Now; me.FileId = FileId; me.FilePath = Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgPath + "\\" + FileId + ".jpg";// me.FileTempPath = Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgTempPath + "\\" + FileId + ".jpg"; } else if (ali.MsgType == (int)MsgTypeEnum.Gif) { //TODO:GIF消息 me.MsgType = MsgTypeEnum.Gif; //语音消息 string Url = string.Format(UrlDefine.ImgUrlBig, ali.MsgId, CommonDefine.LoginResult.skey); string FileId = MethodsHelper.MsgSaveFile(DirectoryDefine.ImageMsgGifPath);//获取FileId HttpMethods.GetFile(Url, Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgGifPath + "\\" + FileId + ".gif", CommonDefine.Cookies); HttpMethods.GetFile(string.Format(UrlDefine.ImgUrl, ali.MsgId, CommonDefine.LoginResult.skey), Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgTempPath + "\\" + FileId + ".jpg", CommonDefine.Cookies); me.MsgTime = DateTime.Now; me.FileId = FileId; me.FilePath = Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgGifPath + "\\" + FileId + ".gif";// me.FileTempPath = Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgTempPath + "\\" + FileId + ".jpg"; } else if (ali.MsgType == (int)MsgTypeEnum.Video) { me.MsgType = MsgTypeEnum.Video; //视频消息 string Url = string.Format(UrlDefine.VideoUrl, ali.MsgId, HttpUtility.UrlEncode(CommonDefine.LoginResult.skey)); string FileId = MethodsHelper.MsgSaveFile(DirectoryDefine.VideoMsgPath);//获取FileId HttpMethods.GetFile(string.Format(UrlDefine.ImgUrl, ali.MsgId, CommonDefine.LoginResult.skey), Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgTempPath + "\\" + FileId + ".jpg", CommonDefine.Cookies); //根据FileID创建本地的语音对象 List <byte> list = HttpMethods.GetVideo(Url, Environment.CurrentDirectory + "\\" + DirectoryDefine.VideoMsgPath + "\\" + FileId + ".mp4", CommonDefine.Cookies); me.MsgTime = DateTime.Now; me.FileId = FileId; me.FilePath = Environment.CurrentDirectory + "\\" + DirectoryDefine.VideoMsgPath + "\\" + FileId + ".mp4";// me.FileTempPath = Environment.CurrentDirectory + "\\" + DirectoryDefine.ImageMsgTempPath + "\\" + FileId + ".jpg"; } else if (ali.MsgType == 1 && !string.IsNullOrWhiteSpace(ali.Url)) { //地图消息 me.MsgType = MsgTypeEnum.Map; me.MsgUrl = ali.Url; //地图消息 string Url = string.Format(UrlDefine.MapUrl, ali.MsgId); //HttpHelper.ContentType = ""; string FileId = MethodsHelper.MsgSaveFile(DirectoryDefine.MapImageMsgPath);//获取FileId //根据FileID创建本地的语音对象 HttpMethods.GetFile(Url, Environment.CurrentDirectory + "\\" + DirectoryDefine.MapImageMsgPath + "\\" + FileId + ".jpg", CommonDefine.Cookies); me.FilePath = Environment.CurrentDirectory + "\\" + DirectoryDefine.MapImageMsgPath + "\\" + FileId + ".jpg"; me.MsgTime = DateTime.Now; } else if (ali.MsgType == (int)MsgTypeEnum.SystemMsg) { me.MsgType = MsgTypeEnum.SystemMsg; me.MsgTime = DateTime.Now; } else { me.MsgType = MsgTypeEnum.Text; me.MsgTime = DateTime.Now; } LogWriter.Write(me.MsgContent.ToString(), LogPathDefine.WeChatLogPath); CommonMethodCallBackHandlers.OnReceivedMsgAnalyseMsgCompleted(me); SetAutoRepate(CommonDefine.WhiteUserList, LoadAutoReplyConfig(ConfigDefine.WeChatAutoReplyPath), me.MsgOwer.UserName, me); #endregion } } catch (Exception ex) { LogWriter.Write(ex.Message, LogPathDefine.ExceptionLogPath); } }
/// <summary> /// 登录 /// </summary> public static void Login() { string str = string.Empty; HttpMethods.ContentType = "application/json;charset=utf-8"; while (true) { if (!str.Contains("200")) { HttpResponseResult ResponseResult = HttpMethods.Get(UrlDefine.WaitingUrl(UrlDefine.Tickets), CommonDefine.Cookies, Encoding.UTF8); str = ResponseResult.ContentData.ToString(); Console.WriteLine("当前返回值是:" + str); if (str.Contains("201")) { //扫码登录中 string[] base64 = str.Split(','); CommonDefine.Base64 = base64[1]; byte[] arr = Convert.FromBase64String(CommonDefine.Base64.Replace("'", "").Replace(";", "").Trim()); File.WriteAllBytes(Environment.CurrentDirectory + "\\User.jpg", arr); MemoryStream ms = new MemoryStream(arr); BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = ms;// new FileStream(); bi.EndInit(); CommonDefine.UserImage = bi; CommonMethodCallBackHandlers.OnLoginScranQRCodeCompleted(Environment.CurrentDirectory + "\\User.jpg"); } } if (str.Contains("200")) { //扫码登录完成 LogWriter.Write("扫码登录成功...", LogPathDefine.WeChatLogPath); string[] strs = str.Split(';'); UrlDefine.LoginUrls = strs[1].Substring(strs[1].IndexOf("=\"") + 2, strs[1].Length - strs[1].IndexOf("=\"") - 3); string XmlList = HttpMethods.Get(UrlDefine.LoginUrls, CommonDefine.Cookies, Encoding.UTF8, true).ContentData.ToString(); CommonDefine.GetCookieDictionary = HttpMethods.SetCookieDictionary; CommonDefine.LoginResult = XMLHelper.DESerializer <LoginResultEntity>(XmlList); //此处可用于二次点击登录 LogWriter.Write(CommonDefine.LoginResult.wxuin, Environment.CurrentDirectory + "\\Data\\data.dat"); Random r = new Random(); BaseRequestEntity Bre = new BaseRequestEntity() { Uin = CommonDefine.LoginResult.wxuin, Sid = CommonDefine.LoginResult.wxsid, Skey = CommonDefine.LoginResult.skey, DeviceID = MethodsHelper.GetDeviceId() }; BaseRequestSubmitEntity le = new BaseRequestSubmitEntity() { BaseRequest = Bre }; string postdata = JsonConvert.SerializeObject(le); string MySelfList = HttpMethods.PostData(UrlDefine.GetLoginId + CommonDefine.LoginResult.pass_ticket, postdata, CommonDefine.Cookies, Encoding.UTF8).ContentData.ToString(); LogWriter.Write(string.Format("获取个人信息{0}...", MySelfList), LogPathDefine.WeChatLogPath); CommonDefine.BaseContact = JsonConvert.DeserializeObject <BaseContactEntity>(MySelfList); string ContentList = HttpMethods.Get(UrlDefine.GetContactUrl(CommonDefine.LoginResult.pass_ticket, CommonDefine.LoginResult.skey), CommonDefine.Cookies, Encoding.UTF8).ContentData.ToString(); CommonDefine.ContactsList = JsonConvert.DeserializeObject <ContactsListEntity>(ContentList); LogWriter.Write(string.Format("获取联系人信息{0}...", ContentList), LogPathDefine.WeChatLogPath); new Task(() => { GetGroupContactsMethod(CommonDefine.ContactsList.MemberList); }).Start(); new Task(() => { CommonDefine.ContactsList.MemberList.ForEach((p) => { p.DownloadImage(); }); }).Start(); CommonMethodCallBackHandlers.OnLoginCompleted(true); break; } Thread.Sleep(5000); } }