def get_opeind(appid, path):
    openid = 'NULL'
    a = FileOperation.FileExsit(os.getcwd() + path)
    if a == True:
        file = open(os.getcwd() + path, "r")
        for line in file.readlines():
            if line[0] == '#' or line[0] == '#' or len(line.strip()) == 0:
                pass
            else:
                app_openid = eval(line.decode(encoding='utf-8'))
                # print app_openid
                if app_openid['appid'] != appid:
                    continue
                else:
                    openid = app_openid['openid']
    else:
        print '请检查/appid/appidlist.txt文件是否存在。'
        send_emails.send_failEmail('请检查/appid/appidlist.txt文件是否存在。')

    return openid
def menu_dict(menu):
    menudict = {}
    for i in range(0, len(menu)):
        tmp_dict = menu[i]
        menu_id=tmp_dict['id']
        menu_name=tmp_dict['menu_name']
        menu_key=tmp_dict['menu_key']
        menu_type=tmp_dict['menu_type']
        view_url=tmp_dict['view_url']
        reply_id=tmp_dict['reply_id']
        is_del=tmp_dict['is_del']
        if is_del=='N':
            if menu_type=='click':
                dict={}
                dict['MenuId'] = menu_id
                dict['Event'] = 'CLICK'
                # dict['is_del'] = is_del
                dict['reply_id'] = reply_id
                dict['EventKey']=menu_key
                dict['MENUNAME']=menu_name
                menudict[menu_key] = dict

            elif menu_type=='view':
                dict = {}
                dict['MenuId'] = menu_id
                dict['Event'] = 'VIEW'
                # dict['is_del'] = is_del
                dict['reply_id'] = reply_id
                dict['EventKey'] = view_url
                dict['MENUNAME'] = menu_name
                menudict[menu_key] = dict
            else:
                # print menu[i]
                send_emails.send_failEmail(tmp_dict)
        else:
            print '获取菜单对应关系失败--map_function'
    dict_str = eval(json.dumps(menudict, ensure_ascii=False))
    # print dict_str
    return dict_str
def get_appidinfo(getvalue_dict):
    today = str(time.strftime("%Y-%m-%d %H.%M", time.localtime(time.time())))
    a = FileOperation.FileExsit(os.getcwd() + r'/log/failresult.html')
    if a == True:
        FileOperation.Copy_file(
            os.getcwd() + r'/log/failresult.html',
            os.getcwd() +
            r'/log/failresult_history/failresult_%s.html' % today)
        FileOperation.DelFile(os.getcwd() + r'/log/failresult.html')
    b = FileOperation.FileExsit(os.getcwd() + r'/log/static.txt')
    if b == True:
        FileOperation.Copy_file(
            os.getcwd() + r'/log/static.txt',
            os.getcwd() + r'/log/staticlog/static_%s.txt' % today)
        FileOperation.DelFile(os.getcwd() + r'/log/static.txt')
    app_openid_data = []
    # print getvalue_dict
    path = getvalue_dict['appid']
    # print path
    a = FileOperation.FileExsit(os.getcwd() + path)
    if a == True:
        file = open(os.getcwd() + path, "r")
        for line in file.readlines():
            if line[0] == '#' or line[0] == '#' or len(line.strip()) == 0:
                pass
            else:
                app_openid = eval(line.decode(encoding='utf-8'))
                app_openid_data.append(app_openid)
                # appid = line.strip('\n').decode(encoding='utf-8')
                # appidlist.append(appid)
        file.close()
        # print app_openid_data
        return app_openid_data

    else:
        print '请检查/appid/appidlist.txt文件是否存在。'
        send_emails.send_failEmail('请检查/appid/appidlist.txt文件是否存在。')
        return 'NULL'
def key_dict(AutoReply):
    keydict = {}
    for i in range(0, len(AutoReply)):
        tmp_dict = AutoReply[i]
        # print tmp_dict
        words = tmp_dict["words"]
        is_del=tmp_dict['del_time']
        tmp_reply=tmp_dict["reply_content"]
        reply_content_type=tmp_dict['reply_content_type']
        if type(words) == dict and is_del == '0':
            words = words.values()
        elif type(words)==list:
            pass
        elif words=='':
            continue
        else:
            print '该种关键词类型暂不支持--map_function'
            send_emails.send_failEmail(tmp_dict)
        if type(words)==list and is_del=='0':
            for i in range(0, len(words)):

                reply_content = {}
                re_key = words[i]
                # print re_key
                reply_content['reply_content']=tmp_reply
                reply_content['reply_content_type']=reply_content_type
                reply_content['MENUNAME'] = '关键词,非菜单'
                keydict[re_key] = reply_content
                # print '回复',reply_content['reply_content']
        else:
            print '获取关键词对应关系失败——map_function'


    dict_str=eval(json.dumps(keydict,ensure_ascii=False))
    # print dict_str
    return dict_str
Beispiel #5
0
def pushdata(pushper_dict, getvalue_dict,key,reply_relation, to_xml):
    # print etree.tostring(to_xml)

    token=pushper_dict['token']
    appid = getvalue_dict['appid']
    http=pushper_dict['pushhttp']
    Third_appid=pushper_dict['Third_appid']
    encodingAESKey=pushper_dict['encodingAESKey']
    authtype=getvalue_dict['authtype']
    General=pushper_dict['General']
    global code

    Unencrypt_xml=etree.tostring(to_xml, encoding="UTF-8")

    timestamp = etree.fromstring(Unencrypt_xml).find('CreateTime').text
    openid = etree.fromstring(Unencrypt_xml).find('FromUserName').text
    if authtype=='1':
        msg_encrypt=Unencrypt_xml
    elif authtype=='3':
        msg_encrypt = MesCrypt.encrypt(encodingAESKey, Third_appid, Unencrypt_xml)  ######XML数据加密
    else:
        send_emails.send_failEmail('该种授权类型不属于已知类型%s,请联系相关人员进行添加'%str(authtype))
        return {'authtype': authtype, 'request_url': http, 'request_xml': Unencrypt_xml, 'result_decrypt': '该种授权类型不属于已知类型%s,请联系相关人员进行添加'%str(authtype)}
    nonce = str(random.randint(1000000000, 9999999999))
    encrypt_type = 'aes'
    # print  token ,timestamp,nonce
    signstr = ''.join(sorted([token, timestamp, nonce]))      ####按照升序排列,拼成字符串

    signature = hashlib.sha1(signstr).hexdigest()
    Msg_signstr = ''.join(sorted([token, timestamp, nonce, msg_encrypt]))
    Msg_Signature = hashlib.sha1(Msg_signstr).hexdigest()
    # print 'signature:%s  &  Msg_Signature:%s'%(signature, Msg_Signature)
    data = collections.OrderedDict()
    ToUserName=etree.fromstring(Unencrypt_xml).find('ToUserName').text
    if authtype=='3':
        data['ToUserName'] = '******' % ToUserName
        data['Encrypt'] = '<![CDATA[%s]]>'%msg_encrypt
        data['from']='<![CDATA[QA-check]]>'
        ele = etree.Element('xml')
        for ke, val in data.items():
            child = etree.Element(ke)
            child.text = str(val)
            ele.append(child)
        encrypt_xml=unescape(etree.tostring(ele))
        url = '%ssignature=%s&timestamp=%s&nonce=%s&openid=%s&encrypt_type=%s&msg_signature=%s' % (
        http, signature, timestamp, nonce, openid, encrypt_type, Msg_Signature)
    elif authtype == '1':
        encrypt_xml=Unencrypt_xml
        appid=General['appid']
        uniqueid=General['uniqueid']
        url = '%ssignature=%s&timestamp=%s&nonce=%s&openid=%s&uniqueid=%s&appid=%s' % (http, signature, timestamp, nonce, openid, uniqueid, appid)
    headers = {'Content-Type': 'text/xml'}
    starttime = time.time()

    # try:
    req = requests.post(url=url, data=encrypt_xml, headers=headers, timeout=10)
    result = req.text

    mutex.acquire()
    taketime = time.time() - starttime
    # print pushper_dict
    # print getvalue_dict
    print '\n****Request_URL****: \n%s\n****Unencrypt_XML****: \n%s\n****Request_EncryptXML****: \n%s' % (url, Unencrypt_xml, encrypt_xml)
    print '*Request time: %s ms' % int(taketime * 1000)
    print '*Status_code: %s' % req.status_code
    if req.status_code==200:
        if result:
            if authtype=='3':
                result_statu,result_decrypt=MesCrypt.decrypt(encodingAESKey, Third_appid, result)
            elif authtype=='1':
                result_statu,result_decrypt=MesCrypt.nodecrypt(result)
            else:
                result_statu='FAIL'
                result_decrypt=result
        else:
            result_statu='NULL'
            print '\nSTATUS=200,请求成功,无返回结果!'
            result_decrypt='STATUS=200,请求成功,无返回结果!'
    else:
        result_statu='FAIL'
        result_decrypt=str(req.status_code)

    pushinfo_dict={'result_statu':result_statu,'request_url':str(req.url),'request_xml':encrypt_xml,'Unencrypt_xml':Unencrypt_xml,'result_decrypt':result_decrypt}

    if to_xml.find('MsgType').text=='text' or to_xml.find('Event').text == 'subscribe':
        request_url, request_xml, result_sign = Compare.Reply_Compare(reply_relation,key,getvalue_dict, pushinfo_dict)
        if result_sign == 'pass':
           code='200'
        elif result_sign == 'fail':
            code = '400'
        else:
            code = '400'
    elif to_xml.find('Event').text == 'VIEW':
        if pushinfo_dict['result_statu']=='NULL':
            print '\n 页面跳转类型,数据推送成功,无需验证!'
            code = '200'
        else:
            code = '500'
            writelog.errorlog(pushinfo_dict['request_url'], pushinfo_dict['request_xml'], pushinfo_dict['result_decrypt'])
            # send_emails.sendEmail(pushinfo_dict['request_url'], pushinfo_dict['request_xml'], result_decrypt, key, str(reply_relation['reply_content']), '接口推送数据失败!')
            # send_emails.send_failEmail('推送数据失败:%s' % str(pushinfo_dict))
    elif to_xml.find('Event').text == 'CLICK':
        if reply_relation['reply_id'] == '0':
            code = '200'
        else:
            request_url, request_xml, result_sign = Compare.Reply_Compare(reply_relation, key,getvalue_dict, pushinfo_dict)
            if result_sign == 'pass':
                code = '200'
            elif result_sign == 'fail':
                code = '400'
            else:
                code = '400'
    else:
        code = '400'
        writelog.errorlog(pushinfo_dict['request_url'], pushinfo_dict['request_xml'], pushinfo_dict['result_decrypt'])
        send_emails.send_failEmail('该种事件类型暂不支持,请联系相关人员进行添加:%s' % str(pushinfo_dict))
    print '\n compare-code:%s\n'%code
    if reply_relation['MENUNAME']== '关键词,非菜单':
        SubData.Key_static(appid, code)
    elif reply_relation['MENUNAME']=='自动回复,非菜单':
        SubData.subdef_static(appid,code)
    else:
        SubData.Menu_static(appid, code)
    mutex.release()
    # print SubData.data
    return
def Menu_PushReply(getvalue_dict, pushper_dict, threadcount):
    appid = getvalue_dict['appid']
    authtype = getvalue_dict['authtype']
    reply_dict, get_Menu_url = get_Menulist.get_Menulist(getvalue_dict)

    # SubData.initData(appid)  ###初始化appid的统计,在Autoreply——Monior统一初始化
    try:
        if reply_dict == 'NULL':
            print '该appid无自定义菜单!'
            writelog.errorlog(get_Menu_url, '查看该appid是否有自定义菜单',
                              '该appid无自定义菜单!')
            static_result = SubData.data
            # print static_result
        elif reply_dict == 'FAIL':
            send_failEmail('获取自定义菜单失败,请检查接口参数或接口请求是否正常:\n%s' % get_Menu_url)
            writelog.errorlog(get_Menu_url, '获取该appid的自定义菜单',
                              '获取自定义菜单失败,请检查接口参数或接口请求是否正常!')
            static_result = SubData.Menu_static(appid, '500')
            print static_result
        else:
            threads = []
            for keyone in reply_dict.keys():
                tmp_reply_relation = reply_dict[keyone]
                tmp_reply_relation['openid'] = getvalue_dict['openid']

                MENUNAME = tmp_reply_relation['MENUNAME']
                getvalue_dict['type'] = 2
                getvalue_dict['content'] = MENUNAME
                service_result, service_url = get_service.get_service(
                    getvalue_dict)

                if service_result == '进入客服':
                    close_result, close_url = get_service.exitservice(
                        getvalue_dict)
                    print '\n%s\n该关键词触发了客服状态' % service_url
                    writelog.errorlog(appid, tmp_reply_relation['MENUNAME'],
                                      '此为人工客服独立功能,暂不校验')
                    while close_result == '进入客服':
                        close_result, close_url = get_service.exitservice(
                            getvalue_dict)
                        break
                    if close_result == '请求失败':
                        close_result, close_url = get_service.exitservice(
                            getvalue_dict)
                        MENUNAME = tmp_reply_relation['MENUNAME']
                        inputword = '%s,\t菜单名称:%s' % (str(keyone),
                                                      str(MENUNAME))
                        print '\n该菜单判断客服状态失败,判断是否进入客服状态:%s\n判断是否退出成功:%s' % (
                            close_url, close_result)
                        send_emails.send_failEmail('该菜单退出客服状态失败:\n%s' %
                                                   close_url)
                        writelog.errorlog(
                            str(service_url),
                            '菜单名称:%s--该菜单退出客服状态失败,请检查该接口请求是否正常\n%s' %
                            str(inputword),
                            str(tmp_reply_relation['reply_content']))
                        SubData.Menu_static(appid, '500')
                    else:
                        SubData.Menu_static(appid, '200')
                    reply_dict.pop(keyone)

                elif service_result == '请求失败':
                    MENUNAME = tmp_reply_relation['MENUNAME']
                    # print "key:%s" % str(key)
                    inputword = '%s,\t菜单名称:%s' % (str(keyone), str(MENUNAME))
                    print '\n%s\n该菜单判断客服状态失败' % (service_url)
                    send_emails.send_failEmail('该菜单判断是否进入客服状态:%s\n' %
                                               service_url)
                    writelog.errorlog(
                        str(service_url),
                        '菜单名称:%s--该菜单判断是否进入客服状态失败,请检查该接口请求是否正常' %
                        str(inputword),
                        str(tmp_reply_relation['reply_content']))
                    SubData.Menu_static(appid, '500')
                    reply_dict.pop(keyone)
                else:
                    if tmp_reply_relation['Event'] == 'CLICK':
                        if tmp_reply_relation.has_key(
                                'replyword'
                        ) and tmp_reply_relation['replyword'] == 'NULL':
                            get_replyword_url = tmp_reply_relation[
                                'get_replyword_url']
                            menuname = tmp_reply_relation['MENUNAME']
                            SubData.Menu_static(appid, '200')
                            writelog.errorlog(
                                get_replyword_url, '查看reply_id对应的回复内容',
                                '"%s"菜单的reply_id无对应回复信息' % menuname)
                            print '\n点击某菜单,该菜单的reply_id无对应回复信息,菜单名称:%s\n%s' % (
                                menuname, get_replyword_url)
                            reply_dict.pop(keyone)
                            continue
                            # send_failEmail('"%s"菜单的reply_id无对应回复信息%s' % (menuname,get_replyword_url))   ##暂时不发送邮件
                        elif tmp_reply_relation.has_key(
                                'replyword'
                        ) and tmp_reply_relation['replyword'] == 'FAIL':
                            SubData.Menu_static(appid, '500')
                            get_replyword_url = tmp_reply_relation[
                                'get_replyword_url']
                            writelog.errorlog(get_replyword_url,
                                              '查看reply_id对应的回复内容',
                                              '根据reply_id获取菜单自动回复内容的接口请求失败')
                            send_failEmail('根据reply_id获取菜单自动回复内容的接口请求失败%s' %
                                           get_replyword_url)
                            reply_dict.pop(keyone)
                            continue

                        else:
                            pass
                    else:
                        pass
                    reply_relation = reply_dict[keyone]
                    reply_relation['openid'] = getvalue_dict['openid']
                    to_xml = MesType.runevent_reply(reply_relation)
                    MENUNAME = reply_relation['MENUNAME']
                    inputword = '%s,\t菜单名称:%s' % (str(keyone), str(MENUNAME))

                    if reply_relation.has_key(
                            'replycontent_type'
                    ) and reply_relation['reply_content_type'] in [
                            '2', '3', '4'
                    ]:
                        material_result, material_url = get_material.get_material(
                            getvalue_dict, reply_relation['reply_content'])
                        if material_result == 'NULL':
                            SubData.Menu_static(appid, '200')
                            print '该material_id获取不到对应的素材:%s' % str(
                                material_url)
                            # sendEmail(request_url, request_xml, result_decrypt, str(inputword), str(reply_relation['reply_content']), '该material_id获取不到对应的素材!\n%s' %str( material_url))
                            writelog.errorlog(
                                str(material_url),
                                '菜单名称:%s--该material_id获取不到对应的素材' %
                                str(inputword),
                                str(reply_relation['reply_content']))
                            reply_dict.pop(keyone)
                            continue
                        elif material_result == 'FAIL':
                            SubData.Menu_static(appid, '500')
                            print '该material_id获取素材失败,请检查该接口请求是否正常:%s' % str(
                                material_url)
                            send_emails.send_failEmail(
                                '获取素材失败,请检查该接口请求是否正常%s\n' % str(material_url))
                            writelog.errorlog(
                                str(material_url),
                                '菜单名称:%s--获取素材失败,请检查该接口请求是否正常' %
                                str(inputword),
                                str(reply_relation['reply_content']))
                            reply_dict.pop(keyone)
                            continue
                        else:
                            pass
                    pushper_dict['key'] = keyone
                    if authtype == '3':
                        pushper_dict['token'] = 'irPNHoJN'
                        pushper_dict['General'] = {}
                    elif authtype == '1':
                        pushper_dict['token'] = getvalue_dict['authtoken']
                        General = {}
                        General['uniqueid'] = getvalue_dict['uniqueid']
                        General['appid'] = getvalue_dict['appid']
                        pushper_dict['General'] = General
                    # Pushdata.pushdata(pushper_dict, getvalue_dict, key,reply_relation, to_xml)
                    obj = Pushdata.pushdata
                    t = threading.Thread(target=obj,
                                         args=(pushper_dict, getvalue_dict,
                                               keyone, reply_relation, to_xml))
                    threads.append(t)

            for t in threads:
                t.setDaemon(True)
                t.start()
                while True:
                    if (len(threading.enumerate()) < threadcount):
                        break
                # print 'threading.activeCount:', threading.activeCount()

            for t in threads:
                t.join()
                # time.sleep(0.05)

            static_result = SubData.data
            # print static_result
        return static_result

    except Exception, e:
        print Exception, ":", e
        static_result = SubData.data
        send_emails.send_failEmail('\n%s :%s' % (str(Exception), str(e)))
        return static_result
def Auto_Monior(getvalue_dict, pushper_dict, threadcount):
    try:
        app_openid_data = get_authorinfo.get_appidinfo(getvalue_dict)

        if app_openid_data == 'NULL':
            print '无监测ID'
        else:
            start = time.time()

            for i in range(0, len(app_openid_data)):
                authtype = app_openid_data[i]['authtype']
                # print authtype
                getvalue_dict['appid'] = app_openid_data[i]['appid']
                getvalue_dict['openid'] = app_openid_data[i]['openid']
                getvalue_dict['authtype'] = authtype
                appid = app_openid_data[i]['appid']
                SubData.initData(appid)
                # print getvalue_dict
                if authtype == '3':
                    getvalue_dict['uniqueid'] = app_openid_data[i]['uniqueid']
                    pushper_dict[
                        'pushhttp'] = 'http://api.biz.social-touch.com/app-base/wechat/monitor/appid/%s?' % getvalue_dict[
                            'appid']
                elif authtype == '1':
                    getvalue_dict['uniqueid'] = app_openid_data[i]['uniqueid']
                    getvalue_dict['authtoken'] = app_openid_data[i][
                        'authtoken']
                    pushper_dict[
                        'pushhttp'] = 'http://api.biz.social-touch.com/app-base/wechat/monitor/?'

                # # list = ['1', '3']
                list = ['1']
                for i in range(0, len(list)):  ###列表中1代表自动回复,3代表再次关注自动回复
                    DefaultAutoReply.default_PushReply(getvalue_dict,
                                                       pushper_dict, list[i])
                result = Auto_PushReply(getvalue_dict, pushper_dict,
                                        threadcount)  ##关键词自定回复校验入口
                result = Menu_PushReply(getvalue_dict, pushper_dict,
                                        threadcount)  ##菜单自动回复校验入口

            total_keypass, total_keyerr, total_keyfail, total_menupass, total_menuerr, total_menufailr, total_subdefpass, total_subdeferr, total_subdeffailr = SubData.Total_static(
                result)

            writelog.static_log('总体', total_keypass, total_keyerr,
                                total_keyfail, total_menupass, total_menufailr,
                                total_menuerr)
            print 'total--关键词通过:%s,未通过:%s,失败:%s 菜单通过:%s,未通过:%s,失败:%s 自动回复通过:%s,未通过:%s,失败:%s' % (
                total_keypass, total_keyerr, total_keyfail, total_menupass,
                total_menuerr, total_menufailr, total_subdefpass,
                total_subdeferr, total_subdeffailr)

            if result != {} and result != None:
                for key in result.keys():
                    tmp = result[key]
                    key_rightcount = tmp['Key_pass']
                    key_errcount = tmp['Key_err']
                    key_failcount = tmp['Key_fail']
                    menu_rightcount = tmp['Menu_pass']
                    menu_errcount = tmp['Menu_err']
                    menu_failcount = tmp['Menu_fail']
                    writelog.static_log(key, key_rightcount, key_errcount,
                                        key_failcount, menu_rightcount,
                                        menu_errcount, menu_failcount)
            else:
                print '全部结果为空'

            end = time.time()
            print end - start
            # send_emails.send_staticEmail()

    except Exception, e:
        print Exception, ":", e
        send_emails.send_failEmail('%s :%s' % (Exception, e))
Beispiel #8
0
def pushdata(token, http, Third_appid, encodingAESKey, value_dict):
    authtype = value_dict['authtype']
    General = value_dict['General']
    Unencrypt_xml = etree.tostring(MesType.text_event(value_dict),
                                   encoding="UTF-8")
    timestamp = etree.fromstring(Unencrypt_xml).find('CreateTime').text
    openid = etree.fromstring(Unencrypt_xml).find('FromUserName').text
    # print token
    if authtype == '1':
        msg_encrypt = Unencrypt_xml

    elif authtype == '3':
        msg_encrypt = MesCrypt.encrypt(encodingAESKey, Third_appid,
                                       Unencrypt_xml)  ######XML数据加密
    else:
        send_emails.send_failEmail('该种授权类型不属于已知类型%s,请联系相关人员进行添加' %
                                   str(authtype))
        return {
            'authtype': authtype,
            'request_url': http,
            'request_xml': Unencrypt_xml,
            'result_decrypt': '该种授权类型不属于已知类型%s,请联系相关人员进行添加' % str(authtype)
        }
    nonce = str(random.randint(1000000000, 9999999999))
    encrypt_type = 'aes'
    signstr = ''.join(sorted([token, timestamp, nonce]))  ####按照升序排列,拼成字符串
    signature = hashlib.sha1(signstr).hexdigest()
    Msg_signstr = ''.join(sorted([token, timestamp, nonce, msg_encrypt]))
    Msg_Signature = hashlib.sha1(Msg_signstr).hexdigest()
    # print 'signature:%s  &  Msg_Signature:%s'%(signature, Msg_Signature)
    data = collections.OrderedDict()
    ToUserName = etree.fromstring(Unencrypt_xml).find('ToUserName').text
    if authtype == '3':
        data['ToUserName'] = '******' % ToUserName
        data['Encrypt'] = '<![CDATA[%s]]>' % msg_encrypt
        data['from'] = '<![CDATA[QA-check]]>'
        ele = etree.Element('xml')
        for ke, val in data.items():
            child = etree.Element(ke)
            child.text = str(val)
            ele.append(child)
        encrypt_xml = unescape(etree.tostring(ele))
        url = '%ssignature=%s&timestamp=%s&nonce=%s&openid=%s&encrypt_type=%s&msg_signature=%s' % (
            http, signature, timestamp, nonce, openid, encrypt_type,
            Msg_Signature)
    elif authtype == '1':
        encrypt_xml = Unencrypt_xml
        appid = General['appid']
        uniqueid = General['uniqueid']
        url = '%ssignature=%s&timestamp=%s&nonce=%s&openid=%s&uniqueid=%s&appid=%s' % (
            http, signature, timestamp, nonce, openid, uniqueid, appid)

    # print url
    # print encrypt_xml

    try:

        headers = {'Content-Type': 'text/xml'}
        starttime = time.time()
        req = requests.post(url=url,
                            data=encrypt_xml,
                            headers=headers,
                            timeout=10)
        # print req.url
        # print encrypt_xml
        result = req.text
        nowtime = time.time() - starttime
        print '\n****Request_URL****: \n%s\n****Unencrypt_XML****: \n%s\n****Request_EncryptXML****: \n%s' % (
            url, Unencrypt_xml, encrypt_xml)
        if req.status_code == 200:
            if result:
                if authtype == '3':
                    MesCrypt.decrypt(encodingAESKey, Third_appid, result)
                elif authtype == '1':
                    MesCrypt.nodecrypt(result)
                else:
                    result_statu = 'FAIL'
                    result_decrypt = result
            else:
                print '\nSTATUS=200,请求成功,无返回结果!'
                return {
                    'NULL': 'NULL',
                    'request_url': req.url,
                    'request_xml': encrypt_xml,
                    'result_decrypt': 'STATUS=200,请求成功,无返回结果!'
                }
        print '\n*Request time: %s ms' % int(nowtime * 1000)
        print '*Status_code: %s\n' % req.status_code
    except Exception, e:
        url = '%ssignature=%s&timestamp=%s&nonce=%s&openid=%s&encrypt_type=%s&msg_signature=%s' % (
            http, signature, timestamp, nonce, openid, encrypt_type,
            Msg_Signature)
        print '数据推送失败%s\n%s' % (url, str(e))
        return {
            'FAIL': 'FAIL',
            'request_url': url,
            'request_xml': encrypt_xml,
            'result_decrypt': str(e)
        }
Beispiel #9
0
def Auto_PushReply(getvalue_dict,pushper_dict,threadcount):
    appid = getvalue_dict['appid']
    authtype = getvalue_dict['authtype']

    # SubData.initData(appid)    ###初始化appid的统计,在Autoreply——Monior统一初始化
    try:
        reply_dict, get_keywords_url = get_keywords.get_keywords(getvalue_dict)

        if reply_dict=='NULL':
            print 'totalCount=0,无关键词配置!'
            writelog.errorlog(get_keywords_url,'查看该appid是否有关键词配置','totalCount=0,无关键词配置!')
            static_result = SubData.data
        elif reply_dict=='FAIL':
            send_failEmail('获取关键词失败,请检查接口参数或接口请求是否正常:\n%s'%get_keywords_url)
            writelog.errorlog(get_keywords_url,'获取该appid的关键词', '获取关键词失败,请检查接口参数或接口请求是否正常!')
            static_result=SubData.Key_static(appid, '500')

        else:
            threads=[]
            for key in reply_dict.keys():
                reply_relation = reply_dict[key]
                openid = getvalue_dict['openid']
                to_xml = MesType.runtext_reply(key, openid)
                MENUNAME = reply_relation['MENUNAME']
                inputword = '%s,\t菜单名称:%s' % (str(key),str(MENUNAME))
                getvalue_dict['type'] = 1
                getvalue_dict['content'] = key
                service_result, service_url = get_service.get_service(getvalue_dict)
                # print service_result
                if service_result == '进入客服':
                    close_result, close_url = get_service.exitservice(getvalue_dict)
                    print '\n%s\n该关键词触发了客服状态'%service_url
                    writelog.errorlog(appid, reply_relation['MENUNAME'], '此为人工客服独立功能,暂不校验')
                    while close_result == '进入客服':
                        close_result, close_url = get_service.exitservice(getvalue_dict)
                        break
                    if close_result == '请求失败':
                        close_result, close_url = get_service.exitservice(getvalue_dict)
                        MENUNAME = reply_relation['MENUNAME']
                        # print "key:%s" % str(key)
                        inputword = '%s,\t菜单名称:%s' % (str(key), str(MENUNAME))
                        print '\n该关键词判断客服状态失败,判断是否进入客服状态:%s\n判断是否退出成功:%s' % (close_url, close_result)
                        send_emails.send_failEmail('该关键词退出客服状态失败:\n%s' % close_url)
                        writelog.errorlog(str(service_url), '关键词名称:%s--该菜单退出客服状态失败,请检查该接口请求是否正常\n' % str(inputword),
                                          str(reply_relation['reply_content']))
                        SubData.Menu_static(appid, '500')
                    else:
                        SubData.Key_static(appid, '200')

                elif service_result == '请求失败':
                    MENUNAME = reply_relation['MENUNAME']
                    # print "key:%s" % str(key)
                    inputword = '%s,\t菜单名称:%s' % (str(key), str(MENUNAME))
                    print '\n%s\n该关键词判断客服状态失败' % (service_url)
                    send_emails.send_failEmail('该关键词判断是否进入客服状态:%s\n' % service_url)
                    writelog.errorlog(str(service_url), '关键词名称:%s--该菜单判断是否进入客服状态失败,请检查该接口请求是否正常' % str(inputword),
                                      str(reply_relation['reply_content']))
                    SubData.Key_static(appid, '500')

                else:

                    if reply_relation['reply_content_type'] in ['2', '3', '4']:
                        material_result, material_url = get_material.get_material(getvalue_dict,reply_relation['reply_content'])
                        if material_result == 'NULL':
                            SubData.Key_static(appid, '200')
                            print '该material_id获取不到对应的素材:%s' % str(material_url)

                            # sendEmail(request_url, request_xml, result_decrypt, str(inputword), str(reply_relation['reply_content']), '该material_id获取不到对应的素材!\n%s' %str( material_url))
                            writelog.errorlog(str(material_url), '关键词名称:%s--该material_id获取不到对应的素材' % str(inputword),str(reply_relation['reply_content']))
                            continue
                        elif material_result == 'FAIL':
                            SubData.Key_static(appid, '500')
                            print '该material_id获取素材失败,请检查该接口请求是否正常:%s' % str(material_url)
                            print reply_relation
                            send_emails.send_failEmail('获取素材失败,请检查该接口请求是否正常%s\n' % str(material_url))
                            writelog.errorlog(str(material_url), '菜单名称:%s--获取素材失败,请检查该接口请求是否正常' % str(inputword),str(reply_relation['reply_content']))
                            continue
                        else:
                            pass
                    else:
                        pass

                    # print '\n授权方式', authtype
                    if authtype == '3':
                        pushper_dict['General'] = {}
                        pushper_dict['token']='irPNHoJN'
                    elif authtype == '1':
                        pushper_dict['token'] = getvalue_dict['authtoken']
                        General = {}
                        General['uniqueid'] = getvalue_dict['uniqueid']
                        General['appid'] = getvalue_dict['appid']
                        pushper_dict['General'] = General
                    # Pushdata.pushdata(pushper_dict, getvalue_dict, key, reply_relation, to_xml)
                    obj = Pushdata.pushdata
                    t=threading.Thread(target=obj,args=(pushper_dict, getvalue_dict, key,reply_relation, to_xml))
                    threads.append(t)

            for t in threads:
                t.setDaemon(True)
                t.start()
                while True:
                    if(threading.activeCount() < threadcount):
                        break
                # print 'threading.activeCount:',threading.activeCount()

            for t in threads:
                t.join()
                # time.sleep(0.02)

            static_result=SubData.data
            # print static_result

        return static_result


    except Exception, e:
        print Exception, ":", e
        static_result = SubData.data
        send_emails.send_failEmail('\n%s :%s' % (str(Exception), str(e)))
        return static_result
def default_PushReply(getvalue_dict, pushper_dict, reply_type):

    appid = getvalue_dict['appid']
    authtype = getvalue_dict['authtype']
    reply_dict, get_defautoreply_url = get_autoreply.get_defaultreply(
        getvalue_dict, reply_type)
    reply_dict['MENUNAME'] = '自动回复,非菜单'
    if authtype == '3':
        pushper_dict['General'] = {}
        pushper_dict['token'] = 'irPNHoJN'
    elif authtype == '1':
        pushper_dict['token'] = getvalue_dict['authtoken']
        General = {}
        General['uniqueid'] = getvalue_dict['uniqueid']
        General['appid'] = getvalue_dict['appid']
        pushper_dict['General'] = General
    # try:
    if reply_dict['reply_content'] == 'NULL' or reply_dict['is_open'] == '0':
        print '该appid未设置或已关闭自动回复!'
        writelog.errorlog(get_defautoreply_url, '查看该appid是否设置自动回复',
                          '该appid未设置自动回复!')
        static_result = SubData.data
    elif reply_dict['reply_content'] == 'FAIL':
        send_failEmail('获取自动回复失败,请检查接口参数或接口请求是否正常:\n%s' % get_defautoreply_url)
        writelog.errorlog(get_defautoreply_url, '获取该appid的自动回复',
                          '获取自动回复失败,请检查接口参数或接口请求是否正常!')
        SubData.subdef_static(appid, '500')
    else:
        openid = getvalue_dict['openid']
        if reply_type == '1':
            to_xml = MesType.runtext_reply(str(int(cur_time)), openid)
            inputword = str(int(cur_time))
            getvalue_dict['content'] = inputword
            getvalue_dict['type'] = 1
            service_result, service_url = get_service.get_service(
                getvalue_dict)
            # print service_result
            if service_result == '进入客服':
                close_result, close_url = get_service.exitservice(
                    getvalue_dict)
                print '\n%s\n该词触发了客服状态' % service_url
                writelog.errorlog(appid, inputword, '此为人工客服独立功能,暂不校验')
                while close_result == '进入客服':
                    close_result, close_url = get_service.exitservice(
                        getvalue_dict)
                    break
                if close_result == '请求失败':
                    close_result, close_url = get_service.exitservice(
                        getvalue_dict)
                    SubData.subdef_static(appid, '500')
                    print '\n该词判断客服状态失败,判断是否进入客服状态:%s\n判断是否退出成功:%s' % (
                        close_url, close_result)
                    send_emails.send_failEmail('该词退出客服状态失败:\n%s' % close_url)
                    writelog.errorlog(
                        str(service_url),
                        '名称:%s--该词退出客服状态失败,请检查该接口请求是否正常\n' % str(inputword),
                        str(reply_dict['reply_content']))
                else:
                    SubData.subdef_static(appid, '200')
            elif service_result == '请求失败':
                print '\n%s\n该词判断客服状态失败' % (service_url)
                send_emails.send_failEmail('该词判断是否进入客服状态:%s\n' % service_url)
                writelog.errorlog(
                    str(service_url),
                    '名称:%s--该词判断是否进入客服状态失败,请检查该接口请求是否正常' % str(inputword),
                    str(reply_dict['reply_content']))
                SubData.subdef_static(appid, '500')
            else:
                if reply_dict['reply_content_type'] in ['2', '3', '4']:
                    material_result, material_url = get_material.get_material(
                        getvalue_dict, reply_dict['reply_content'])
                    if material_result == 'NULL':
                        print '该material_id获取不到对应的素材:%s' % str(material_url)
                        # sendEmail(request_url, request_xml, result_decrypt, str(inputword), str(reply_relation['reply_content']), '该material_id获取不到对应的素材!\n%s' %str( material_url))
                        writelog.errorlog(
                            str(material_url),
                            ':%s--该material_id获取不到对应的素材' % str(inputword),
                            str(reply_dict['reply_content']))
                        SubData.subdef_static(appid, '200')
                    elif material_result == 'FAIL':
                        SubData.subdef_static(appid, '500')
                        print '该material_id获取素材失败,请检查该接口请求是否正常:%s' % str(
                            material_url)
                        send_emails.send_failEmail('获取素材失败,请检查该接口请求是否正常%s\n' %
                                                   str(material_url))
                        writelog.errorlog(
                            str(material_url),
                            '菜单名称:%s--获取素材失败,请检查该接口请求是否正常' % str(inputword),
                            str(reply_dict['reply_content']))
                    else:
                        Pushdata.pushdata(pushper_dict, getvalue_dict,
                                          inputword, reply_dict, to_xml)
                elif reply_dict['reply_content_type'] == '1':
                    Pushdata.pushdata(pushper_dict, getvalue_dict, inputword,
                                      reply_dict, to_xml)
                else:
                    print '该种reply_content_type暂不支持'
        elif reply_type == '3':
            evendict = {}
            evendict['openid'] = openid
            evendict['Event'] = 'subscribe'
            to_xml = MesType.runevent_reply(evendict)
            inputword = 'subscribe'
            if reply_dict['reply_content_type'] in ['2', '3', '4']:
                material_result, material_url = get_material.get_material(
                    getvalue_dict, reply_dict['reply_content'])
                if material_result == 'NULL':
                    SubData.subdef_static(appid, '200')
                    print '该material_id获取不到对应的素材:%s' % str(material_url)
                    # sendEmail(request_url, request_xml, result_decrypt, str(inputword), str(reply_relation['reply_content']), '该material_id获取不到对应的素材!\n%s' %str( material_url))
                    writelog.errorlog(
                        str(material_url),
                        ':%s--该material_id获取不到对应的素材' % str(inputword),
                        str(reply_dict['reply_content']))
                elif material_result == 'FAIL':
                    print '该material_id获取素材失败,请检查该接口请求是否正常:%s' % str(
                        material_url)
                    SubData.subdef_static(appid, '500')
                    send_emails.send_failEmail('获取素材失败,请检查该接口请求是否正常%s\n' %
                                               str(material_url))
                    writelog.errorlog(
                        str(material_url),
                        '菜单名称:%s--获取素材失败,请检查该接口请求是否正常' % str(inputword),
                        str(reply_dict['reply_content']))
                else:
                    Pushdata.pushdata(pushper_dict, getvalue_dict, inputword,
                                      reply_dict, to_xml)
            elif reply_dict['reply_content_type'] == '1':
                Pushdata.pushdata(pushper_dict, getvalue_dict, inputword,
                                  reply_dict, to_xml)
            else:
                print '该种reply_content_type暂不支持'
        else:
            SubData.subdef_static(appid, '500')
            print '该种回复类型暂不支持!reply_type=%s' % reply_type
            return '该种回复类型暂不支持!reply_type=%s' % reply_type
            # print '\n授权方式', authtype
        static_result = SubData.data
    return static_result