Exemple #1
0
def do_reply(msg):
    if msg.content == '天气':
        # msg.content 就是发送过来消息的内容
        reply = create_reply('今天是晴天', msg)
    elif msg.content == '王者荣耀':
        reply = create_reply('万年青铜垃圾游戏,不玩了', msg)
    elif msg.content == '历史':
        result = hisutils.request1()
        reply = create_reply(result, msg)

    elif msg.content == '星座运势':
        result = hisutils.request2()

        res = result['name'] + ':' + '1.时间:' + result[
            'datetime'] + '2.幸运色:' + result['color'] + '3.注意事项:' + result[
                'summary']
        reply = create_reply(res, msg)
    elif msg.content == '倔强':
        reply = ArticlesReply(message=msg)
        reply.add_article({
            "title":
            "倔强",
            "description":
            "倔强",
            'image':
            '',
            "url":
            "https://mp.weixin.qq.com/s?__biz=MzU1OTc0NTQ1OQ==&tempkey=OTgwX1VsOXpaamFiaTJnRGtuMFZZRTVRNE5MQ0NMbTg1TmNrU2tRLWRvZWFxQ2ZGd0djSmdtazJoNC1NZXBMZW5Ob2ptOGNZb3d4VUdYNklFaWkwSHc5NWJoaEI2dl81SjZHZDhYdUwtbEVBRWZSN01acC05OVhST3hXem9wN1RFd0VCQWdxaUpjck12SGg3R0RzdWFYZC1ZeU1RYWZnOFEtcHlNRGpZN3d%2Bfg%3D%3D&chksm=7c13d1f94b6458ef3458ddd1e6bd5e31ae8bc410a21751e6ae5284cfbb6f9f0144d3613bac07#rd"
        })
    else:
        aip = apiutils.AiPlat('2109307989', '867FI1Wu8YsT3Gd8')
        data = aip.get_nlp_text_trans(msg.content, 0)
        reply = create_reply(data['data']['trans_text'], msg)
    return reply
Exemple #2
0
    def test_multi_article_reply(self):
        from wechatpy.replies import ArticlesReply

        article = {'title': 'test', 'url': 'http://www.qq.com'}

        r1 = ArticlesReply()
        r1.add_article(article)
        r2 = ArticlesReply()
        self.assertTrue(r1.render() != r2.render())
Exemple #3
0
    def test_multi_article_reply(self):
        from wechatpy.replies import ArticlesReply

        article = {"title": "test", "url": "http://www.qq.com"}

        r1 = ArticlesReply()
        r1.add_article(article)
        r2 = ArticlesReply()
        self.assertTrue(r1.render() != r2.render())
Exemple #4
0
    def test_multi_article_reply(self):
        from wechatpy.replies import ArticlesReply

        article = {'title': 'test', 'url': 'http://www.qq.com'}

        r1 = ArticlesReply()
        r1.add_article(article)
        r2 = ArticlesReply()
        self.assertTrue(r1.render() != r2.render())
Exemple #5
0
def handle_msg(request):
    if request.method == 'GET':
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        echo_str = request.GET.get('echostr')
        check_signature(TOKEN, signature, timestamp, nonce)
        return HttpResponse(echo_str)
    elif request.method == 'POST':
        body = request.body
        msg = parse_message(body)
        rep = TextReply()
        rep.source = msg.target
        rep.target = msg.source
        if msg.type == 'event':
            if msg.event == 'click':
                if msg.key == 'sports_advice':
                    rep.content = recommend_plan(msg.source)
                elif msg.key == 'view_info':
                    rep.content = get_info(msg.source)
                elif msg.key == 'add_bong':
                    rep.content = add_bong(msg.source)
                elif msg.key == 'add_test':
                    rep.content = add_test(msg.source)
                elif msg.key == 'add_test_new':
                    rep.content = add_test_new(msg.source)
                elif msg.key == 'show_today':
                    rep.content = get_datatoday(msg.source)
                elif msg.key == 'change_remind':
                    rep.content = set_remind(msg.source)
                elif msg.key == 'build_match':
                    article_rep = ArticlesReply()
                    article_rep.source = msg.target
                    article_rep.target = msg.source
                    article_rep.add_article({
                        'title': '创建比赛',
                        'description': '点此链接以创建比赛',
                        'image': serverIP+'static/img/run02.jpg',
                        'url': build_match(msg.source)
                    })
                    repxml = article_rep.render()
                    return HttpResponse(repxml)
            elif msg.event == 'subscribe':
                rep.content = create_newuser(msg.source)
            else:
                rep.content = '!!!'
        else:
            rep.content = '你好'
        repxml = rep.render()
        return HttpResponse(repxml)
Exemple #6
0
def test_handler(recv_msg, *args, **kwargs):
    reply = ArticlesReply()
    reply.source = recv_msg.to_user_name
    reply.target = recv_msg.from_user_name
    reply.add_article({
        'title': '测试图文消息',
        'description': '图文消息描述',
        'image': 'http://pic1.win4000.com/pic/b/6e/5aee949474.jpg',
        'url': 'http://www.baidu.com'
    })
    reply.add_article({
        'title': '测试图文消息',
        'description': '图文消息描述',
        'image': 'http://pic1.win4000.com/pic/b/6e/5aee949474.jpg',
        'url': 'http://www.baidu.com'
    })

    xml = reply.render()
    return HttpResponse(xml)
Exemple #7
0
def send_message(request):
    if request.method == 'GET':  # 验证URL
        signature = request.GET.get('signature', '')
        timestamp = request.GET.get('timestamp', '')
        nonce = request.GET.get('nonce', '')
        echo_str = request.GET.get('echostr', '')
        try:
            check_signature(AUTH_TOKEN, signature, timestamp, nonce)
        except InvalidSignatureException:
            echo_str = 'error'
        response = HttpResponse(echo_str, content_type='text/plain')
        return response
    elif request.method == 'POST':  # 接收来微信服务器信息
        msg = parse_message(request.body)
        if msg.type == 'text':
            reply = create_reply("<a href='https://articuly.com'>清心涟漪博客</a>",
                                 msg)
        elif msg.type == 'event':
            reply = ArticlesReply(message=msg)
            reply.add_article({
                'title': '清心涟漪博客',
                'description': '因缘相见,整合图谱,心理占星,Python全栈',
                'image':
                'https://articuly.com/wp-content/uploads/2014/07/articuly.jpg',
                'url': 'https://articuly.com'
            })
        elif msg.type == 'image':
            reply = create_reply('你刚才发给我的是一张图片', msg)
        elif msg.type == 'voice':
            reply = create_reply('你刚才发给我的是语音', msg)
        else:
            reply = create_reply('这是其它类型消息', msg)
        response = HttpResponse(reply.render(), content_type='application/xml')
        return response
    else:
        print('-' * 50)
Exemple #8
0
def getWeatherMsg(msg):
    reply = ArticlesReply(message=msg)
    result = getcityweather()
    temperature = result['result']['today']['temperature']
    weather = result['result']['today']['weather']
    wind = result['result']['today']['wind']
    reply.add_article({
        'title': temperature,
    })
    reply.add_article({
        'title': weather,
    })
    reply.add_article({
        'title': wind,
    })
    return reply
Exemple #9
0
def subscribe(msg):
    reply = ArticlesReply(message=msg)
    reply.add_article({
        'title': '米客鹿 - 欢迎您',
        'description': '米客鹿 - 欢迎您',
        'image':
        'https://mmbiz.qlogo.cn/mmbiz_png/yPLjxp6uDp30bajsBE2nR9nV5WUaI80NJ6s315CHBP0s3KvruP5pT2TesSNNTpKUiawRqdjNJpvicW1mJtS3RTnw/0?wx_fmt=png',
        'url': 'http://wxclientdev.fogcloud.io/welcome/'
    })
    reply.add_article({
        'title': '配置玩具wifi',
        'description': '配置玩具wifi',
        'image':
        'https://mmbiz.qlogo.cn/mmbiz_png/yPLjxp6uDp30bajsBE2nR9nV5WUaI80NMucDbFsLF0FceUIRISpWrsnibRtfPEyEdZdEoibEP5J1gVwTQbk4vI5A/0?wx_fmt=png',
        'url': 'http://wxclientdev.fogcloud.io/wifi/'
    })
    reply.add_article({
        'title': '如何使用',
        'description': '如何使用',
        'image':
        'https://mmbiz.qlogo.cn/mmbiz_png/yPLjxp6uDp30bajsBE2nR9nV5WUaI80NBLkJgCOa3lq4udulLw1F8fQhKQic2PvIlMtqQ8E8hRiaDw6MAvvrOJDw/0?wx_fmt=png',
        'url': 'http://wxclientdev.fogcloud.io/instructions/'
    })
    return reply
Exemple #10
0
def send_article(toUser, fromUser):
    reply = ArticlesReply()
    reply.source = fromUser
    reply.target = toUser
    reply.add_article({"title":"圣光会制裁你!", "description":"The Light Shall Bring Victory!", "image":LIGHT, "url":"http://baike.baidu.com/link?url=QBxKSNA79HbeeaSwsbkcPHdhhVI5ZM9HePZrUpQCwtwKx9xShsZ1vOCd35UuNYP0SxaedrA2UIaPLMvFVW5wD_"})
    return HttpResponse(reply.render())
Exemple #11
0
def wechat(request):
    """
    此地址为响应微信发送的Token验证,验证服务器配置是否正确
    :param request:
    :return:
    """
    signature = request.GET.get('signature', 'c58469c4151fac046efe180b277c51b1e5b563d3')
    timestamp = request.GET.get('timestamp', '1451138472')
    nonce = request.GET.get('nonce', '1432579014')
    echo_str = request.GET.get('echostr', '2691756735856574460')
    encrypt_type = request.args.get('encrypt_type', '')
    msg_signature = request.args.get('msg_signature', '')
    print('signature:', signature)
    print('timestamp: ', timestamp)
    print('nonce:', nonce)
    print('echo_str:', echo_str)
    print('encrypt_type:', encrypt_type)
    print('msg_signature:', msg_signature)
    try:
        check_signature(settings.WECHAT_TOKEN, signature, timestamp, nonce)
    except InvalidSignatureException:
        return HttpResponseForbidden()
    if request.method == 'GET':
        return echo_str
    else:
        print('Raw message: \n%s' % request.data)
        crypto = WeChatCrypto(settings.WECHAT_TOKEN, settings.EncodingAESKey, settings.WECHAT_APPID)
        try:
            msg = crypto.decrypt_message(
                request.data,
                msg_signature,
                timestamp,
                nonce
            )
            print('Descypted message: \n%s' % msg)
        except (InvalidSignatureException, InvalidAppIdException):
            return HttpResponseForbidden()
        msg = parse_message(msg)
        if msg.type == 'text':
            reply = create_reply(msg.content, msg)
        elif msg.type == 'image':
            reply = ArticlesReply(message=msg)
            # simply use dict as article
            reply.add_article({
                'title': 'test',
                'description': 'test',
                'image': 'image url',
                'url': 'url'
            })
            # or you can use ObjectDict
            article = ObjectDict()
            article.title = 'test'
            article.description = 'test'
            article.image = 'image url'
            article.url = 'url'
            reply.add_article(article)
            # reply = create_reply([article], msg)
        else:
            reply = create_reply('Sorry, can not handle this for now', msg)
        msg= crypto.encrypt_message(
            reply.render(),
            nonce,
            timestamp)
        print(msg)
        return HttpResponse(msg)
Exemple #12
0
        def get_reply_msg():
            # 被动回复 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html
            if isinstance(msg, SubscribeScanEvent) or isinstance(
                    msg, ScanEvent):
                # 未关注用户扫描带参数二维码事件 - 订阅关注
                # 已关注用户扫描带参数二维码事件
                platform_id = int(msg.scene_id)
                platform = Platform.get(platform_id=platform_id)
                assert platform
                user = User.get(openid=from_user_openid)
                if not user:
                    # 创建 user
                    user = User.create(openid=from_user_openid,
                                       bind_platform_id=platform.platform_id)
                else:
                    # user 表记录, 存在
                    if user.bind_platform_id != platform.platform_id:
                        log.w(
                            f'platform_id change: {user.bind_platform_id} -> {platform.platform_id}, openid: {user.openid}'
                        )
                        user.update(bind_platform_id=platform.platform_id)
                account = Account.get(user_id=user.user_id,
                                      platform_id=user.bind_platform_id)
                if not account:
                    # 创建 account
                    username = MyRandom.random_digit(length=8)
                    expired_at = Datetime.localtime() + datetime.timedelta(
                        days=1)  # 新账户一天内免费
                    account = Account.create(
                        user_id=user.user_id,
                        platform_id=user.bind_platform_id,
                        username=username,
                        password=username,
                        radius_password=username,
                        role=Account.Role.PAY_USER.value,
                        expired_at=expired_at,
                    )
                sentry_sdk.capture_message(
                    f'有用户扫描带参数二维码, platform_id: {platform.platform_id}, openid: {from_user_openid}'
                )
                # 判断是否允许房东注册
                if platform.platform_id == settings.ADMIN_PLATFORM_ID:
                    redis = get_redis()
                    if redis.get('enable_platform_register'):
                        # 新创建平台
                        new_platform = create_new_platform(
                            user_id=user.user_id)
                        platform_url = f'{settings.API_SERVER_URL}/platform/{new_platform.platform_id}'
                        sentry_sdk.capture_message(
                            f'房东平台已建立, platform_url: {platform_url}')
                        redis.delete('enable_platform_register')
                # 应答
                return TextReply(
                    source=appid,
                    target=from_user_openid,
                    content=
                    f'账号: {account.username}\n密码: {account.password}\n状态: {account.status}'
                )

            if isinstance(msg, ClickEvent):
                # 点击按钮 - 账号中心
                if msg.key == WeClient.ACCOUNT_VIEW_BTN_EVENT:
                    user = User.get(openid=from_user_openid)
                    if not user or user.bind_platform_id is None:
                        # 用户未经扫码, 进入公众号
                        return TextReply(source=appid,
                                         target=from_user_openid,
                                         content=f'请先扫描房东的WIFI二维码')
                    else:
                        platform = Platform.get(
                            platform_id=user.bind_platform_id)
                        if platform.is_platform_owner(
                                user_id=user.user_id
                        ) and not settings.is_admin(openid=from_user_openid):
                            # 房东不能打开充值页面, 但 admin 可以
                            return TextReply(source=appid,
                                             target=from_user_openid,
                                             content=f'房东不允许打开充值页面')
                        r = ArticlesReply(source=appid,
                                          target=from_user_openid)
                        r.add_article({
                            'title': f'点击进入',
                            'description': '查询WIFI密码 / WIFI续费',
                            'image':
                            'http://zlxpic.lynatgz.cn/zhuzaiyuan_mini.jpg',
                            'url': WeClient.ACCOUNT_VIEW_URI,
                        })
                        return r
                elif msg.key == WeClient.CUSTOMER_SERVICE_BTN_EVENT:
                    return TextReply(source=appid,
                                     target=from_user_openid,
                                     content=settings.MP_DEFAULT_REPLY)

            elif isinstance(msg, SubscribeEvent):  # 关注公众号事件
                pass

            elif isinstance(msg, TextMessage):  # 文本消息
                if msg.content in ['help', '帮助', '命令']:
                    command = [
                        'id',
                        '搜索 $name',
                        'free',
                        '放通mac',
                        '房东注册',
                    ]
                    message = '命令:\n  ' + '\n  '.join(command)
                    return TextReply(source=appid,
                                     target=from_user_openid,
                                     content=message)

                elif msg.content == 'id':
                    # 查看用户ID
                    user = User.get(openid=from_user_openid)
                    messages = [
                        f'你的信息:',
                        f'openid: {user.openid}',
                        f'user_id: {user.user_id}',
                    ]
                    return TextReply(source=appid,
                                     target=from_user_openid,
                                     content='\n'.join(messages))

                # 以下命令需要 admin 权限
                elif msg.content.startswith('搜索') and settings.is_admin(
                        openid=from_user_openid):
                    # 搜索用户信息
                    name = msg.content.split('搜索')[1].strip()
                    return TextReply(
                        source=appid,
                        target=from_user_openid,
                        content=
                        f'{settings.API_SERVER_URL}/search/user?name={name}')

                elif msg.content.startswith('放通mac') and settings.is_admin(
                        openid=from_user_openid):
                    redis = get_redis()
                    ex = 60 * 5
                    redis.set('enable_mac_authentication',
                              str(datetime.datetime.now()),
                              ex=ex)
                    return TextReply(source=appid,
                                     target=from_user_openid,
                                     content=f'有效时间: {ex}秒')

                elif msg.content.startswith('房东注册') and settings.is_admin(
                        openid=from_user_openid):
                    redis = get_redis()
                    ex = 60 * 5
                    redis.set('enable_platform_register',
                              str(datetime.datetime.now()),
                              ex=ex)
                    return TextReply(source=appid,
                                     target=from_user_openid,
                                     content=f'有效时间: {ex}秒')

                elif msg.content.startswith('free') and settings.is_admin(
                        openid=from_user_openid):
                    expired_at = Datetime.localtime() + datetime.timedelta(
                        minutes=30)
                    account = Account.get(user_id=0, platform_id=0)
                    if not account:
                        account = Account.create(
                            user_id=0,
                            platform_id=0,
                            username='******',
                            password='******',
                            radius_password='******',
                            role=Account.Role.FREE_USER.value,
                            expired_at=expired_at,
                        )
                    else:
                        account.update(expired_at=expired_at)
                    content = f'用户名: {account.username}, 密码: {account.password}, 失效时间: {Datetime.to_str(expired_at, fmt="%Y-%m-%d %H:%M:%S")}'
                    return TextReply(source=appid,
                                     target=from_user_openid,
                                     content=content)

                else:
                    return TextReply(source=appid,
                                     target=from_user_openid,
                                     content=settings.MP_DEFAULT_REPLY)
            return None
Exemple #13
0
def home(request):
    if request.method == 'GET':
        signature = request.GET.get('signature', '')
        timestamp = request.GET.get('timestamp', '')
        nonce = request.GET.get('nonce', '')
        echo_str = request.GET.get('echostr', '')
        try:
            check_signature(WECHAT_TOKEN, signature, timestamp, nonce)
        except InvalidSignatureException:
            echo_str = 'error'
        response = HttpResponse(echo_str, content_type="text/plain")
        return response
    elif request.method == 'POST':
        msg = parse_message(request.body)
        if msg.type == 'text':
            muser = MagicUser.objects.get_or_create(openid=msg.source)
            print(muser[0].snumber)
            if '成绩' in msg.content and '更新' not in msg.content:
                reply = create_reply(
                    str(muser[0].uuid) + str(msg.content), msg)
                print(str(muser[0].uuid))
                if None == muser[0].snumber:
                    url = BASEURL + reverse('index') + '?uuid=' + str(
                        muser[0].uuid) + "&type=chengji&create=" + str(
                            muser[1])
                else:
                    url = BASEURL + reverse('chengji') + '?uuid=' + str(
                        muser[0].uuid)
                reply = ArticlesReply(message=msg)
                reply.add_article({
                    'title': '成绩',
                    'description': '成绩',
                    'image': BASEURL + '/static/mags/imgs/weixinmsggrade.png',
                    'url': url
                })
            elif '课表' in msg.content and '更新' not in msg.content:
                reply = create_reply(
                    str(muser[0].uuid) + str(msg.content), msg)
                if None == muser[0].snumber:
                    url = BASEURL + reverse('index') + '?uuid=' + str(
                        muser[0].uuid) + "&type=kebiao&create=" + str(muser[1])
                else:
                    url = BASEURL + reverse('kebiao') + '?uuid=' + str(
                        muser[0].uuid)
                reply = ArticlesReply(message=msg)
                reply.add_article({
                    'title': '课表',
                    'description': '课表',
                    'image':
                    'http://pic1.sc.chinaz.com/files/pic/pic9/201803/zzpic10731.jpg',
                    'url': url
                })

            elif '更新成绩' in msg.content or '更新课表' in msg.content:
                if None == muser[0].snumber:
                    url = BASEURL + reverse('index') + '?uuid=' + str(
                        muser[0].uuid) + "&type=chengji&create=" + str(
                            muser[1])
                else:
                    url = BASEURL + reverse('gengxin') + '?uuid=' + str(
                        muser[0].uuid)
                reply = ArticlesReply(message=msg)
                reply.add_article({
                    'title': '更新成绩和课表',
                    'description': '更新成绩和课表点击前往更新',
                    'image':
                    'http://pic1.sc.chinaz.com/files/pic/pic9/201803/zzpic10731.jpg',
                    'url': url
                })
            else:
                flag = False
                buildings = [
                    '致高楼A幢', '管理楼', '致用楼', '科学会堂', '致高楼B幢', '水利馆', '闻天馆',
                    '博学楼', '工程馆', '北教楼', '致远楼', '江宁体育场', '研究生综合楼', '水文楼',
                    '励学楼', '勤学楼'
                ]
                for i in buildings:
                    if msg.content in i:
                        flag = True
                        break

                if flag:
                    d = datetime.datetime.now()
                    index = d.weekday()

                    #false空闲 true有课
                    #西康路校区 江宁校区 江宁西校区 常州校区

                    todayres = test_curl_fetch(
                        'http://map.hhu.edu.cn/mapi/api/v2.0/classRoom.json?day='
                        + str(index))
                    tomorrowres = test_curl_fetch(
                        'http://map.hhu.edu.cn/mapi/api/v2.0/classRoom.json?day='
                        + str((index + 1) % 7))

                    todayjisoshi = json.loads(todayres)['data']
                    tomorrowjisoshi = json.loads(tomorrowres)['data']

                    today = '您查询的教学楼为: {}\n今天空闲的教室有:'.format(msg.content)
                    tomorrow = '\n明天空闲的教室有:'.format(msg.content)

                    for i in todayjisoshi:
                        if msg.content in i['buildName']:
                            today += i['code'] + ' '
                            for index, j in enumerate(i['lessons']):
                                if not j:
                                    today += str(index + 1) + ' '
                            today += '小节|'

                    for i in tomorrowjisoshi:
                        if msg.content in i['buildName']:
                            tomorrow += i['code'] + ' '
                            for index, j in enumerate(i['lessons']):
                                if not j:
                                    today += str(index + 1) + ' '
                            tomorrow += '小节|'

                    reply = create_reply(today, msg)

                else:
                    reply = create_reply('暂不支持相关信息的查询', msg)

        elif msg.type == 'image':
            reply = create_reply('这是条图片消息', msg)
        elif msg.type == 'voice':
            reply = create_reply('这是条语音消息', msg)
        else:
            reply = create_reply('这是条其他类型消息', msg)
        response = HttpResponse(reply.render(), content_type="application/xml")
        return response
Exemple #14
0
def Reply_Article(msg, reply_dic):
    reply = ArticlesReply(message=msg)
    # simply use dict as article
    reply.add_article(reply_dic)
    return reply.render()