706-微信机器人

首先登陆图灵机器人注册一个属于自己的微信机器人,注册成功后可查看apikey以供后面使用!

我是在pycharm中使用的,导入相应的模块即可!下面直接看代码吧!代码很简洁!

wechat autoreply

源代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import itchat
import requests
import re

# 抓取网页
def getHtmlText(url):
	try:
		r = requests.get(url, timeout=30)
		r.raise_for_status()
		r.encoding = r.apparent_encoding
		return r.text
	except:
		return ""


# 自动回复
# 封装好的装饰器,当接收到的消息是Text,即文字消息
@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=(输入你自己的apikey)&info="
		url = url + msg['Text']
		html = getHtmlText(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()