实现功能:
version1:
自动回复固定消息
version2:
批量爬取网站笑话并随机自动回复一个
准备工作:
itchat等库,目标网站
效果展示:
代码:
import urllib.request
import re
import urllib.error
import random
import itchat
itchat.login()
@itchat.msg_register('Text')
def text_reply(msg):
if not msg['FromUserName'] == myUserName:
itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" %
(("%Y-%m-%d %H:%M:%S", (msg['CreateTime'])),
msg['User']['NickName'],
msg['Text']), 'filehelper')
for j in range(1, 2):
try:
headers = ('User-Agent',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0')
opener = urllib.request.build_opener()
opener.addheaders = [headers]
urllib.request.install_opener(opener)
url = 'https://www.qiushibaike.com/text/'
urllib.request.urlopen(url)
print('第' + str(j) + '次检测,没有异常')
if j == 1:
print('检测完成')
except urllib.error.URLError as e:
if hasattr(e, 'code'):
print(e.code)
if hasattr(e, 'reason'):
print(e.reason)
page_data = urllib.request.urlopen(url).read().decode('utf-8')
pat1 = '<div class="content">.*?<span>(.*?)</span>'
rst1 = re.compile(pat1, re.S).findall(page_data)
z = len(rst1)
i = random.randint(1, z)
global recall
recall = '刚才在糗事百科看到个笑话' + rst1[i]
return recall
if __name__ == '__main__':
itchat.auto_login()
myUserName = itchat.get_friends(update=True)[0]["UserName"]
itchat.run()