用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
複製代碼
相關文章
相關標籤/搜索