微信聊天机器人

python

浏览数:513

2019-1-8

import requests
import itchat
import time
from threading import Timer

KEY = '8f7fcbf19bab471e8067e2783e95b924'

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

def isMsgFromMyself(msgFromUserName):
   
    global myName
    return myName == msgFromUserName
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    global autoReplyFlag,  timerSet, noReply, t  
    print(msg['Text'])
    if isMsgFromMyself(msg['FromUserName']):
        print("Replied!!")
        autoReplyFlag = False
        noReply = False
        try:
            t.cancel()
            print("Timer Canceled")
            timerSet = False
        except:
            pass
        return None

    if autoReplyFlag:
           
        defaultReply = 'I received: ' + msg['Text']
        
        reply = get_response(msg['Text'])
        
        return reply or defaultReply
    else:
        noReply = True
        if not timerSet:
            
            print("Timer setting")
            t = Timer(12, sendBusyStatus, [msg['FromUserName']])
            t.start()
            timerSet = True

def sendBusyStatus(UserName):
    global noReply, autoReplyFlag, timerSet
    print("Timer Working!")
    if noReply:
        itchat.send("我的主人不知道在干嘛!让我先陪你聊一会", UserName)
        autoReplyFlag = True
        timerSet = Falseitchat.auto_login()

autoReplyFlag, timerSet, noReply = False, False, False
t = 0  
myName = itchat.get_friends(update=True)[0]['UserName']
itchat.run()