itchat可以很简单的实现自动回复,通过增加线程,修改代码实现完全终端微信聊天。
#coding=utf8
import requests
import itchat
import time
import csv
import datetime
import pandas as pd
import numpy as np
import threading
KEY = '8edce3ce905a4c1dbb965e6b35c3834d'
threads=[]
def get_response(msg): #通过改下面的代码,也可以自动回复
apiUrl = 'http://www.tuling123.com/openapi/api'
data = {
'key' : KEY,
'info' : msg,
'userid' : 'wechat-robot',
}
try:
r = requests.post(apiUrl, data=data).json()
return r.get('text')
except:
return
@itchat.msg_register(itchat.content.TEXT)
def mes_reply(): #定义回复函数,回复是,先输入想要回复的人或群的前面的标识数字,然后输入一个空格,再输入回复消息即可回复。
while(1):
try:
MES=[]
MES=raw_input()
i=int(MES[0]) #获取标识
s=MES[2:]
itchat.send("%s"%(s.decode('utf-8')),mes_list[i])
except:
print "error"
mes_list=[] #存放FromUserName
t = threading.Thread(target=mes_reply) #开启并行线程
t.setDaemon(True)
t.start()
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
if (msg['FromUserName'] not in mes_list) :
mes_list.append(msg['FromUserName'])
print mes_list.index(msg['FromUserName']),msg['User']['NickName'].encode('utf-8'),msg['User']['RemarkName'].encode('utf-8'),msg['Content'].encode('utf-8')
@itchat.msg_register(itchat.content.TEXT,isGroupChat=True)
def text_reply(msg):
if (msg['User']['UserName'] not in mes_list) :
mes_list.append(msg['User']['UserName'])
csv_writer.writerow(row)
print mes_list.index(msg['User']['UserName']),msg['User']['NickName'].encode('utf-8'),msg['ActualNickName'].encode('utf-8'),msg['User']['RemarkName'].encode('utf-8'),msg['Content'].encode('utf-8')
@itchat.msg_register([itchat.content.PICTURE,itchat.content.RECORDING,itchat.content.ATTACHMENT,itchat.content.VIDEO],isGroupChat=True)
def download_files(msg): #保存记录接受的图片、表情等信息。
print msg['Text']
msg['Text']('地址'+msg['FileName'])
@itchat.msg_register([itchat.content.PICTURE,itchat.content.RECORDING,itchat.content.ATTACHMENT,itchat.content.VIDEO])
def download_file(msg):
print msg['Text']
msg['Text']('地址'+msg['FileName'])
itchat.auto_login(hotReload=True)
itchat.run()