#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 = 'xxxxxxxxx'

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 signin(name,msg):
        # 查找公众号,进行签到

        user = itchat.search_mps(name='tqyb')
        print user 
        #UserName = user[0]['UserName']
        itchat.send(msg , toUserName="@1bb5209510385ea7963fb2c9eb4fed9a")
        #itchat.dump_login_status()
        #pickleDumps('flag', localDay)  # 如果执行成功写入标致文件
        #exit()





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
    # 将消息的类型和文本内容返回给发送者
    print msg
    print itchat.update_friend("store6") 
    print itchat.get_mps( 'bj-tqyb')
    RequestMessage=""
    ReceiveMessage=""
    ReceiveMessageDefault=""

    if (msg['User']['PYQuanPin']=="yueyingpengpeng"):  
        if(msg['Text'].startswith(u'To:')):
             msg_array=msg['Text'].split(':', 2 )
             print "%s %s %s" %(msg_array[0] ,msg_array[1] ,msg_array[2])
             itchat.send(msg_array[2],   msg_array[1])
             RequestMessage=msg_array[2]
        elif(msg['Text'].startswith(u'Add:')): 
             msg_array=msg['Text'].split(':', 2 )
             print "%s %s %s" %(msg_array[0] ,msg_array[1] ,msg_array[2])
             itchat.add_friend(msg_array[1], status=2, verifyContent=msg_array[2], autoUpdate=True)
        elif (msg['Text'].startswith(u'Signin')):  
             msg_array=msg['Text'].split(':', 2 )
             print "%s %s %s" %(msg_array[0] ,msg_array[1] ,msg_array[2])
             signin(msg_array[1],msg_array[2])

    elif (msg['Text'].find('讲个故事') != -1):      
        RequestMessage="讲个故事" 
    elif (msg['Text'].find('北京天气') != -1) or (msg['Text'].encode('utf-8','ignore').startswith(u'天气'))  :      
        RequestMessage="北京天气"     
    elif (msg['Text'].find('荤段子') != -1):
        RequestMessage="北京天气" 
    elif (msg['Text'].find('段子') != -1):

        RequestMessage="讲个笑话" 
    elif (msg['Text'].find('帮助') != -1):
        ReceiveMessageDefault='''我是智能客服,只有"讲个故事","讲个笑话","北京天气"等关键字,各别功能只对vip用户开放'''

    else:
        RequestMessage=""





    if(ReceiveMessageDefault):
        itchat.send(ReceiveMessageDefault,msg['FromUserName'])

    elif(RequestMessage):
    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['User']['UserName'],msg['Text'],ReceiveMessage)
    print message
    print ReceiveMessage
    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=""
    ReceiveMessageDefault=""




    if msg['isAt']:

        LiaoTianGroup=["@a3b56eadcffa7c06ca488c98d4c9ca58" , "@28c8d9018d29e77f9af1a4d8a2fb3b500998eaed432f4319b42f22aad0efe5b1" ,
        "@@40ee5b12ebc190c7dd656ecedc77b79f7956a88442bff99619fc200a84535d23",
        "@0aac6fc4c227ffa07e2b01eb1c6f4c8d5a96222e4621b5f7cd5633be510cfde7",
        "@73b2c7d2cdcee9ac6e29e9b0f514249e" ,
        "@82cdb2c5b7f5bb154a282d6a9df04bb6",
        "@7c94c1a48863e557964ddee82bfbec3f"]      
        #msg['Text']=msg['Text'].split("  ")[1]
    print msg['Text']
        if (msg['Text'].find('黄段子') != -1):
        #if (msg['User']['EncryChatRoomId']in LiaoTianGroup ): 
             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: 
                   #ReceiveMessageDefault='''我是智能客服,只有"讲个故事","讲个笑话","北京天气"等关键字,各别功能只对vip用户开放'''
                RequestMessage=msg['Text']

        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='荤段子'
        elif (msg['Text'].find('帮助') != -1):
              ReceiveMessageDefault='''我是智能客服,只有"讲个故事","讲个笑话","北京天气"等关键字,各别功能只对vip用户开放'''

        else: 
              #ReceiveMessage="[微笑]"
          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'曹哥'))or msg['Text'].startswith(u'北京天气') :
        RequestMessage="北京天气"    

    else: 
        RequestMessage=""

    if(ReceiveMessageDefault):
        itchat.send(ReceiveMessageDefault,msg['FromUserName'])

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


    message="""{"type"="group","CreateTime"="%s","NickName"="%s","ActualNickName"="%s","FromUserName"="%s","ActualUserName"="%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-07-18 17:39   作者:月影鹏鹏