python 使微信自動回復
阿新 • • 發佈:2019-02-15
caption end cap map eat %s 就是 tro 原理
https://zhuanlan.zhihu.com/p/308999073
今天是鄙人的生日,歡luo過後想寫點關於itchat的文章~
(不小心暴露年齡了,是的,我已經16歲了~~)
言歸正傳,這裏說的自動回復包括了兩種:一個是類似QQ的“【自動回復】”,就是一句自己設置的固定的話,別人以給你發消息你就自動回復這句話;二是類似Siri的智能回復,就是找了一個機器人代替你聊天,哈哈,雖然賤賤的但是我真的很討厭微信聊天。
一、運行環境和看懂下文需要的知識
1、Python基本語法。這個如果不清楚的話,先學習下吧,幾天就看完了:
Python基本知識
2、Linux系統。當然這個不是必須的,如果你只是想試驗一下的話完全可以在windows下,Python可以跨平臺的,不過畢竟我想24h跑這個腳本,那就最好用服務器,服務器大部分是Linux的,我用的是阿裏雲ECS CentOS release 6.5。
二、基本原理
1、針對第一種類QQ的自動回復,這個很簡單,就是收到消息就向發送者發送一條固定字符串就行了。
2、針對第二種類Siri的智能回復,這個需要調用圖靈機器人(Turing Robort),就是將收到的消息發送給Turing,再把Turing回復的消息發送給發送者。
3、有一些問題需要解決
- 如何區別這兩種自動回復呢?類QQ自動回復針對所有人,不針對群消息(估計1分鐘內就被踢出群!),向自己發送消息“開啟自動回復”,則便開啟了對所有人的類QQ自動回復;向自己發送消息“關閉自動回復”,則便關閉了對所有人的類QQ自動回復。類Siri消息針對指定人,也是不針對群消息,向對方發送消息“= =” (你可以自己換成別的),便開啟了智能回復;向對方發送消息“x x”,則關閉智能回復。
- 只針對某個人或者某些人開啟智能回復呢?在腳本中增加一個需要對其開啟智能回復的人的list,只有這些人發的消息才會自動回復。
三、代碼實現
1、申請Turing機器人的對外接口key
註冊圖靈機器人
添加一個機器人,設置機器人跟你的名字一樣,其他信息也一樣,因為有時候這個傻子會以第三人稱來回復消息,比如“帥帥覺得這個很不錯!”,設置好,不容易露餡!
最關鍵的是拿到APIkey,然後替換掉下面代碼中的“replaceKeyByYourKey”。
2、python源代碼
#coding=utf8
import itchat
from itchat.content import TEXT
from itchat.content import *
import sys
import time
import re
import requests, json
import aiml
import os
# When recieve the following msg types, trigger the auto replying.
@itchat.msg_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO],isFriendChat=True, isMpChat=True)
def text_reply(msg):
global auto_reply, robort_reply, peer_list
# The command signal of "[自動回復]"
if msg[‘FromUserName‘] == myUserName and msg[‘Content‘] == u"開啟自動回復":
auto_reply = True
itchat.send_msg(u"[自動回復]已經打開。\n", msg[‘FromUserName‘])
elif msg[‘FromUserName‘] == myUserName and msg[‘Content‘] == u"關閉自動回復":
auto_reply = False
itchat.send_msg(u"[自動回復]已經關閉。\n", msg[‘FromUserName‘])
# elif not msg[‘FromUserName‘] == myUserName:
else:
if auto_reply == True:
itchat.send_msg(u"[自動回復]您好,我現在有事不在,一會再和您聯系。\n", msg[‘FromUserName‘])
else:
‘‘‘
For none-filehelper message,
if recieve ‘= =‘, start robort replying.
if recieve ‘x x‘, stop robort replying.
‘‘‘
if msg[‘Content‘] == u"= =":
robort_reply = True
peer_list.append(msg[‘ToUserName‘])
return
elif msg[‘Content‘] == u"x x":
robort_reply = False
peer_list.remove(msg[‘ToUserName‘])
return
# Let Turing reply the msg.
if robort_reply == True and msg[‘FromUserName‘] in peer_list:
# Sleep 1 second is not necessary. Just cheat human.
time.sleep(1)
cont = requests.get(‘http://www.tuling123.com/openapi/api?key=replacekeyByYourKey&info=%s‘ % msg[‘Content‘]).content
m = json.loads(cont