wxRobot.py 8.4 KB
Newer Older
1 2 3 4 5 6 7 8
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 24 16:19:48 2022

@author: ljc545w
"""

# Before use,execute `CWeChatRebot.exe /regserver` in cmd by admin user
L
ljc545w 已提交
9
# need `pip install comtypes`
10 11
import comtypes.client
import ast
12 13
import threading
import time
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

class ChatSession():
    def __init__(self,robot,wxid):
        self.robot = robot
        self.chatwith = wxid
        
    def SendText(self,msg):
        return self.robot.CSendText(self.chatwith,msg)
        
    def SendImage(self,imgpath):
        return self.robot.CSendImage(self.chatwith,imgpath)
    
    def SendFile(self,filepath):
        return self.robot.CSendFile(self.chatwith,filepath)
    
    # 其实发送图片的函数比较智能,也可以发送视频和文件
    def SendMp4(self,mp4path):
        return self.robot.CSendImage(self.chatwith,mp4path)
        
    def SendArticle(self,title,abstract,url):
        return self.robot.CSendArticle(self.chatwith,title,abstract,url)
    
    def SendCard(self,sharedwxid,nickname):
        return self.robot.CSendCard(self.chatwith,sharedwxid,nickname)
L
ljc545w 已提交
38 39 40 41 42
    
    def SendAtText(self,wxid,msg):
        if '@chatroom' not in self.chatwith:
            return 1
        return self.robot.CSendAtText(self.chatwith,wxid,msg)
43 44 45 46 47 48 49 50
        

class WeChatRobot():
    
    def __init__(self):
        self.robot = comtypes.client.CreateObject("WeChatRobot.CWeChatRobot")
        self.AddressBook = []
        self.myinfo = {}
51
        self.ReceiveMessageStarted = False
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        
    def StartService(self):
        status = self.robot.CStartRobotService()
        return status

    def GetSelfInfo(self):
        myinfo = self.robot.CGetSelfInfo().replace('\n','\\n')
        try:
            myinfo = ast.literal_eval(myinfo)
        except SyntaxError:
            return {}
        myinfo['wxBigAvatar'] = myinfo['wxBigAvatar'].replace("/132","/0")
        self.myinfo = myinfo
        return self.myinfo
        
    def StopService(self):
68
        self.StopReceiveMessage()
69 70 71
        return self.robot.CStopRobotService()
    
    def GetAddressBook(self):
L
ljc545w 已提交
72 73 74 75 76
        try:
            FriendTuple = self.robot.CGetFriendList()
            self.AddressBook = [dict(i) for i in list(FriendTuple)]
        except IndexError:
            self.AddressBook = []
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
        return self.AddressBook
    
    def GetFriendList(self):
        if not self.AddressBook:
            self.GetAddressBook()
        FriendList = []
        for item in self.AddressBook:
            if 'wxid_' == item['wxid'][0:5]:
                FriendList.append(item)
        return FriendList
    
    def GetChatRoomList(self):
        if not self.AddressBook:
            self.GetAddressBook()
        ChatRoomList = []
        for item in self.AddressBook:
            if '@chatroom' in item['wxid']:
                ChatRoomList.append(item)
        return ChatRoomList
    
    def GetOfficialAccountList(self):
        if not self.AddressBook:
            self.GetAddressBook()
        OfficialAccountList = []
        for item in self.AddressBook:
            if 'wxid_' != item['wxid'][0:5] and '@chatroom' not in item['wxid']:
                OfficialAccountList.append(item)
        return OfficialAccountList
    
    def GetFriendByWxRemark(self,remark:str):
        if not self.AddressBook:
            self.GetAddressBook()
        for item in self.AddressBook:
            if item['wxRemark'] == remark:
                return item
        return None
    
    def GetFriendByWxNumber(self,wxnumber:str):
        if not self.AddressBook:
            self.GetAddressBook()
        for item in self.AddressBook:
            if item['wxNumber'] == wxnumber:
                return item
        return None
    
    def GetFriendByWxNickName(self,wxnickname:str):
        if not self.AddressBook:
            self.GetAddressBook()
        for item in self.AddressBook:
            if item['wxNickName'] == wxnickname:
                return item
        return None
    
    def GetChatSession(self,wxid):
        return ChatSession(self.robot, wxid)
        
    def GetWxUserInfo(self,wxid):
        userinfo = self.robot.CGetWxUserInfo(wxid).replace('\n','\\n')
        return ast.literal_eval(userinfo)
    
    def CheckFriendStatusInit(self):
        return self.robot.CCheckFriendStatusInit()
    
    def CheckFriendStatusFinish(self):
        return self.robot.CCheckFriendStatusFinish()
    
    def CheckFriendStatus(self,wxid):
        _EnumFriendStatus = {
            0xB0:'被删除',
            0xB1:'是好友',
L
ljc545w 已提交
147
            0xB2:'已拉黑',
148 149 150 151 152 153
            0xB5:'被拉黑',
            }
        status = self.robot.CCheckFriendStatus(wxid)
        if status == 0x0:
            print('请先初始化再进行检测!')
            assert False
L
ljc545w 已提交
154 155 156
        try:
            return _EnumFriendStatus[status]
        except KeyError:
157
            return "未知状态:{}".format(hex(status).upper().replace('0X','0x'))
158 159 160
        
    def ReceiveMessage(self,CallBackFunc = None):
        comtypes.CoInitialize()
161 162
        # 线程中必须新建一个对象,但无需重复注入
        ThreadRobot = WeChatRobot()
163 164
        while self.ReceiveMessageStarted:
            try:
165
                message = dict(ThreadRobot.robot.CReceiveMessage())
L
ljc545w 已提交
166
                if CallBackFunc and message:
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
                    CallBackFunc(ThreadRobot,message)
            except IndexError:
                message = None
            time.sleep(0.5)
        comtypes.CoUninitialize()
    
    # 接收消息的函数,可以添加一个回调
    def StartReceiveMessage(self,CallBackFunc = None):
        self.ReceiveMessageStarted = True
        status = self.robot.CStartReceiveMessage()
        self.ReceiveMessageThread = threading.Thread(target = self.ReceiveMessage,args= (CallBackFunc,))
        self.ReceiveMessageThread.daemon = True
        self.ReceiveMessageThread.start()
        return status
        
    def StopReceiveMessage(self):
        self.ReceiveMessageStarted = False
        try:
            self.ReceiveMessageThread.join()
        except:
            pass
        status = self.robot.CStopReceiveMessage()
        return status

# 一个示例回调,将收到的文本消息转发给filehelper
def ReceiveMessageCallBack(robot,message):
    if message['type'] == 1 and message['sender'] != 'filehelper':
194 195 196 197
        robot.robot.CSendText('filehelper',message['message'])
    if message['sender'] != 'filehelper':
        wxSender = robot.GetWxUserInfo(message['sender'])
        sender = wxSender['wxNickName'] if wxSender['wxNickName'] != 'null' else message['sender']
L
ljc545w 已提交
198 199
        print("来自 {}".format(sender))
        print(message)
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    
def test_SendText():
    import os
    path = os.path.split(os.path.realpath(__file__))[0]
    # image full path
    imgpath = os.path.join(path,'test\\测试图片.png')
    # file full path
    filepath = os.path.join(path,'test\\测试文件')
    wx = WeChatRobot()
    wx.StartService()
    myinfo = wx.GetSelfInfo()
    chatwith = wx.GetFriendByWxNickName("文件传输助手")
    session = wx.GetChatSession(chatwith.get('wxid'))
    filehelper = wx.GetWxUserInfo(chatwith.get('wxid'))
    session.SendText('个人信息:{}'.format(str(myinfo.get('wxNickName'))))
    session.SendText('好友信息:{}'.format(str(filehelper.get('wxNickName'))))
    if os.path.exists(imgpath): session.SendImage(imgpath)
    if os.path.exists(filepath): session.SendFile(filepath)
218
    session.SendArticle("天气预报","点击查看","http://www.baidu.com")
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    shared = wx.GetFriendByWxNickName("码农翻身")
    if shared: session.SendCard(shared.get('wxid'),shared.get('wxNickName'))
    wx.StopService()
    
def test_FriendStatus():
    f = open('Friendstatus.txt','wt',encoding = 'utf-8')
    wx = WeChatRobot()
    wx.StartService()
    FriendList = wx.GetFriendList()
    wx.CheckFriendStatusInit()
    index = "\t".join(['微信号','昵称','备注','状态','\n'])
    f.writelines(index)
    for Friend in FriendList:
        result = '\t'.join(
            [Friend.get('wxNumber'),Friend.get('wxNickName'),Friend.get('wxRemark'),
              wx.CheckFriendStatus(Friend.get('wxid'))])
        print(result)
        result += '\n'
        f.writelines(result)
        time.sleep(1)
        break
    f.close()
    wx.StopService()
242 243 244 245 246
    
def test_ReceiveMessage():
    wx = WeChatRobot()
    wx.StartService()
    wx.StartReceiveMessage(CallBackFunc = ReceiveMessageCallBack)
L
ljc545w 已提交
247 248 249 250 251
    try:
        while True:
            pass
    except KeyboardInterrupt:
        pass
252
    wx.StopService()
253 254

if __name__ == '__main__':
255
    test_ReceiveMessage()