python利用圖靈機(jī)器人實(shí)現(xiàn)微信好友自動(dòng)回復(fù)

安裝

安裝python3環(huán)境,請(qǐng)找度娘。
pip install itchat
pip install requests

抓取網(wǎng)頁(yè)

def getHtmlText(url):
        try:
                r = requests.get(url,timeout=30)
                r.raise_for_status()
                r.encoding = r.apparent_encoding
                return r.text
        except:
                return ""

當(dāng)接收到的消息是Text時(shí)自動(dòng)回復(fù)

@itchat.msg_register(['Text','Map', 'Card', 'Note', 'Sharing', 'Picture'])
def text_reply(msg):
    # 當(dāng)消息不是由自己發(fā)出的時(shí)候 if not msg['FromUserName'] == Name["自己微信號(hào)"]:
    # 或者指定微信好友
    if msg['FromUserName'] == Name["好友微信昵稱"]:
        # 回復(fù)給好友
        tulingkey = "***********"  #注冊(cè)圖靈官網(wǎng)申請(qǐng)自己的機(jī)器人
        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

# 抓取網(wǎng)頁(yè)
def getHtmlText(url):
        try:
                r = requests.get(url,timeout=30)
                r.raise_for_status()
                r.encoding = r.apparent_encoding
                return r.text
        except:
                return ""

# 自動(dòng)回復(fù)
@itchat.msg_register(['Text','Map', 'Card', 'Note', 'Sharing', 'Picture'])
def text_reply(msg):
    # 當(dāng)消息不是由自己發(fā)出的時(shí)候 if not msg['FromUserName'] == Name["自己微信號(hào)"]:
    # 或者指定微信好友
    if msg['FromUserName'] == Name["好友微信昵稱"]:
        # 回復(fù)給好友
        tulingkey = "***********"  #注冊(cè)圖靈官網(wǎng),申請(qǐng)自己的機(jī)器人
        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()                      
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容