using CsharpHttpHelper; using HPSocketCS; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using PCRobot.Pack; using PCRobot.PCWechat; using PCRobot.Utils; using PCRobot.WechatApi; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Web.Caching; using System.Windows.Forms; using System.Xml; using static PCRobot.PCWechat.Wechat_Xiaoxie; using static PCRobot.WechatApi.NMHelper; namespace PCRobot { public partial class WinForm : Form { public WinForm() { InitializeComponent(); } private void WinForm_FormClosing(object sender, FormClosingEventArgs e) { var msg = MessageBox.Show("您确定要退出软件吗?\r\n退出后,已登陆的微信将会被强制关闭!", "谨慎操作", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (msg != DialogResult.Yes) e.Cancel = true; else PCWechat.WechatClient.UnInstall(); } private void PCForm_FormClosing(object sender, FormClosingEventArgs e) { if (!e.Cancel && socketClient != null && socketClient.IsConnected) { socketClient.Close(true); } } private void WinForm_SizeChanged(object sender, EventArgs e) { //判断是否选择的是最小化按钮 if (WindowState == FormWindowState.Minimized) { //托盘显示图标等于托盘图标对象 //注意notifyIcon1是控件的名字而不是对象的名字 this.易转发.Visible = true; //隐藏任务栏区图标 this.ShowInTaskbar = false; } else this.易转发.Visible = false; } private void 易转发_MouseDoubleClick(object sender, MouseEventArgs e) { this.Visible = true; this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; } public static SocketClient socketClient = null; private void button2_Click(object sender, EventArgs e) { try { if (!socketClient.IsConnected) { this.tabControl1.SelectedIndex = 1; MessageBox.Show("请先连接机器人服务器!", "友情提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } StartWechat(); //NmClient nmClient = new NmClient(); //nmClient.IniWechat(socketClient,lgCall); //nmClient.StartWechat(); //nmCore = nmClient.nmCore;WxRecvCallback } catch (Exception ex) { MessageBox.Show(ex.Message, "启动失败", MessageBoxButtons.OK, MessageBoxIcon.Error); //if (ex.Message == "微信版本") //{ // if (DialogResult.OK == MessageBox.Show($@"您的微信版本不兼容,以后请不要自己买升级微信!!!\r\n 点击确定按钮后,我们将为您还原指定的微信版本!", "微信版本异常", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)) // { // new WechatUpdate(comboBox1.SelectedItem.ToString()).ShowDialog(); // } //} } } #region 分析消息 private static readonly object SequenceLock = new object(); static HPSocketCS.TcpPackServer HP_Server = new HPSocketCS.TcpPackServer(); NMHelper nmHeler = new NMHelper(); public NMCore nmCore { get; set; } public string NewLine; public bool isReady { get; set; } = false; nmWxidInfo curWx; public void IniWechat() { if (!isReady) { try { PCWechat.Wechat_Xiaoxie.Install(); NewLine = Environment.NewLine; HP_Server.OnAccept += new ServerEvent.OnAcceptEventHandler(OnAccept); HP_Server.OnReceive += new ServerEvent.OnReceiveEventHandler(OnReceive); HP_Server.OnClose += new ServerEvent.OnCloseEventHandler(OnClose); HP_Server.MaxPackSize = 0x3FFFFF; HP_Server.IpAddress = "127.0.0.1"; HP_Server.Port = 0; if (HP_Server.Start() == true) { isReady = true; nmCore = new NMCore(HP_Server); string szIPAddress = string.Empty; ushort dwPort = 0; HP_Server.GetListenAddress(ref szIPAddress, ref dwPort); if (dwPort == 0) { //MessageBox.Show("通信端口创建失败,请重试!", "错误"); //Environment.Exit(0); } nmHeler.Socket_Port = dwPort; WriteLog("[初始化]" + NewLine + "绑定地址:" + szIPAddress + NewLine + "通信端口:" + nmHeler.Socket_Port.ToString()); } else { //MessageBox.Show("创建通信服务失败,请重试!", "错误"); //Environment.Exit(0); } //byte[] bytPath = new byte[260]; //if (NMHelper.NM_GetWeChatPath(bytPath, 260) == true) //{ // string Path = System.Text.Encoding.GetEncoding("GB2312").GetString(bytPath, 0, bytPath.Length); // text_WeChatPath.Text = Path; //} NMHelper.NM_LinkWeChat(201912121, nmHeler.Socket_Port, 0, 0); } catch (Exception) { } } } HandleResult OnAccept(IServer sender, IntPtr connId, IntPtr pClient) { try { nmCore.NM_Init((int)connId, "C#-275569550"); } catch (Exception ex) { } return HandleResult.Ok; } HandleResult OnReceive(IServer sender, IntPtr connId, byte[] bytes) { try { string s_Recv = Encoding.Default.GetString(bytes); JObject RecvJson = JObject.Parse(s_Recv); int RecvType; if (nmHeler.Json_GetInt(RecvJson, "PackType", out RecvType) == true) { if (RecvType == NMHelper.Recv_QRCode)//二维码 { Event_QRCode(RecvJson); } else if (RecvType == NMHelper.Recv_Login)//登录 { Event_Login((int)connId, RecvJson); } else if (RecvType == NMHelper.Recv_Logout) { Event_Logout((int)connId, RecvJson); } else if (RecvType == NMHelper.Recv_Msg)//消息 { Event_RecvMsg((int)connId, RecvJson); } else if (RecvType == NMHelper.Recv_SelectTalker)//切换聊天对象 { Event_SelectTalker((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_GetContactList)//获取好友列表列表 { Event_RecvContactList((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_GetGroupMember)//获取群信息 { Event_RecvGroupMember((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_GetWxidInfo)//获取群或好友详细信息 { Event_RecvWxidInfo((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_AddFriend) { Event_AddFriend((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_CreateGroup) { Event_CreateGroup((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_GetFavList) { Event_GetFavList((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_GetA8Key) { Event_GetA8Key((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_InvitePull) { Event_GroupInvite((int)connId, RecvJson); } else if (RecvType == NMHelper.NM_QuitGroup) { Event_GroupQuit((int)connId, RecvJson); } } } catch (Exception ex) { } return HandleResult.Ok; } HandleResult OnClose(IServer sender, IntPtr connId, SocketOperation enOperation, int errorCode) { try { Event_Logout((int)connId, new JObject()); } catch (Exception) { } return HandleResult.Ok; } /// /// 通信事件_接收登录二维码 /// /// void Event_QRCode(JObject RecvJson) { try { int dwPid = 0; nmHeler.Json_GetInt(RecvJson, "ProcessId", out dwPid); string B64_QRCode = nmHeler.Json_GetString(RecvJson, "QRCode", false); if (B64_QRCode != string.Empty) { byte[] imageBytes = Convert.FromBase64String(B64_QRCode); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); ms.Write(imageBytes, 0, imageBytes.Length); //pictureBox1.Image = System.Drawing.Image.FromStream(ms, true); WriteLog("[二维码]" + NewLine + "接收来自进程(PID:" + dwPid.ToString() + ")的登录二维码"); } } catch (Exception) { } } /// /// 通信事件_登录成功 /// /// /// void Event_Login(int ConnID, JObject RecvJson) { try { lock (SequenceLock) { DwPid = (IntPtr)nmHeler.Json_GetIntEx(RecvJson, "ProcessId"); NMHelper.nmWxidInfo WxidInfo = new NMHelper.nmWxidInfo(); WxidInfo.Nick = nmHeler.Json_GetString(RecvJson, "Nick", true); WxidInfo.Wxid = nmHeler.Json_GetString(RecvJson, "Wxid", true); WxidInfo.WxNo = nmHeler.Json_GetString(RecvJson, "WxNo", true); WxidInfo.HeadIMG = nmHeler.Json_GetString(RecvJson, "HeadIMG", true); WxidInfo.Sex = nmHeler.Json_GetIntEx(RecvJson, "Sex").ToString(); WxidInfo.Phone = nmHeler.Json_GetString(RecvJson, "Phone", true); WxidInfo.handle = (int)DwPid; WxidInfo.socketHandle = ConnID; curWx = WxidInfo; lgCall(curWx); GetUsers(ConnID); } } catch (Exception ex) { } } public void GetUsers(int ConnID) { nmCore.NM_GetContactList(ConnID); } Dictionary> nmWxidInfos = new Dictionary>(); /// /// 通信事件_退出登录 /// /// /// void Event_Logout(int ConnID, JObject RecvJson, bool isAll = false) { try { var nm = nms.FirstOrDefault(p => p.socketHandle == ConnID); if (nm.Wxid != null) { if (socketClient != null) { WechatStatus msg = new WechatStatus(); msg.Cmd = PCRobotCMD.offline; msg.RobotUsername = nm.Wxid; msg.RobotUsernick = nm.Nick; msg.RobotType = RobotType.客户端微信; msg.Status = Status.退出; socketClient.Send(msg); } WriteLog("[微信退出]" + NewLine + "昵称:" + nm.Nick + NewLine + "Wxid:" + nm.Wxid); if (!isAll) { nms.Remove(nm); UpdateUi(); } } //int dwRowIndex = nmHeler.FindRowIndex(list_Login, ConnID.ToString(), 0); //if (dwRowIndex != -1) //{ // if (ConnID == nmHeler.Socket_ConnId) // { // nmHeler.Socket_ConnId = 0; // groupBox1.Text = "登录列表"; // } // string szNick = list_Login.Items[dwRowIndex].SubItems[1].Text; // string szWxid = list_Login.Items[dwRowIndex].SubItems[2].Text; // list_Login.Items.RemoveAt(dwRowIndex); // WriteLog("[微信退出]" + NewLine + "昵称:" + szNick + NewLine + "Wxid:" + szWxid); //} } catch (Exception ex) { } } private List filtrationWX = new List() { "weixin" };//gh_43f2581f6fd6 //private static string[] not_delete = new string[] { "fmessage", "floatbottle", "qmessage", "medianote", "qqmail", "weixin" }; /// /// 客户端请求 /// /// public void Rcv(string str) { try { var bodyIndex = str.IndexOf(" "); if (bodyIndex == -1) return; var head = str.Substring(0, bodyIndex); var cmd = (PCRobotCMD)Enum.Parse(typeof(PCRobotCMD), head); var msg = str.Substring(bodyIndex).Trim().Replace("\r\n", "\n").Replace("[换行]", "\n"); var text = PackTool.DecompressString(msg); //str = CsharpHttpHelper.HttpHelper.URLDecode(msg).Replace("\0", "").Trim().Replace("\r\n", "\n"); //if (!str.StartsWith("{")) //{ // AESCryption aes = new AESCryption(); // str = aes.AesDecrypt(msg, socketClient.key); //} //var msgT = JObject.Parse(str); //var msg = JsonConvert.DeserializeObject(str); // var _data = HttpExtend.JsonToDictionary(str); var data = Util.JsonToObject(text) as ServerWechatMsg; if (data == null || data.Key != socketClient.key) return; var wechatUser = WechatClient.Users.FirstOrDefault(f => f.Key == data.RobotUsername.ToString()).Value; if (wechatUser != null) { //if (cmd.ToString().ToLower().StartsWith("send")) //{ // var mess = data.ToMessage; // if (cmd == PCRobotCMD.sendTxt) // mess = mess.Replace("\r\n", "\n"); // Common.SetCache(curWx.Wxid, data.ToUsername, mess); //} object obj = null; switch (cmd) { case PCRobotCMD.sendTxt: obj = new { type = MsgType.MT_SEND_TEXTMSG, data = new { to_wxid = data.ToUsername.ToString(), content = data.ToMessage } }; break; case PCRobotCMD.sendFile: case PCRobotCMD.sendImg: obj = new { type = PCRobotCMD.sendImg == cmd ? MsgType.MT_SEND_IMGMSG : MsgType.MT_SEND_FILEMSG, data = new { to_wxid = data.ToUsername.ToString(), file = data.ToMessage } }; break; case PCRobotCMD.agreeFriend: { //data.ToMessage //TODO 这还没有获取v1 v2 scene 的值 /* "data" : { "v1": "v1_xxxxxxxx@stranger", // v1 "v2": "v2_xxxxxxxx@stranger", "scene": 17 }, "type" : MT_ACCEPT_FRIEND_MSG */ var v1 = string.Empty; var v2 = string.Empty; var scene = string.Empty; obj = new { type = MsgType.MT_ACCEPT_FRIEND_MSG, data = new { v1 = v1, v2 = v2, scene = scene } }; } break; case PCRobotCMD.sendCard: obj = new { type = MsgType.MT_SEND_CARDMSG, data = new { to_wxid = data.ToUsername, card_wxid = data.ToMessage } }; break; case PCRobotCMD.getContact: obj = new { type = MsgType.MT_DATA_FRIENDS_MSG, data = new { } }; Thread.Sleep(330); obj = new { type = MsgType.MT_DATA_CHATROOMS_MSG, data = new { } }; break; case PCRobotCMD.getGroupMember: obj = new { type = MsgType.MT_DATA_CHATROOM_MEMBERS_MSG, data = new { room_wxid = data.ToMessage } }; break; case PCRobotCMD.getPay: { //var Invalidtime = 0; var Transferid = string.Empty; var dic = HttpExtend.JsonToDictionary(data.ToMessage); //if (dic.ContainsKey("Invalidtime")) // Invalidtime = int.Parse(dic["Invalidtime"].ToString()); if (dic.ContainsKey("Transferid")) Transferid = dic["Transferid"].ToString(); obj = new { type = MsgType.MT_ACCEPT_WCPAY_MSG, data = new { transferid = Transferid } }; } break; case PCRobotCMD.deleteFriend: obj = new { type = MsgType.MT_DEL_FRIEND_MSG, data = new { wxid = data.ToMessage } }; break; case PCRobotCMD.sendInviteGroup: obj = new { type = MsgType.MT_SEND_CARDMSG, data = new { to_wxid = data.ToUsername, card_wxid = data.ToMessage } }; break; case PCRobotCMD.editContacts: obj = new { type = MsgType.MT_MOD_FRIEND_REMARK_MSG, data = new { wxid = data.ToUsername, remark = data.ToMessage } }; break; case PCRobotCMD.stateOpt: obj = new { type = MsgType.MT_MOD_CHAT_SESSION_TOP_MSG, data = new { wxid = data.ToUsername, status = int.Parse(data.ToMessage) } }; break; case PCRobotCMD.getWxidInfo: obj = new { type = MsgType.MT_UPDATE_WXID_MSG, data = new { wxid = data.ToMessage } }; break; } //if (obj != null) // WechatClient.GetApi(wechatUser).SendMessage(wechatUser.Wxid.ToString(), obj); } else { var curWx = nms.FirstOrDefault(p => p.Wxid == data.RobotUsername.ToString()); if (string.IsNullOrEmpty(curWx.Wxid)) return; if (cmd.ToString().ToLower().StartsWith("send")) { var mess = data.ToMessage; if (cmd == PCRobotCMD.sendTxt) mess = mess.Replace("\r\n", "\n"); Common.SetCache(curWx.Wxid, data.ToUsername, mess); } switch (cmd) { case PCRobotCMD.sendTxt: var dataMsg = data.ToMessage.Replace("\r\n", "\n"); if (isXML(dataMsg)) { nmCore.NM_SendURLMsg(curWx.socketHandle, data.ToUsername.ToString(), dataMsg.Replace("&", "&")); } else { nmCore.NM_SendTextMsg(curWx.socketHandle, data.ToUsername.ToString(), new string[] { "" }, dataMsg); } break; case PCRobotCMD.sendFile: //文件接口 //WechatAPI.Wx_SendFileMsg(WechatAPI.Client_Handle, 3, msg.FromUsername, msg.FromMessage); //Util.Base64ToFileAndSave(data.ToMessage,) nmCore.NM_SendFileMsg(curWx.socketHandle, NMHelper.NM_SendFile, data.ToUsername.ToString(), data.ToMessage); break; case PCRobotCMD.sendImg: //byte[] ImageByte = Convert.FromBase64String(msg.FromMessage); //string temp = System.Environment.GetEnvironmentVariable("TEMP"); ////DirectoryInfo info = new DirectoryInfo(temp); //string uFile = temp + "//" + Guid.NewGuid().ToString() + ".png"; //File.WriteAllBytes(uFile, ImageByte); ////图片接口 //WechatAPI.Wx_SendFileMsg(WechatAPI.Client_Handle, 3, msg.FromUsername, uFile); nmCore.NM_SendFileMsg(curWx.socketHandle, NMHelper.NM_SendPic, data.ToUsername, data.ToMessage); break; case PCRobotCMD.sendCard: if (data.ToMessage.Contains("@")) nmCore.NM_InviteToGroup(curWx.socketHandle, NMHelper.NM_InviteURL, data.ToMessage, new string[] { data.ToUsername }); else nmCore.NM_SendCardMsg(curWx.socketHandle, data.ToUsername, data.ToMessage); break; case PCRobotCMD.sendInviteGroup: nmCore.NM_InviteToGroup(curWx.socketHandle, NMHelper.NM_InviteURL, data.ToMessage, new string[] { data.ToUsername }); break; case PCRobotCMD.getContact: nmCore.NM_GetContactList(curWx.socketHandle); break; case PCRobotCMD.getPay: { var Invalidtime = 0; var Transferid = string.Empty; var dic = HttpExtend.JsonToDictionary(data.ToMessage); if (dic.ContainsKey("Invalidtime")) Invalidtime = int.Parse(dic["Invalidtime"].ToString()); if (dic.ContainsKey("Transferid")) Transferid = dic["Transferid"].ToString(); nmCore.NM_GetMoney(curWx.socketHandle, data.ToUsername, Transferid, Invalidtime); } break; case PCRobotCMD.agreeFriend: nmCore.NM_PassApply(curWx.socketHandle, data.ToMessage); break; case PCRobotCMD.deleteFriend: nmCore.NM_DelFriend(curWx.socketHandle, data.ToMessage); break; case PCRobotCMD.getGroupMember: nmCore.NM_GetGroupMember(curWx.socketHandle, data.ToMessage); break; case PCRobotCMD.getWxidInfo: nmCore.NM_GetWxidInfo(curWx.socketHandle, string.Empty, data.ToMessage); break; case PCRobotCMD.editContacts: nmCore.NM_SetFriendMark(curWx.socketHandle, data.ToUsername, data.ToMessage); break; case PCRobotCMD.stateOpt: nmCore.NM_StateOpt(curWx.socketHandle, 2, data.ToUsername, data.ToMessage == "1"); break; //case PCRobotCMD.heartBreak: // break;` } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } /// /// 通信事件_接收消息 /// /// /// void Event_RecvMsg(int ConnID, JObject RecvJson) { try { NMHelper.nmMsgInfo MsgInfo = new NMHelper.nmMsgInfo(); MsgInfo.RecvWxid = nmHeler.Json_GetString(RecvJson, "RecvWxid", true); MsgInfo.Type = nmHeler.Json_GetIntEx(RecvJson, "Type"); MsgInfo.State = nmHeler.Json_GetIntEx(RecvJson, "State"); MsgInfo.Time = nmHeler.Json_GetIntEx(RecvJson, "Time"); MsgInfo.IsSend = nmHeler.Json_GetIntEx(RecvJson, "Sender"); MsgInfo.LocalMsgID = nmHeler.Json_GetIntEx(RecvJson, "LocalID"); MsgInfo.ServerMsgID = nmHeler.Json_GetString(RecvJson, "ServerID", false); MsgInfo.Wxid_1 = nmHeler.Json_GetString(RecvJson, "Wxid_1", true); MsgInfo.Nick_1 = nmHeler.Json_GetString(RecvJson, "Nick_1", true); MsgInfo.Wxid_2 = nmHeler.Json_GetString(RecvJson, "Wxid_2", true); MsgInfo.Nick_2 = nmHeler.Json_GetString(RecvJson, "Nick_2", true); MsgInfo.Msg = nmHeler.Json_GetString(RecvJson, "Msg", true); MsgInfo.Source = nmHeler.Json_GetString(RecvJson, "Source", true); if (filtrationWX.Contains(MsgInfo.Wxid_1)) return; string outLog = (MsgInfo.IsSend > 0 ? "[发出消息]" : "[接收消息]") + MsgInfo.RecvWxid + NewLine; outLog += "类型:" + MsgInfo.Type.ToString() + " 状态:" + MsgInfo.State.ToString() + " 时间:" + nmHeler.Timestamp2DataTime(MsgInfo.Time) + NewLine; outLog += "本地ID:" + MsgInfo.LocalMsgID.ToString() + " 服务器ID:" + MsgInfo.ServerMsgID + NewLine; outLog += "Wxid1:" + MsgInfo.Wxid_1 + (MsgInfo.Nick_1 == String.Empty ? string.Empty : "(" + MsgInfo.Nick_1 + ")") + NewLine; outLog += "Wxid2:" + MsgInfo.Wxid_2 + (MsgInfo.Nick_2 == String.Empty ? string.Empty : "(" + MsgInfo.Nick_2 + ")") + NewLine; outLog += "消息内容:" + MsgInfo.Msg + NewLine + "附加消息:" + MsgInfo.Source + NewLine; if ((MsgInfo.Type == 43 || MsgInfo.Type == 49) && MsgInfo.IsSend == 0)//视频、文件 { string FilePath = nmHeler.Json_GetString(RecvJson, "File", true); if (FilePath != string.Empty) { outLog += "文件路径:" + FilePath; if (socketClient != null) { if (File.Exists(FilePath)) { WechatReceiveMsg msg = new WechatReceiveMsg(); msg.IsSend = MsgInfo.IsSend == 1 ? true : false; msg.RobotUsername = MsgInfo.RecvWxid; msg.RobotUsernick = GetRobotNick(MsgInfo.RecvWxid); msg.RobotType = RobotType.客户端微信; msg.Cmd = PCRobotCMD.rcvFile; if (MsgInfo.Type == 43)//视频 { msg.FromMessage = $"[视频={FilePath}]"; msg.FromMessageType = WechatMsgType.视频; msg.FileCDNXML = MsgInfo.Msg; } else if (MsgInfo.Type == 49)//文件 { msg.FromMessage = $"[文件={FilePath}]"; msg.FromMessageType = WechatMsgType.文件; } if (MsgInfo.Wxid_1.Contains("@chatroom")) { msg.FromGroupid = MsgInfo.Wxid_1; msg.FromUsername = MsgInfo.Wxid_2; msg.FromUsernick = MsgInfo.Nick_2; } else if (MsgInfo.Wxid_2.Contains("@chatroom")) { msg.FromGroupid = MsgInfo.Wxid_2; msg.FromUsername = MsgInfo.Wxid_1; msg.FromUsernick = MsgInfo.Nick_1; } else { msg.FromUsername = MsgInfo.Wxid_1; msg.FromUsernick = MsgInfo.Nick_1; } if (string.IsNullOrEmpty(msg.FromUsernick) || string.IsNullOrEmpty(msg.RobotUsernick)) { var t = nms.FirstOrDefault(p => p.Wxid == MsgInfo.RecvWxid); if (t.Wxid != null) { msg.RobotUsernick = t.Nick; var m = nmWxidInfos[t.socketHandle]; if (m != null) { var tar = m.FirstOrDefault(p => p.Wxid == MsgInfo.Wxid_1); if (!string.IsNullOrEmpty(tar.Nick) && string.IsNullOrEmpty(msg.FromUsernick)) { msg.FromUsernick = tar.Nick; } } } } socketClient.Send(msg); } } } } else if ((MsgInfo.Type == 3 || MsgInfo.Type == 34) && MsgInfo.IsSend == 0)//图片、语音 { string FileData = nmHeler.Json_GetString(RecvJson, "File", false); if (FileData != string.Empty) { byte[] FileBytes = Convert.FromBase64String(FileData); string FilePath = nmHeler.SaveFile(MsgInfo.RecvWxid, MsgInfo.Wxid_1, (MsgInfo.Type == 3 ? "IMAGE" : "VOICE"), MsgInfo.ServerMsgID, (MsgInfo.Type == 3 ? "jpg" : "silk"), FileBytes); outLog += "文件路径:" + FilePath; //if (MsgInfo.Type == 3 && chk_MaxPicture.Checked == true && MsgInfo.IsSend == 0) //{ // string MaxFilePath = FilePath.Replace(MsgInfo.ServerMsgID, MsgInfo.ServerMsgID + "_MAX"); // nmCore.NM_GetImageByCDN(ConnID, MsgInfo.Msg, MaxFilePath); //} if (socketClient != null) { if (File.Exists(FilePath)) { WechatReceiveMsg msg = new WechatReceiveMsg(); //msg.IsSend = MsgInfo.IsSend == 1 ? true : false; msg.RobotUsername = MsgInfo.RecvWxid; msg.RobotUsernick = GetRobotNick(MsgInfo.RecvWxid); msg.RobotType = RobotType.客户端微信; if (MsgInfo.Type == 3)//图片 { msg.IsSend = MsgInfo.IsSend == 1 ? true : false; msg.Cmd = PCRobotCMD.rcvImg; msg.FromMessage = $"[图片={FilePath}]"; msg.FromMessageType = WechatMsgType.图片; msg.FileCDNXML = MsgInfo.Msg; } else if (MsgInfo.Type == 34)//语音 { msg.IsSend = false;//MsgInfo.IsSend == 1 ? true : false; msg.Cmd = PCRobotCMD.rcvFile; msg.FromMessage = $"[语音={FilePath}]"; msg.FromMessageType = WechatMsgType.语音; } if (MsgInfo.Wxid_1.Contains("@chatroom")) { msg.FromGroupid = MsgInfo.Wxid_1; msg.FromUsername = MsgInfo.Wxid_2; msg.FromUsernick = MsgInfo.Nick_2; } else if (MsgInfo.Wxid_2.Contains("@chatroom")) { msg.FromGroupid = MsgInfo.Wxid_2; msg.FromUsername = MsgInfo.Wxid_1; msg.FromUsernick = MsgInfo.Nick_1; } else { msg.FromUsername = MsgInfo.Wxid_1; msg.FromUsernick = MsgInfo.Nick_1; } if (string.IsNullOrEmpty(msg.FromUsernick) || string.IsNullOrEmpty(msg.RobotUsernick)) { var t = nms.FirstOrDefault(p => p.Wxid == MsgInfo.RecvWxid); if (t.Wxid != null) { msg.RobotUsernick = t.Nick; var m = nmWxidInfos[t.socketHandle]; if (m != null) { var tar = m.FirstOrDefault(p => p.Wxid == MsgInfo.Wxid_1); if (!string.IsNullOrEmpty(tar.Nick) && string.IsNullOrEmpty(msg.FromUsernick)) { msg.FromUsernick = tar.Nick; } } } } socketClient.Send(msg); } } } } WriteLog(outLog); //申请好友 if (MsgInfo.Type == 37) { //nmCore.NM_PassApply(ConnID, MsgInfo.Msg); WechatApplyFriend wXApply = new WechatApplyFriend(); wXApply.Cmd = PCRobotCMD.applyFriend; wXApply.RobotUsername = MsgInfo.RecvWxid; wXApply.RobotUsernick = GetRobotNick(MsgInfo.RecvWxid); wXApply.RobotType = RobotType.客户端微信; var reg = Regex.Match(MsgInfo.Msg, @"content=""(?<申请文本>[^""]*?)"""); if (reg.Success) wXApply.Message = reg.Groups["申请文本"].Value; reg = Regex.Match(MsgInfo.Msg, @"sourceusername=""(?<账号>[^""]*?)"" sourcenickname=""(?<昵称>[^""]*?)"""); if (reg.Success) { wXApply.OldFriendWxid = reg.Groups["账号"].Value; wXApply.OldFriendNick = reg.Groups["昵称"].Value; } reg = Regex.Match(MsgInfo.Msg, @"fromusername=""(?<账号>[^""]*?)"""); if (reg.Success) { if (!string.IsNullOrWhiteSpace(reg.Groups["账号"].Value)) wXApply.NewFriendWxid = reg.Groups["账号"].Value; else { reg = Regex.Match(MsgInfo.Msg, @"alias=""(?<账号>[^""]*?)"""); if (reg.Success) wXApply.NewFriendWxid = reg.Groups["账号"].Value; } } reg = Regex.Match(MsgInfo.Msg, @"fromnickname=""(?<昵称>[^""]*?)"""); if (reg.Success) wXApply.NewFriendNick = reg.Groups["昵称"].Value; wXApply.Token = MsgInfo.Msg; socketClient.Send(wXApply); } if (MsgInfo.IsSend == 0 && MsgInfo.Type == 49) { #region 收到转账 //if (MsgInfo.Msg.IndexOf("微信转账") != -1 && MsgInfo.Msg.IndexOf("收到转账") != -1) //{ // string State = nmHeler.StringMid(MsgInfo.Msg, "", ""); // string Transid = nmHeler.StringMid(MsgInfo.Msg, "transferid>"); // int dwTime = 0; // int.TryParse(nmHeler.StringMid(MsgInfo.Msg, ""), out dwTime); // if (State == "1" && Transid != string.Empty) // { // nmCore.NM_GetMoney(ConnID, MsgInfo.Wxid_1, Transid, dwTime); // } //} if (MsgInfo.Msg.IndexOf("微信转账") != -1 && MsgInfo.Msg.IndexOf("收到转账") != -1) { string State = nmHeler.StringMid(MsgInfo.Msg, "", ""); string Transid = nmHeler.StringMid(MsgInfo.Msg, "transferid>"); int dwTime = 0; int.TryParse(nmHeler.StringMid(MsgInfo.Msg, ""), out dwTime); if (State == "1" && Transid != string.Empty) { WechatReicevePay reicevePay = new WechatReicevePay(); reicevePay.RobotUsername = MsgInfo.RecvWxid; reicevePay.RobotUsernick = GetRobotNick(MsgInfo.RecvWxid); reicevePay.RobotType = RobotType.客户端微信; if (!string.IsNullOrWhiteSpace(MsgInfo.Wxid_1)) { reicevePay.FromUsername = MsgInfo.Wxid_1; reicevePay.FromUsernick = MsgInfo.Nick_1; } reicevePay.Cmd = PCRobotCMD.receivePay; reicevePay.Invalidtime = dwTime.ToString(); reicevePay.Transferid = Transid; var reg = Regex.Match(MsgInfo.Msg, "收到转账(?<金额>.+)元"); if (reg.Success) reicevePay.Money = double.Parse(reg.Groups["金额"].Value); if (reicevePay.RobotUsernick == null) reicevePay.RobotUsernick = string.Empty; socketClient.Send(reicevePay); return; } } #endregion //自动接受群聊邀请 //if (MsgInfo.IsSend == 0 && MsgInfo.Type == 49) //{ //if (MsgInfo.Msg.IndexOf("邀请你加入群聊") != -1 && MsgInfo.Msg.IndexOf("mmsupport-bin/addchatroombyinvite") != -1) //{ // string InviteURL = nmHeler.StringMid(MsgInfo.Msg, ""); // if (InviteURL != string.Empty) // { // nmCore.NM_GetA8Key(ConnID, MsgInfo.Wxid_1, InviteURL); // } //} //} } //文本消息、xml if (MsgInfo.Type == 1 || MsgInfo.Type == 49) { //if (socketClient != null && MsgInfo.IsSend == 0) if (socketClient != null) { var isSend = true; if (MsgInfo.IsSend == 1)//判断是否为机器人自动回复的内容(这里似乎有个问题,图片、xml、无法正常判断是否为自动回复) { isSend = !Regex.IsMatch(MsgInfo.Msg.Trim(), @"<\?xml version=""1\.0""\?>([\w\W]+)"); if (isSend) isSend = !Regex.IsMatch(MsgInfo.Msg.Trim(), @"([\w\W]*?[\w\W]+)"); if (isSend) isSend = WechatClient.IsAuxiliaryInput(MsgInfo.RecvWxid, MsgInfo.Wxid_1, MsgInfo.Msg); } if (isSend) { WechatReceiveMsg msg = new WechatReceiveMsg(); msg.Cmd = PCRobotCMD.rcvTxt; msg.IsSend = MsgInfo.IsSend == 1 ? true : false; msg.RobotUsername = MsgInfo.RecvWxid; msg.RobotUsernick = GetRobotNick(MsgInfo.RecvWxid); msg.RobotType = RobotType.客户端微信; msg.FromMessageType = WechatMsgType.文本; if (MsgInfo.Wxid_1.Contains("@chatroom")) { msg.FromGroupid = MsgInfo.Wxid_1; msg.FromUsername = MsgInfo.Wxid_2; msg.FromUsernick = MsgInfo.Nick_2; } else if (MsgInfo.Wxid_2.Contains("@chatroom")) { msg.FromGroupid = MsgInfo.Wxid_2; msg.FromUsername = MsgInfo.Wxid_1; msg.FromUsernick = MsgInfo.Nick_1; } else { msg.FromUsername = MsgInfo.Wxid_1; msg.FromUsernick = MsgInfo.Nick_1; } if (string.IsNullOrEmpty(msg.FromUsernick) || string.IsNullOrEmpty(msg.RobotUsernick)) { var t = nms.FirstOrDefault(p => p.Wxid == MsgInfo.RecvWxid); if (t.Wxid != null) { msg.RobotUsernick = t.Nick; if (nmWxidInfos.ContainsKey(t.socketHandle)) { var m = nmWxidInfos[t.socketHandle]; if (m != null) { var tar = m.FirstOrDefault(p => p.Wxid == MsgInfo.Wxid_1); if (!string.IsNullOrEmpty(tar.Nick) && string.IsNullOrEmpty(msg.FromUsernick)) { msg.FromUsernick = tar.Nick; } } } } } msg.FromMessage = MsgInfo.Msg; socketClient.Send(msg); } } } if (MsgInfo.IsSend == 0 && MsgInfo.Type == 10000) //&& MsgInfo.State == 2) { if (socketClient != null) { //新人入群 if (MsgInfo.Wxid_1.Contains("@")) { var reg1 = Regex.Match(MsgInfo.Msg, @"""(?<邀请人昵称>.*)""邀请""(?<新人昵称>.*)""加入了群聊"); var reg2 = Regex.Match(MsgInfo.Msg, @"你邀请""(?<新人昵称>.*)""加入了群聊"); var reg3 = Regex.Match(MsgInfo.Msg, @"""(?<新人昵称>.*)""通过扫描""(?<邀请人昵称>.*)""分享的二维码加入群聊"); var reg4 = Regex.Match(MsgInfo.Msg, @"""(?<新人昵称>.*)""通过扫描你分享的二维码加入群聊"); if (reg1.Success || reg2.Success || reg3.Success || reg4.Success) { WechatNewMemer newMember = new WechatNewMemer(); newMember.Cmd = PCRobotCMD.newMember; newMember.RobotType = RobotType.客户端微信; newMember.RobotUsername = MsgInfo.RecvWxid; newMember.RobotUsernick = GetRobotNick(MsgInfo.RecvWxid); if (reg1.Success) { newMember.SourceNick = reg1.Groups["邀请人昵称"].Value; newMember.MemberNick = reg1.Groups["新人昵称"].Value; } else if (reg2.Success) { newMember.SourceNick = newMember.RobotUsernick; newMember.MemberNick = reg2.Groups["新人昵称"].Value; } else if (reg3.Success) { newMember.SourceNick = reg3.Groups["邀请人昵称"].Value; newMember.MemberNick = reg3.Groups["新人昵称"].Value; } else if (reg4.Success) { newMember.SourceNick = newMember.RobotUsernick; newMember.MemberNick = reg4.Groups["新人昵称"].Value; } if (MsgInfo.Wxid_1.Contains("@chatroom")) { newMember.GroupId = MsgInfo.Wxid_1; newMember.GroupNick = MsgInfo.Nick_1; } var t = nms.FirstOrDefault(p => p.Wxid == MsgInfo.RecvWxid); if (t.Wxid != null) { newMember.RobotUsernick = t.Nick; if (nmWxidInfos.ContainsKey(t.socketHandle)) { var m = nmWxidInfos[t.socketHandle]; if (m != null) { var tar = m.FirstOrDefault(p => p.Wxid == MsgInfo.Wxid_1); if (!string.IsNullOrEmpty(tar.Nick) && string.IsNullOrEmpty(newMember.GroupNick)) { newMember.GroupNick = tar.Nick; } } } } socketClient.Send(newMember); } } else//新增好友 { #region 添加好友成功 var reg1 = Regex.Match(MsgInfo.Msg, "^你已添加了(.*?),现在可以开始聊天了。$"); var reg2 = Regex.Match(MsgInfo.Msg, "^(.*?)刚刚把你添加到通讯录,现在可以开始聊天了。$"); if (reg1.Success || reg2.Success) { WechatNewFriend msg = new WechatNewFriend(); msg.Cmd = PCRobotCMD.newfriend; msg.RobotUsername = MsgInfo.RecvWxid; msg.RobotUsernick = GetRobotNick(MsgInfo.RecvWxid); msg.RobotType = RobotType.客户端微信; msg.FromUserName = MsgInfo.Wxid_1; msg.FromUserNick = MsgInfo.Nick_1; socketClient.Send(msg); } #endregion } } } //自动填充消息内容,用于撤回消息 //if (MsgInfo.IsSend == 1 && ConnID == nmHeler.Socket_ConnId) //{ //text_Recvke_Wxid.Text = MsgInfo.Wxid_1; //text_Recvke_Sid.Text = MsgInfo.ServerMsgID; //text_Recvke_Message.Text = MsgInfo.Msg; //} //名片消息自动填充数据 //if (MsgInfo.IsSend == 0 && MsgInfo.Type == 42 && ConnID == nmHeler.Socket_ConnId) //{ //string v1 = nmHeler.StringMid(MsgInfo.Msg, "username=\"", "\" nickname="); //string v2 = nmHeler.StringMid(MsgInfo.Msg, "antispamticket=\"", "\" /"); //text_Friend_v1.Text = v1; //text_Friend_v2.Text = v2; //} } catch (Exception ex) { } } /// /// 通信事件_切换聊天对象 /// /// /// void Event_SelectTalker(int ConnID, JObject RecvJson) { try { //NMHelper.nmWxidInfo WxidInfo = new NMHelper.nmWxidInfo(); //string RecvWxid = nmHeler.Json_GetString(RecvJson, "RecvWxid", true); //WxidInfo.Wxid = nmHeler.Json_GetString(RecvJson, "Wxid", true); //WxidInfo.WxNo = nmHeler.Json_GetString(RecvJson, "WxNo", true); //WxidInfo.Nick = nmHeler.Json_GetString(RecvJson, "Nick", true); //WxidInfo.Mark = nmHeler.Json_GetString(RecvJson, "Mark", true); //WxidInfo.HeadIMG = nmHeler.Json_GetString(RecvJson, "HeadIMG", true); //string outLog = "[切换聊天对象]" + RecvWxid + NewLine; //outLog += "Wxid:" + WxidInfo.Wxid + NewLine; //outLog += WxidInfo.WxNo == string.Empty ? string.Empty : "微信号:" + WxidInfo.Wxid + NewLine; //outLog += "昵称:" + WxidInfo.Nick + NewLine; //outLog += WxidInfo.Mark == string.Empty ? string.Empty : "备注:" + WxidInfo.Mark; ////outLog += "头像:" + WxidInfo.HeadIMG; //WriteLog(outLog); var wxid = nmHeler.Json_GetString(RecvJson, "Wxid", true); nmCore.NM_SetObject(curWx.socketHandle, 2, wxid); } catch (Exception ex) { } } void Event_RecvContactList(int ConnID, JObject RecvJson) { try { var recvWxid = nmHeler.Json_GetString(RecvJson, "RecvWxid", true); string outLog = "[通讯录列表]" + recvWxid + NewLine; int dwState = nmHeler.Json_GetIntEx(RecvJson, "State"); if (dwState == 0) { outLog += "通讯录列表读取失败!"; WriteLog(outLog); return; } JArray m_List = RecvJson.Value("List"); if (m_List != null) { List> nmss = new List>(); List mis = new List(); var count = 40; var rem = m_List.Count % count; var num = m_List.Count / count; for (int i = 0; i < m_List.Count; i++) { JToken JtMember = m_List.ElementAt(i); if (JtMember != null) { NMHelper.nmWxidInfo MemberInfo = new NMHelper.nmWxidInfo(); MemberInfo.Type = nmHeler.Json_GetIntEx((JObject)JtMember, "Type"); MemberInfo.List = nmHeler.Json_GetIntEx((JObject)JtMember, "List"); MemberInfo.Wxid = nmHeler.Json_GetString((JObject)JtMember, "Wxid", true); MemberInfo.WxNo = nmHeler.Json_GetString((JObject)JtMember, "WxNo", true); MemberInfo.Nick = nmHeler.Json_GetString((JObject)JtMember, "Nick", true); MemberInfo.Mark = nmHeler.Json_GetString((JObject)JtMember, "Mark", true); MemberInfo.HeadIMG = nmHeler.Json_GetString((JObject)JtMember, "HeadIMG", true); mis.Add(MemberInfo); if (mis.Count >= count) { nmss.Add(mis); mis = new List(); } else if (nmss.Count == num && mis.Count == rem) { nmss.Add(mis); } } } if (socketClient != null) { foreach (var item in nmss) { WechatContactList msg = new WechatContactList(); msg.RobotUsername = recvWxid; msg.RobotUsernick = GetRobotNick(recvWxid); msg.RobotType = RobotType.客户端微信; msg.Cmd = PCRobotCMD.rcvContactList; msg.Message = HttpHelper.ObjectToJson(new Dictionary>() { { "data", item } }); socketClient.Send(msg); Thread.Sleep(5); } } } } catch (Exception ex) { } } void Event_RecvGroupMember(int ConnID, JObject RecvJson) { try { //string outLog = "[群员列表]" + nmHeler.Json_GetString(RecvJson, "RecvWxid", true) + NewLine; var recvWxid = nmHeler.Json_GetString(RecvJson, "RecvWxid", true); int dwState = nmHeler.Json_GetIntEx(RecvJson, "State"); if (dwState == 0) { //outLog += nmHeler.Json_GetString(RecvJson, "GroupID", false) + "的群员列表读取失败!"; //WriteLog(outLog); return; } JArray m_List = RecvJson.Value("List"); if (m_List != null) { List> nmss = new List>(); List mis = new List(); var count = 20; var rem = m_List.Count % count; var num = m_List.Count / count; for (int i = 0; i < m_List.Count; i++) { JToken JtMember = m_List.ElementAt(i); if (JtMember != null) { NMHelper.nmWxidInfo MemberInfo = new NMHelper.nmWxidInfo(); MemberInfo.Type = nmHeler.Json_GetIntEx((JObject)JtMember, "Type"); MemberInfo.List = nmHeler.Json_GetIntEx((JObject)JtMember, "List"); MemberInfo.Wxid = nmHeler.Json_GetString((JObject)JtMember, "Wxid", true); MemberInfo.WxNo = nmHeler.Json_GetString((JObject)JtMember, "WxNo", true); MemberInfo.Nick = nmHeler.Json_GetString((JObject)JtMember, "Nick", true); MemberInfo.Mark = nmHeler.Json_GetString((JObject)JtMember, "Mark", true); MemberInfo.HeadIMG = nmHeler.Json_GetString((JObject)JtMember, "HeadIMG", true); mis.Add(MemberInfo); if (mis.Count >= count) { nmss.Add(mis); mis = new List(); } else if (nmss.Count == num && mis.Count == rem) { nmss.Add(mis); } } } if (socketClient != null) { foreach (var item in nmss) { WechatGroupMember msg = new WechatGroupMember(); msg.RobotUsername = recvWxid; msg.RobotUsernick = GetRobotNick(recvWxid); msg.RobotType = RobotType.客户端微信; msg.Cmd = PCRobotCMD.rcvGroupMember; nmGroupInfo group = new nmGroupInfo(); group.Count = nmHeler.Json_GetIntEx(RecvJson, "Count"); group.GroupID = nmHeler.Json_GetString(RecvJson, "GroupID", true); group.List = item; msg.Message = HttpHelper.ObjectToJson(new Dictionary() { { "data", group } }); socketClient.Send(msg); Thread.Sleep(5); } } //outLog += nmHeler.Json_GetString(RecvJson, "GroupID", true) + "的群员列表读取成功,群员数:" + list_GroupMember.Items.Count.ToString(); //WriteLog(outLog); } } catch (Exception ex) { } } void Event_RecvWxidInfo(int ConnID, JObject RecvJson) { try { var recvWxid = nmHeler.Json_GetString(RecvJson, "RecvWxid", true); string outLog = "[下载详细信息]" + nmHeler.Json_GetString(RecvJson, "RecvWxid", true) + NewLine; int dwState = nmHeler.Json_GetIntEx(RecvJson, "State"); if (dwState == -1) { outLog += "下载详细信息超时(原因:服务器无返回)!"; } else if (dwState == 0) { outLog += "下载详细信息失败(原因:可能是输入的Wxid不正确)!"; } else if (dwState == 1) { string szGroupID = nmHeler.Json_GetString(RecvJson, "GroupId", true); NMHelper.nmWxidInfo MemberInfo = new NMHelper.nmWxidInfo(); MemberInfo.Wxid = nmHeler.Json_GetString(RecvJson, "Wxid", true); MemberInfo.WxNo = nmHeler.Json_GetString(RecvJson, "WxNo", true); MemberInfo.Nick = nmHeler.Json_GetString(RecvJson, "Nick", true); MemberInfo.V1 = nmHeler.Json_GetString(RecvJson, "v1", true); MemberInfo.HeadIMG = nmHeler.Json_GetString(RecvJson, "HeadIMG", true); MemberInfo.Address = nmHeler.Json_GetString(RecvJson, "Address", true); MemberInfo.Sex = nmHeler.Json_GetIntEx(RecvJson, "Sex").ToString(); outLog += szGroupID == string.Empty ? string.Empty : "群ID:" + szGroupID + NewLine; outLog += "Wxid:" + MemberInfo.Wxid + NewLine; outLog += MemberInfo.WxNo == string.Empty ? string.Empty : "微信号:" + MemberInfo.WxNo + NewLine; outLog += "昵称:" + MemberInfo.Nick + NewLine; outLog += MemberInfo.V1 == string.Empty ? string.Empty : "v1:" + MemberInfo.V1 + NewLine; outLog += "性别:" + MemberInfo.Sex + NewLine; outLog += MemberInfo.Address == string.Empty ? string.Empty : "地区:" + MemberInfo.Address + NewLine; outLog += MemberInfo.HeadIMG == string.Empty ? string.Empty : "头像:" + MemberInfo.HeadIMG + NewLine; WechatContactList msg = new WechatContactList(); msg.RobotUsername = recvWxid; msg.RobotUsernick = GetRobotNick(recvWxid); msg.RobotType = RobotType.客户端微信; msg.Cmd = PCRobotCMD.rcvContactList; msg.Message = HttpHelper.ObjectToJson(new Dictionary>() { { "data", new List() { MemberInfo } } }); socketClient.Send(msg); Thread.Sleep(5); } WriteLog(outLog); } catch (Exception ex) { } } void Event_AddFriend(int ConnID, JObject RecvJson) { try { //string outLog = "[添加好友]" + nmHeler.Json_GetString(RecvJson, "RecvWxid", true) + NewLine; //int DataType = nmHeler.Json_GetIntEx(RecvJson, "DataType"); //string Data = nmHeler.Json_GetString(RecvJson, "Data", true); //int Type = nmHeler.Json_GetIntEx(RecvJson, "Type"); //int AddType = nmHeler.Json_GetIntEx(RecvJson, "AddType"); //string Wxid = nmHeler.Json_GetString(RecvJson, "Wxid", true); //string v2 = nmHeler.Json_GetString(RecvJson, "V2", true); //string Message = nmHeler.Json_GetString(RecvJson, "Message", true); //outLog += "添加返回:[" + DataType.ToString() + "]" + (DataType == 0 ? "已发送好友请求或已添加好友。" : Data) + NewLine; //outLog += "添加类型:" + Type.ToString() + " 添加来源:" + AddType.ToString() + NewLine; //outLog += "Wxid:" + Wxid; //outLog += v2 == string.Empty ? string.Empty : NewLine + "v2:" + v2; //outLog += Message == string.Empty ? string.Empty : NewLine + "附加消息:" + Message; //WriteLog(outLog); //if (Type == 1 && DataType == -44) //{ // nmCore.NM_AddFriend(ConnID, 2, AddType, Wxid, v2, text_Friend_Message.Text); //} } catch (Exception ex) { } } void Event_CreateGroup(int ConnID, JObject RecvJson) { try { //string outLog = "[创建群聊]" + nmHeler.Json_GetString(RecvJson, "RecvWxid", true) + NewLine; //string Data = nmHeler.Json_GetString(RecvJson, "Data", true); //string GroupID = nmHeler.Json_GetString(RecvJson, "GroupID", true); //outLog += "建群返回:" + Data; //outLog += GroupID == string.Empty ? string.Empty : NewLine + "群聊ID:" + GroupID + NewLine; //JArray MemberList = RecvJson.Value("List"); //if (MemberList != null) //{ // outLog += "群员列表:"; // for (int i = 0; i < MemberList.Count; i++) // { // JToken JtMember = MemberList.ElementAt(i); // if (JtMember != null) // { // string Wxid = nmHeler.Json_GetString((JObject)JtMember, "Wxid", true); // string Nick = nmHeler.Json_GetString((JObject)JtMember, "Nick", true); // int state = nmHeler.Json_GetIntEx((JObject)JtMember, "State"); // if (Wxid != string.Empty) // { // outLog += NewLine + "[" + state.ToString() + "]" + (state == 0 ? "[成功]" : "[失败]"); // outLog += Wxid + (Nick == string.Empty ? string.Empty : "(" + Nick + ")"); // } // } // } //} //WriteLog(outLog); } catch (Exception ex) { } } void Event_GetFavList(int ConnID, JObject RecvJson) { try { //string outLog = "[收藏列表]" + nmHeler.Json_GetString(RecvJson, "RecvWxid", true) + NewLine; //JArray FavList = RecvJson.Value("List"); //if (FavList != null) //{ // list_Fav.Items.Clear(); // int dwCount = FavList.Count; // if (dwCount != 0) // { // list_Fav.BeginUpdate(); // for (int i = 0; i < dwCount; i++) // { // JToken JtMember = FavList.ElementAt(i); // if (JtMember != null) // { // int Type = nmHeler.Json_GetIntEx((JObject)JtMember, "Type"); // string SearchKey = nmHeler.Json_GetString((JObject)JtMember, "SearchKey", true); // string TypeName = nmHeler.GetFavType(Type); // ListViewItem FavItem = new ListViewItem(); // FavItem.Text = i.ToString(); // FavItem.SubItems.Add(TypeName); // FavItem.SubItems.Add(SearchKey == string.Empty ? "[" + TypeName + "文件]" : SearchKey); // list_Fav.Items.Add(FavItem); // } // } // list_Fav.EndUpdate(); // outLog += "收藏列表读取成功,共" + dwCount.ToString() + "条记录!"; // } // else // { // outLog += "没有收藏"; // } //} //WriteLog(outLog); } catch (Exception ex) { } } void Event_GetA8Key(int ConnID, JObject RecvJson) { try { //string RecvWxid = nmHeler.Json_GetString(RecvJson, "RecvWxid", true); //string outLog = "[GetA8Key]" + RecvWxid + NewLine; //string URL = nmHeler.Json_GetString(RecvJson, "URL", true); //string LastURL = nmHeler.Json_GetString(RecvJson, "LastURL", true); //outLog += "获取链接:" + URL + NewLine; //outLog += "返回链接:" + LastURL; //WriteLog(outLog); //if (URL.IndexOf("mmsupport-bin/addchatroombyinvite") != -1) //{ // HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(URL); // Request.Method = "POST"; // Request.AllowAutoRedirect = false; // Request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; // Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.556.400 QQBrowser/9.0.2524.400"; // Request.Referer = URL; // Request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,en-us;q=0.6,en;q=0.5;q=0.4"); // HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); // string hLocation = Response.GetResponseHeader("Location").ToString(); // if (hLocation != "") // { // if (hLocation.IndexOf("chatroom") != -1) // { // string GroupID = nmHeler.StringMid(hLocation, "weixin://jump/mainframe/", "@chatroom"); // WriteLog("[接受群聊邀请]" + RecvWxid + NewLine + "群聊ID:" + GroupID + "@chatroom"); // } // } //} } catch (Exception ex) { } } void Event_GroupInvite(int ConnID, JObject RecvJson) { try { string RecvWxid = nmHeler.Json_GetString(RecvJson, "RecvWxid", true); string outLog = "[群员动态-进群]" + RecvWxid + NewLine; string GroupID = nmHeler.Json_GetString(RecvJson, "GroupID", true); outLog = "群聊ID:" + GroupID + NewLine; JArray MemberList = RecvJson.Value("List"); if (MemberList != null) { for (int i = 0; i < MemberList.Count; i++) { JToken JtMember = MemberList.ElementAt(i); if (JtMember != null) { string Wxid = nmHeler.Json_GetString((JObject)JtMember, "Wxid", true); string Nick = nmHeler.Json_GetString((JObject)JtMember, "Nick", true); string InvWxid = nmHeler.Json_GetString((JObject)JtMember, "InvWxid", true); string InvNick = nmHeler.Json_GetString((JObject)JtMember, "InvNick", true); outLog += "[" + (i + 1).ToString() + "]" + NewLine; outLog += "进群人:" + Wxid + (Nick == string.Empty ? string.Empty : "(" + Nick + ")" + NewLine); outLog += "邀请人:" + InvWxid + (InvNick == string.Empty ? string.Empty : "(" + InvNick + ")" + NewLine); } } } WriteLog(outLog); } catch (Exception ex) { } } void Event_GroupQuit(int ConnID, JObject RecvJson) { try { string RecvWxid = nmHeler.Json_GetString(RecvJson, "RecvWxid", true); string outLog = "[群员动态-退群]" + RecvWxid + NewLine; string GroupID = nmHeler.Json_GetString(RecvJson, "GroupID", true); outLog += "群聊ID:" + GroupID + NewLine; JArray MemberList = RecvJson.Value("List"); if (MemberList != null) { for (int i = 0; i < MemberList.Count; i++) { JToken JtMember = MemberList.ElementAt(i); if (JtMember != null) { string Wxid = nmHeler.Json_GetString((JObject)JtMember, "Wxid", true); string Nick = nmHeler.Json_GetString((JObject)JtMember, "Nick", true); outLog += "[" + (i + 1).ToString() + "]" + NewLine; outLog += Wxid + (Nick == string.Empty ? string.Empty : "(" + Nick + ")" + NewLine); } } } WriteLog(outLog); } catch (Exception ex) { } } [DllImport("User32.dll", EntryPoint = "PostMessage")] public static extern int PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("LIB.KTY.WC.dll", EntryPoint = "Run")] public static extern IntPtr Run(string path, string dll, int port); private IntPtr DwPid = IntPtr.Zero; public int handle { get { return (int)DwPid; } } public int StartWechat() { try { // api.StartWechat(); PCWechat.Wechat_Xiaoxie.StartWechat(HttpExtend.MapFile("WeChat.exe", $"PCWechat\\2.7.1.82")); return -1; bool isAlterXML = false; //var path = CsharpHttpHelper.HttpExtend.MapPath("PCWechat\\2.8.0.112"); //var path = CsharpHttpHelper.HttpExtend.MapPath("PCWechat\\2.7.1.88"); var path = CsharpHttpHelper.HttpExtend.MapPath($"PCWechat\\{comboBox1.SelectedItem.ToString()}"); var wechatPath = CsharpHttpHelper.HttpExtend.MapFile("WeChatWin.dll", path); if (!File.Exists(wechatPath)) { var rst = MessageBox.Show($"您还没有下载{comboBox1.SelectedItem.ToString()}版本微信,是否立即下载?", "微信版本异常", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (rst == DialogResult.Yes) { new WechatUpdate(comboBox1.SelectedItem.ToString()).ShowDialog(); } return -1; } var md5 = Common.GetMD5Hash(wechatPath); var version = comboBox1.SelectedItem.ToString(); //PCWechat.BaseApi api = null; //if (version == "2.7.1.82") //{ // api = new PCWechat.Wechat_Xiaoxie(); // api.StartWechat(HttpExtend.MapFile("WeChat.exe", $"PCWechat\\{version}")); // return -1; //} if ((version == "2.7.1.88" && md5 == "CED61F308EDD8CF3E2D864DF285DC2AF") || (version == "2.8.0.112" && md5 == "D13203AC5C3099D8563E16185DA944BC")) { string szDllPath = System.IO.Directory.GetCurrentDirectory() + "\\bin\\NanMuCore.dll"; var id = NMHelper.NM_CreateWeChatProcess(path, "WeChat.exe", szDllPath, nmHeler.Socket_Port); return id; } else { var rst = MessageBox.Show($"启动失败,您的微信{comboBox1.SelectedItem.ToString()}版本异常,是否重新下载?\r\n注意:平时请关闭微信自动升级,不要随意升级微信!!!", "微信版本异常", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (rst == DialogResult.Yes) { new WechatUpdate(comboBox1.SelectedItem.ToString()).ShowDialog(); return -1; } } } catch (Exception ex) { throw ex; } return -1; } public void WriteLog(string str) { } #endregion public static List nms = new List(); /** * 判断是否是xml结构 */ public static bool isXML(string value) { try { //XmlDocument xdoc = new XmlDocument(); //xdoc.LoadXml(value); //return true; //上面的这里有些情况下不准 var reg = Regex.IsMatch(value.Trim(), @"(.*0[\w\W]*1Window wechat)"); return reg; } catch (Exception ex) { return false; } } public static void alterXML() { try { var updateXml = CsharpHttpHelper.HttpExtend.MapFile("LevelUpdate.xml"); XmlDocument xdoc = new XmlDocument(); xdoc.Load(updateXml); var rootNode = xdoc.SelectSingleNode("Files"); //获得该节点的子节点(即:该节点的第一层子节点) bool isFind = false; XmlNodeList firstLevelNodeList = rootNode.ChildNodes; foreach (XmlNode node in firstLevelNodeList) { if (isFind) break; //获得该节点的属性集合 XmlAttributeCollection attributeCol = node.Attributes; foreach (XmlAttribute attri in attributeCol) { //获取属性名称与属性值 string name = attri.Name; string value = attri.Value; if (name == "Name" && value == "PCWechat") { isFind = true; continue; } if (isFind && name == "Version") { attri.Value = "2020.02.14.1"; break; } Console.WriteLine("{0} = {1}", name, value); } } xdoc.Save(updateXml); throw new Exception("微信版本"); } catch (Exception ex) { throw ex; } } /// /// 通过机器人id获取机器人昵称 /// /// /// private string GetRobotNick(string wxid) { var curWx = nms.FirstOrDefault(p => p.Wxid == wxid); if (string.IsNullOrEmpty(curWx.Wxid)) return string.Empty; return curWx.Nick; } public void lgCall(nmWxidInfo nm) { try { if (!nms.Contains(nm)) { //Process nms.Add(nm); if (nm.Wxid != null) { if (socketClient != null) { WechatStatus msg = new WechatStatus(); msg.Cmd = PCRobotCMD.offline; msg.RobotUsername = nm.Wxid; msg.RobotUsernick = nm.Nick; msg.RobotType = RobotType.客户端微信; msg.Status = Status.在线; socketClient.Send(msg); } WriteLog("[微信登陆]" + NewLine + "昵称:" + nm.Nick + NewLine + "Wxid:" + nm.Wxid); } } //nms.Add(nm); UpdateUi(); } catch (Exception ex) { LogHelper.GetSingleObj().Error("lgc ERROR:", $"{ex.Message} - {ex.StackTrace}"); } } private void button3_Click(object sender, EventArgs e) { try { foreach (var item in nms) { Event_Logout(item.socketHandle, new JObject(), true); if ((IntPtr)item.handle != IntPtr.Zero) { PostMessage((IntPtr)item.handle, 18, 0, 0); Process[] myproc = Process.GetProcesses(); foreach (Process items in myproc) { try { if (items.Id == item.handle) { items.Kill(); break; } } catch (Exception) { } } } } nms.Clear(); UpdateUi(); } catch (Exception ex) { } } IniHelper config = null; private void Sleep(int number) { Thread t = new Thread(o => Thread.Sleep(number)); t.Start(this); while (t.IsAlive) { Application.DoEvents(); } } private void button1_Click(object sender, EventArgs e) { //this.button1.Enabled = false; try { if (config == null) { var fileName = HttpExtend.MapFile("服务器配置.ini", "Config"); config = new IniHelper(fileName); } config.SetValue("服务器信息", "IP", textBox1.Text); config.SetValue("服务器信息", "Port", textBox2.Text); config.SetValue("秘钥", "SecretKey", textBox3.Text); if (this.button1.Text != "连接服务器") { if (socketClient != null) { socketClient.Stop = true; socketClient.Close(); } StateCall("您已断开与服务器的连接!"); this.button1.Text = "连接服务器"; return; } //MessageBox.Show("保存配置成功"); if (socketClient != null) { socketClient.Close(); } socketClient.Stop = false; socketClient.Connection(config.GetValue("服务器信息", "IP"), Convert.ToInt32(config.GetValue("服务器信息", "Port")), Rcv, Sea, config.GetValue("秘钥", "SecretKey"), StateCall); Thread.Sleep(1000); if (socketClient.IsConnected) { //socketClient.Stop = false; this.button1.Text = "断开服务器"; //this.Close(); } else throw new Exception("连接服务器失败,请检查是否填写正确!"); } catch (Exception ex) { if (socketClient != null) socketClient.Stop = true; MessageBox.Show(ex.Message, "友情提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void StateCall(string str) { if (!string.IsNullOrEmpty(str)) { try { this.Invoke(new Action(() => { status.Text = str; if (str.Contains("成功")) { this.groupBox1.Enabled = false; this.button1.Text = "断开服务器"; } else { this.groupBox1.Enabled = true; this.button1.Text = "连接服务器"; } })); } catch (Exception ex) { LogHelper.GetSingleObj().Error("sc ERROR:", $"{ex.Message} - {ex.StackTrace}"); } } } private void Sea(Exception obj) { StateCall("连接异常:" + obj.Message); socketClient.Close(); } private void RefUserMethod(WechatUser user) { this.Invoke(new Action(delegate { try { this.listView1.Items.Clear(); foreach (var item in WechatClient.Users.Values.ToList()) { var view = new ListViewItem(new string[] { item.Pid.ToString(),item.Wxid, item.Nickname, item.Phone }); view.Tag = item; this.listView1.Items.Add(view); } } catch (Exception) { } })); } private void WinForm_Load(object sender, EventArgs e) { this.FormClosing += PCForm_FormClosing; contextMenuStrip1.Opening += ContextMenuStrip1_Opening; //try //{ // IniWechat(); //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message, "初始化微信失败", MessageBoxButtons.OK, MessageBoxIcon.Error); // this.Close(); // return; //} try { WechatClient.RefUserEvent = RefUserMethod; WechatClient.Install();//安装微信,初始化注入 var fileName = HttpExtend.MapFile("服务器配置.ini", "Config"); var config = new IniHelper(fileName); textBox1.Text = config.GetValue("服务器信息", "IP"); textBox2.Text = config.GetValue("服务器信息", "Port"); textBox3.Text = config.GetValue("秘钥", "SecretKey"); var version = config.GetValue("微信版本", "Version"); if (string.IsNullOrWhiteSpace(version)) config.SetValue("微信版本", "Version", "2.7.1.88"); var v = config.GetValue("微信版本", "Version"); for (int i = 0; i < comboBox1.Items.Count; i++) { if (comboBox1.Items[i].ToString() == v) { comboBox1.SelectedIndex = i; break; } } //comboBox1.SelectedIndex = config.GetValue("微信版本", "Version") == "2.7.1.88" ? 0 : 1; socketClient = new SocketClient(); socketClient.Connection(config.GetValue("服务器信息", "IP"), Convert.ToInt32(config.GetValue("服务器信息", "Port")), Rcv, Sea, config.GetValue("秘钥", "SecretKey"), StateCall); } catch (Exception ex) { LogHelper.GetSingleObj().Error("加载窗体 ERROR:", $"{ex.Message} - {ex.StackTrace}"); } } private void ContextMenuStrip1_Opening(object sender, CancelEventArgs e) { if (listView1.SelectedItems.Count == 0) { e.Cancel = true; //删除微信ToolStripMenuItem.Enabled = false; } } private void 删除微信ToolStripMenuItem_Click(object sender, EventArgs e) { try { if (listView1.SelectedItems.Count == 0) return; else { string site = listView1.SelectedItems[0].Text; int handle = 0; if (int.TryParse(site, out handle)) { var nm = nms.FirstOrDefault(p => p.handle == handle); Event_Logout(nm.socketHandle, new JObject()); CloseWechat(handle); //nms.Remove(nm); //UpdateUi(); } } var item = listView1.SelectedItems; } catch (Exception ex) { LogHelper.GetSingleObj().Error("Delete Wechat ERROR:", $"{ex.Message} - {ex.StackTrace}"); } } public void UpdateUi() { try { listView1.Invoke(new Action(() => { listView1.Items.Clear(); })); for (int i = 0; i < nms.Count; i++) { var temp = nms[i]; ListViewItem UserItem = new ListViewItem(); UserItem.Text = temp.handle.ToString(); UserItem.SubItems.Add(temp.Wxid); UserItem.SubItems.Add(temp.Nick); UserItem.SubItems.Add(temp.WxNo); UserItem.SubItems.Add(temp.HeadIMG); listView1.Invoke(new Action(() => { listView1.Items.Add(UserItem); })); } } catch (Exception ex) { LogHelper.GetSingleObj().Error("ui ERROR:", $"{ex.Message} - {ex.StackTrace}"); } } public void CloseWechat(int handle) { try { if ((IntPtr)handle != IntPtr.Zero) { PostMessage((IntPtr)handle, 18, 0, 0); Process[] myproc = Process.GetProcesses(); foreach (Process items in myproc) { try { if (items.Id == handle) { items.Kill(); break; } } catch (Exception) { } } } } catch (Exception ex) { LogHelper.GetSingleObj().Error("CloseWechat ERROR:", $"{ex.Message} - {ex.StackTrace}"); } } private void button4_Click(object sender, EventArgs e) { try { var nm = nms.FirstOrDefault(); if (nm.Wxid != null) { string str = "\nwxid_u02qcv8eas7l51\n0\n\n \n公公和儿媳妇之间...\n内容儿童不宜,非礼勿视~~\nview\n5\n0\n\nhttps://www.baidu.com/\n\n\nhttp://ww2.sinaimg.cn/large/ceeb653ejw1fad1gv3wv5j20cm09g0t5.jpg\n\n\n\n\n\n\n\n \n0\n\n\n\n \n\n\n1\nWindow wechat\n\n"; if (isXML(str)) { } nmCore.NM_SendURLMsg(nm.socketHandle, "wxid_y5bnbqqa9d9721", str); } } catch (Exception ex) { LogHelper.GetSingleObj().Error("SendUrlMsg ERROR:", $"{ex.Message} - {ex.StackTrace}"); } } private void button4_Click_1(object sender, EventArgs e) { OnlineUpdate.Client client = new OnlineUpdate.Client(); if (client.CheckVersion()) { client.StartInstall(); this.Close(); //we } //new LevelUpdate.UpdateForm().ShowDialog(); } private void textBox3_TextChanged(object sender, EventArgs e) { } private void button5_Click_1(object sender, EventArgs e) { nmCore.NM_GetContactList(curWx.socketHandle); } string[] ClearDirs = new string[] { "VOICE", "IMAGE" }; /// /// 清理缓存 /// /// /// private void ClearCache_Timer_Tick(object sender, EventArgs e) { this.Invoke(new Action(() => { try { //删除微信缓存文件(图片/文件) var cachePath = CsharpHttpHelper.HttpExtend.MapPath("Accounts"); if (Directory.Exists(cachePath)) { DirectoryInfo dirs = new DirectoryInfo(cachePath); FileSystemInfo[] fileinfos = dirs.GetFileSystemInfos(); //返回目录中所有文件和子目录 for (int z = 0; z < fileinfos.Length; z++) { for (int k = 0; k < ClearDirs.Length; k++) { var path = CsharpHttpHelper.HttpExtend.MapPath($@"Accounts\{fileinfos[z]}\{ClearDirs[k]}"); Common.DeleteDir(path); } } } //删除更新包 Common.DeleteDir(CsharpHttpHelper.HttpExtend.MapPath(@"Cache\Update")); } catch (Exception) { } })); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (config == null) { var fileName = HttpExtend.MapFile("服务器配置.ini", "Config"); config = new IniHelper(fileName); } config.SetValue("微信版本", "Version", comboBox1.SelectedItem.ToString()); } } }