Python中itchat模块对于操作微信来说是个福音,今天,我们就用Python实现微信自动回复,同时调用图灵机器人,实现智能回复。
具体代码如下:
#导入库 import itchat import requests import re # 抓取网页 def tulingrobot(url): try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return "" # 自动回复 @itchat.msg_register(['Text', 'Map', 'Card', 'Note', 'Sharing', 'Picture']) def text_reply(msg): # 判断消息是不是自己回复 if not msg['FromUserName'] == Name["***"]:#改成自己的微信名字 # 回复给好友 url = "http://www.tuling123.com/openapi/api?key=d92fd1e8671f4d2487b47f85b118eab6&info=" url = url + msg['Text'] html = tulingrobot(url) message = re.findall(r'"text":".*?"', html) reply = eval(message[0].split(':')[1]) return reply if __name__ == '__main__': itchat.auto_login() # 获取自己的UserName friends = itchat.get_friends(update=True)[0:] Name = {} Nic = [] User = [] for i in range(len(friends)): Nic.append(friends[i]["NickName"]) User.append(friends[i]["UserName"]) for i in range(len(friends)): Name[Nic[i]] = User[i] itchat.run()
测试运行效果如下:
进群:960410445 获取源码!
好了,See you!