コード例 #1
0
ファイル: wechatapp.py プロジェクト: xingkaixin/pinpin
def wechat_handler():
    try:
        token = current_app.config['WECHAT_TOEKN']
        signature = request.args.get('signature')
        timestamp = request.args.get('timestamp')
        nonce = request.args.get('nonce')
        check_signature(token, signature, timestamp, nonce)

        current_app.logger.info('wechat_handler begin')
        body = request.get_data()
        current_app.logger.info('wechat_handler body %s' % body)
        msg = parse_message(body)
        if msg.type == 'text':
            return reply_msg(msg)
        elif msg.type == 'event' and msg.event == 'click' and msg.key == 'V2003_SignIn':
            return sign_in(msg)
        elif msg.type == 'event' and msg.event in ['subscribe_scan', 'scan'] and msg.scene_id == '123':
            binding(msg)
            if msg.event == 'subscribe_scan':
                return welcome_article(msg)
        elif msg.type == 'event' and msg.event == 'unsubscribe':
            unsubscribe_unbinding(msg)
        elif msg.type == 'event' and msg.event == 'subscribe':
            return welcome_article(msg)
        reply = EmptyReply()
        return reply.render()
    except InvalidSignatureException:
        abort(404)
    except Exception as e:
        current_app.logger.exception('wechat_handler %s' % e)
        reply = EmptyReply()
        return reply.render()
コード例 #2
0
class Event(object):
    '''
    事件基类
    '''

    reply = None
    expected_type = None
    msg_reply = None

    id = 0
    type = 'unknown'  # 消息的类型
    source = None  # 消息的来源用户,即发送消息的用户
    target = None  # 消息的目标用户
    create_time = None  # 消息的发送时间,UNIX 时间戳
    time = None

    def __init__(self, msg):
        if not isinstance(msg, self.expected_type):
            raise TypeError("Expected " + str(self.expected_type))

        self.msg = msg
        self.id = self.msg.id
        self.type = self.msg.type
        self.source = self.msg.source
        self.target = self.msg.target
        self.create_time = self.msg.create_time
        self.time = self.msg.time

    def on_take(self):
        '''
        推送消息-主动调用该方法
        :return:
        '''
        print('TextMessageBase', self.id)
        print('TextMessageBase', self.type)
        print('TextMessageBase', self.source)
        print('TextMessageBase', self.target)
        print('TextMessageBase', self.create_time)
        print('TextMessageBase', self.time)

        context = self.get_reply_body()
        if not context:
            self.msg_reply = EmptyReply()
            print('EmptyReply', type(self.msg_reply))
            return

        context_send = {'message': self.msg, **context}

        self.msg_reply = self.reply(**context_send)

    def get_reply_body(self, context=None):
        '''
        微信公众号消息回复内容构建
        :param context:
        :return:
        '''
        return context

    def render(self):
        return self.msg_reply.render()
コード例 #3
0
ファイル: wechatapp.py プロジェクト: xingkaixin/pinpin
def reply_msg(msg):
    rs = get_match_bloginfo(msg.content)
    record_msg(msg, rs['is_match'])
    if rs['is_match']:
        data = [rs]
        client = get_wechat_client()
        client.message.send_articles(msg.source, data)
        reply = EmptyReply()
    else:
        rs = get_sougou_result(msg.content)
        if rs['is_match']:
            client = get_wechat_client()
            client.message.send_articles(msg.source, [rs])
            reply = EmptyReply()
        else:
            reply = TextReply(content=u'抱歉,关键词:{keyword} 还未收录。'.format(
                keyword=msg.content), message=msg)
    return reply.render()
コード例 #4
0
ファイル: test_replies.py プロジェクト: yupengyan/wechatpy
    def test_empty_reply(self):
        from wechatpy.replies import EmptyReply

        reply = EmptyReply()
        self.assertEqual('', reply.render())
コード例 #5
0
ファイル: test_replies.py プロジェクト: Brightcells/wechatpy
    def test_empty_reply(self):
        from wechatpy.replies import EmptyReply

        reply = EmptyReply()
        self.assertEqual('', reply.render())
コード例 #6
0
ファイル: api.py プロジェクト: richardweiu/OpenCLMS
def api(request):
    # 从 request 中提取基本信息 (signature, timestamp, nonce, xml)
    signature = request.GET.get('msg_signature')
    timestamp = request.GET.get('timestamp')
    nonce = request.GET.get('nonce')
    # 解析本次请求的 XML 数据
    crypto = WeChatCrypto(settings.TOKEN, settings.ENCODINGAESKEY, settings.CORPID)
    if request.method == 'GET':
        # 检验合法性
        echo_str = request.GET.get('echostr', '')
        try:
            echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str)
        except InvalidSignatureException:
            # 处理异常情况或忽略
            return HttpResponseBadRequest('Verify Failed')
        return HttpResponse(echo_str, content_type="text/plain")

    try:
        decrypted_xml = crypto.decrypt_message(
            request.body,
            signature,
            timestamp,
            nonce
        )
    except (InvalidCorpIdException, InvalidSignatureException):
        # 处理异常或忽略
        return HttpResponseBadRequest('Failed')
    msg = parse_message(decrypted_xml)
    response = EmptyReply()
    if msg.type == 'text':
        text = msg.content
        if text == 'info':
            userinfo = wechat_client.user.get(msg.source)
            response = TextReply(content=str(userinfo), message=msg)
        else:
            reply = Wechatkeyword.objects.extra(where=['%s SIMILAR TO keyword'], params=[text]).first()
            if reply:
                response = TextReply(content=u'%s' % reply.data, message=msg)
    elif msg.type == 'event':
        if msg.event == 'subscribe':  # 关注事件
            response = EmptyReply()

        elif msg.event == 'unsubscribe':
            logger.info('wechat user %s unsubscribe' % msg.source)
            user = User.objects.get(openid=msg.source)
            user.checkinaccountabnormal = True
            user.save()

        elif msg.event == 'location':
            nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            try:
                user = User.objects.get(openid=msg.source)
            except User.DoesNotExist:
                pass
            else:
                user.latitude = msg.latitude
                user.longitude = msg.longitude
                user.accuracy = msg.precision
                user.lastpositiontime = nowtime
                user.save()

        elif msg.event == 'click':
            if msg.key == '1200':
                response = TextReply(content=u'地址:%s\n学生默认帐号:学号/身份证号\n教师默认帐号:职工号/职工号' % settings.DOMAIN,
                                     message=msg)

    xml = response.render()
    encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp)
    return HttpResponse(encrypted_xml, content_type="application/xml")