天天看點

用Python實作簡單的微信自動回複wechat_autoreply

wechat_autoreply

簡介

    無意中看到GitHub上的大佬給女朋友寫的每日定時發送微信消息的程式,想到自己經常也因為各種事情沒看到女朋友的消息,導緻自己跪搓衣闆,是以想自己也學習一下如何實作一個微信自動回複的功能,順便學習學習。

  本程式功能較為簡單,運作程式,輸入要自動回複對象的微信備注名和要自動回複的内容,然後登入微信,即可實作對指定對象的消息自動回複。

  程式中主要用到了itchat這個庫,它是一個基于微信網頁版的接口微信庫,可以實作對微信的各種操作。

實作功能

查詢日期;查詢天氣;機器人聊天。

配置環境及依賴

語言:

Python 3.5 及以上
           

依賴庫:

itchat
datetime
requests
           

天氣查詢API:

http://t.weather.sojson.com/api/weather/city/{city_code}
           

聊天機器人:

圖靈機器人 http://www.turingapi.com
           

程式說明

擷取天氣資訊

    這裡主要參考了https://github.com/sfyc23/EverydayWechat這位大神的方法,用了一個存有全國格城市對應代碼的清單,根據城市代碼在接口中查詢對應天氣狀況。

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請求資料即可。

示例:

#圖靈機器人接口
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官方文檔:http://itchat.readthedocs.io

itchatGitHub網址:https://github.com/littlecodersh/ItChat

它通過一個裝飾器實作對微信消息的監聽:

@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連結。

項目位址

https://github.com/hh997y/wechat_autoreply

小結

    很簡單的一個小項目,幾乎沒什麼技術含量,可以拿來練練手,也可以在這上面豐富其它更多有意思的東西,也算是每天學習進步一點點哈哈,提升自己的姿勢水準。

參考

https://github.com/sfyc23/EverydayWechat
https://blog.csdn.net/coder_pig/article/details/81357810
https://blog.csdn.net/Lynn_coder/article/details/79436539