#coding=utf8
import sys ,json 
import time ,requests
reload(sys)
sys.setdefaultencoding('utf8')
import itchat, time ,string
from itchat.content import *

import urllib2,string,json 

import sys,os,re  
import time  






#图灵机器人接口
KEY = '3xxxxxxxxxxxxxxx'

def get_tulingresponse(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        print r
        #return  r.get('text').replace('图灵','AIWALY')
    if    r.get('url') :
            return r.get('text').replace('图灵','AIWALY') +"\n" + r.get('url').replace('图灵','AIWALY')
    else :
            return  r.get('text').replace('图灵','AIWALY')
    except:
        return








def timestamp_datatime(value):  
    #format = '%Y-%m-%d %H:%M'  
    format = '%Y-%m-%d %H:%M:%S'  
    #value 为时间戳值,如:1460073600.0  
    value = time.localtime(value)  
    dt = time.strftime(format,value)  
    return dt  





# 处理文本类消息
# 包括文本、位置、名片、通知、分享
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    # 微信里,每个用户和群聊,都使用很长的ID来区分
    # msg['FromUserName']就是发送者的ID
    # 将消息的类型和文本内容返回给发送者




    if (msg['Text'].find('讲个笑话') != -1):  
        RequestMessage="讲个笑话"    

    elif (msg['Text'].find('讲个故事') != -1):      
        RequestMessage="讲个故事" 
    elif (msg['Text'].find('北京天气') != -1):      
        RequestMessage="北京天气"     
    elif (msg['Text'].find('荤段子') != -1):
        RequestMessage="北京天气" 
    elif (msg['Text'].find('段子') != -1):

        RequestMessage="讲个笑话" 

    else: 
        RequestMessage=msg['Text']
    ReceiveMessage=get_tulingresponse(RequestMessage)
    itchat.send(ReceiveMessage,msg['FromUserName'])



    #print msg

    #logfile.write(json.dumps(msg) + '\n')
    message="""{"type"="message","CreateTime"="%s","NickName"="%s","FromUserName"="%s","Text"="%s","ReceiveMessage"="%s"}""" %(timestamp_datatime(msg['CreateTime']),msg['User']['NickName'].encode('utf-8'),msg['FromUserName'],msg['Text'],ReceiveMessage)
    print message
    print get_tulingresponse(msg['Text'])
    logfilemessage.write(  message + '\n' )
    itchat.send(message, toUserName='store6')
    logfilemessage.flush()





# 处理多媒体类消息
# 包括图片、录音、文件、视频
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
  # msg['Text']是一个文件下载函数
  # 传入文件名,将文件下载下来
  msg['Text'](msg['FileName'])
  # 把下载好的文件再发回给发送者
  return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])

# 处理好友添加请求
@itchat.msg_register(FRIENDS)
def add_friend(msg):
  # 该操作会自动将新好友的消息录入,不需要重载通讯录
  itchat.add_friend(**msg['Text']) 
  # 加完好友后,给好友打个招呼
  itchat.send_msg('您好!我是自助机器人AIWALY小鹏鹏,很高兴人认识你!目前开发完善中![微笑]', msg['RecommendInfo']['UserName'])
  #print msg
  MessageTopengpeng="""{"type"="add_friend","NickName"="%s","UserName"="%s"}""" %(msg['RecommendInfo']['NickName'],msg['RecommendInfo']['UserName'])
  #itchat.send("add_friend" + MessageTopengpeng ,  toUserName='filehelper' )
  itchat.send("add_friend" + MessageTopengpeng ,  toUserName='store6' )
  logfilemessage.write( "add_friend|" +MessageTopengpeng+ '||||\n' )

  logfilemessage.flush()


@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):

    #print msg 
    print msg['User']['NickName']+" "+ msg['Text']
    RequestMessage=""
    ReceiveMessage=""



    if msg['isAt']:
        #msg['Text']=msg['Text'].split("  ")[1]
    print msg['Text']
        if (msg['Text'].find('黄段子') != -1):
              RequestMessage='黄段子'
        elif (msg['Text'].find('讲个笑话') != -1):      
              RequestMessage='讲个笑话'
        elif (msg['Text'].find('讲个故事') != -1):      
              RequestMessage='讲个故事'
        elif (msg['Text'].find('北京天气') != -1):      
              RequestMessage='北京天气'    
        elif (msg['Text'].find('荤段子') != -1):
              RequestMessage='荤段子'
        elif (msg['Text'].find('段子') != -1):
              RequestMessage='讲个笑话'

        else: 

              RequestMessage=msg['Text']

    elif (msg['Text'].encode('utf-8','ignore').startswith(u'段子')):
        RequestMessage='讲个笑话'    
    elif (msg['Text'].encode('utf-8','ignore').startswith(u'天气') or msg['Text'].encode('utf-8','ignore').   startswith(u'曹哥')):
        RequestMessage="北京天气"    

    else: 
        RequestMessage=""



    if(RequestMessage):
    ReceiveMessage=get_tulingresponse(RequestMessage)
        itchat.send(ReceiveMessage,msg['FromUserName'])


    message="""{"type"="group","CreateTime"="%s","NickName"="%s","ActualNickName"="%s","FromUserName"="%s","ActualUserNam"="%s","Text"="%s","ReceiveMessage"="%s"}"""  %(timestamp_datatime(msg['CreateTime']),msg['User']['NickName'],msg['ActualNickName'],msg['FromUserName'], msg['ActualUserName'], msg['Text'],ReceiveMessage)
    #print msg
    print message


    logfilemessage.write(  message + '\n' )

    logfilemessage.flush()

logfilemessage=open('weixingmessage.log','a')
itchat.auto_login(enableCmdQR=2,hotReload=True)
itchat.run()

logfilemessage.close
文档更新时间: 2019-06-14 13:38   作者:月影鹏鹏