用Python实现简单的微信自动回复

wechat_autoreply


简介

    无心中看到GitHub上的大佬给女友写的每日定时发送微信消息的程序,想到本身常常也由于各类事情没看到女友的消息,致使本身跪搓衣板,因此想本身也学习一下如何实现一个微信自动回复的功能,顺便学习学习。   本程序功能较为简单,运行程序,输入要自动回复对象的微信备注名和要自动回复的内容,而后登陆微信,便可实现对指定对象的消息自动回复。   程序中主要用到了itchat这个库,它是一个基于微信网页版的接口微信库,能够实现对微信的各类操做。python


实现功能

查询日期;查询天气;机器人聊天。git


配置环境及依赖

语言:github

Python 3.5 及以上
复制代码

依赖库:json

itchat
datetime
requests
复制代码

天气查询API:api

http://t.weather.sojson.com/api/weather/city/{city_code}
复制代码

聊天机器人:微信

图灵机器人 http://www.turingapi.com
复制代码

程序说明

获取天气信息

    这里主要参考了https://github.com/sfyc23/EverydayWechat这位大神的方法,用了一个存有全国格城市对应代码的列表,根据城市代码在接口中查询对应天气情况。app

def isJson(resp):
    try:
        resp.json()
        return True
    except:
        return False

#获取天气信息
def get_weather_info(city_code):
    weather_url = f'http://t.weather.sojson.com/api/weather/city/{city_code}'
    resp = requests.get(url=weather_url)
    if resp.status_code == 200 and isJson(resp) and resp.json().get('status') == 200:
        weatherJson = resp.json()
        # 今日天气
        today_weather = weatherJson.get('data').get('forecast')[1]
        # 温度
        high = today_weather.get('high')
        high_c = high[high.find(' ') + 1:]
        low = today_weather.get('low')
        low_c = low[low.find(' ') + 1:]
        temperature = f"温度 : {low_c}/{high_c}"
        # 空气指数
        aqi = today_weather.get('aqi')
        aqi = f"空气质量 : {aqi}"
        # 天气
        tianqi = today_weather.get('type')
        tianqi = f"天气 : {tianqi}"

        today_msg = f'{tianqi}\n{temperature}\n{aqi}\n'
        return today_msg
复制代码
图灵机器人接口

    这里用到的是http://www.turingapi.com这里的图灵机器人,只须要在网站注册并建立机器人,得到每一个用户独有的"userId"和每一个机器人独有的"apiKey",根据其要求的请求参数,向其接口http://openapi.tuling123.com/openapi/api/v2请求数据便可。post

示例:学习

#图灵机器人接口
def robot(info):
    #info = msg['Content'].encode('utf8')
    # 图灵API接口
    api_url = 'http://openapi.tuling123.com/openapi/api/v2'
    # 接口请求数据
    data = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": str(info)
            }
        },
        "userInfo": {
            "apiKey": "XXX...XXX",  #每一个机器人独有的apiKey
            "userId": "XXXXXX"      #每一个用户独有的userId 
        }
    }
    headers = {
        'Content-Type': 'application/json',
        'Host': 'openapi.tuling123.com',
        'User-Agent': 'Mozilla/5.0 (Wi`ndows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3486.0 '
                      'Safari/537.36 '
    }
    # 请求接口
    result = requests.post(api_url, headers=headers, json=data).json()
    # 提取text,发送给发信息的人
    return result['results'][0]['values']['text']
复制代码

上面一段程序输入info,经过接口返回机器人的回复。网站

itchat微信微信接口

itchat官方文档:itchat.readthedocs.io itchatGitHub网址:github.com/littlecoder… 它经过一个装饰器实现对微信消息的监听:

@itchat.msg_register(itchat.content.TEXT)
复制代码

其中,括号内为itchat监听的消息类型,TEXT表示对文字内容进行监听,此外itchat还支持多种消息类型,如: MAP             地理位置的分享 CARD           名片信息 SHARING        连接分享 PICTURE        表情或照片 RECORDING     语音 ATTACHMENT    附件 VIDEO           视频 FRIENDS         加好友申请,也就是说发起的一个好友申请实际上是一条特殊的信息 SYSTEM         系统消息,好比系统推送消息或者是某个群成员发生变更等等 NOTE            通知文本,好比撤回了消息等等   而后经过使用:

itchat.send(text, toUserName=userName)
复制代码

向指定对象回复消息。其中的userName并非微信名,是一串数字字母的代码,因此咱们能够从刚才监听获取的消息中获得向咱们发送消息的对象的userName,即:

userName = msg['User']['UserName']
复制代码

而后咱们能够用:

msg['User']['RemarkName']
复制代码

来经过对对象的微信备注名的对比来判断是不是女友,是不是咱们要回复的对象。我这里只能有一个对象,固然有些人可能有多个女友的,容我献上本身的双膝。。。

回复代码示例:

@itchat.msg_register([itchat.content.TEXT,itchat.content.PICTURE])
def reply_msg(msg):
    global t, name, rtext
    userName = msg['User']['UserName']
    if t == 2:
        if msg['User']['RemarkName'] == name:
            if msg['Content'] == "退出":
                itchat.send("机器人已退出", toUserName=userName)
                t = 0
            else:
                text = msg['Content']
                rep = robot(text)
                itchat.send(rep+"\n回复“退出”,退出机器人聊天", toUserName=userName)
    elif t == 1:
        if msg['User']['RemarkName'] == name:
            ctn = msg['Content']
            if ctn in city_dict.city_dict:
                city_code = city_dict.city_dict[ctn]
                wheather = get_weather_info(city_code)
                itchat.send(wheather, toUserName=userName)
            else:
                itchat.send("没法获取您输入的城市信息", toUserName=userName)
        t = 0
    else:
        if msg['User']['RemarkName'] == name:
            if msg['Content'] == '你好':
                itchat.send('你好', toUserName=userName)
            elif msg['Content'] == '天气':
                itchat.send('请输入您要查询的城市名', toUserName=userName)
                t = 1
            elif msg['Content'] == '日期':
                itchat.send(nowdate, toUserName=userName)
            elif msg['Content'] == '聊天':
                itchat.send('你好,我是人工智障', toUserName=userName)
                t = 2
            else:
                itchat.send(rtext + ',自动消息\n回复“日期”,获取日期\n回复“天气”,获取天气\n回复“聊天”,开始和机器人聊天', toUserName=userName)
复制代码

这样咱们就能够对指定对象实现自动回复,而且实现简单的获取日期、天气和机器人聊天的功能。关于itchat我也是刚接触,讲得不详细,具体更多指导内容能够详见上面的官方文档和GitHub连接。


项目地址

github.com/hh997y/wech…


小结

    很简单的一个小项目,几乎没什么技术含量,能够拿来练练手,也能够在这上面丰富其它更多有意思的东西,也算是天天学习进步一点点哈哈,提高本身的姿式水平。


参考

https://github.com/sfyc23/EverydayWechat
https://blog.csdn.net/coder_pig/article/details/81357810
https://blog.csdn.net/Lynn_coder/article/details/79436539
复制代码
相关文章
相关标签/搜索