python利用图灵机器人实现微信好友自动回复

python利用图灵机器人实现微信好友自动回复

安装

安装python3环境,请找度娘。
pip install itchat
pip install requests

抓取网页

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["自己微信号"]:
    # 或者指定微信好友
    if msg['FromUserName'] == Name["好友微信昵称"]:
        # 回复给好友
        tulingkey = "***********"  #注册图灵官网申请自己的机器人
        url = "http://www.tuling123.com/openapi/api?key=%s&info=" % (tulingkey)
        url = url + msg['Text']
        html = getHtmlText(url)
        message = re.findall(r'\"text\"\:\".*?\"',html)
        reply = eval(message[0].split(':')[1])
        return reply

完整代码

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 ""

# 自动回复
@itchat.msg_register(['Text','Map', 'Card', 'Note', 'Sharing', 'Picture'])
def text_reply(msg):
    # 当消息不是由自己发出的时候 if not msg['FromUserName'] == Name["自己微信号"]:
    # 或者指定微信好友
    if msg['FromUserName'] == Name["好友微信昵称"]:
        # 回复给好友
        tulingkey = "***********"  #注册图灵官网,申请自己的机器人
        url = "http://www.tuling123.com/openapi/api?key=%s&info=" % (tulingkey)
        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(hotReload=True)
    # 获取自己的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()                      
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值