Example #1
0
def test_add_filter():
    import werobot.testing
    import re

    robot = WeRoBot()

    def test_register():
        return "test"

    robot.add_filter(test_register, ["test", re.compile(u".*?啦.*?")])

    tester = werobot.testing.WeTest(robot)

    assert tester.send_xml(_make_xml("test"))._args["content"] == "test"
    assert tester.send_xml(_make_xml(u"我要测试啦"))._args["content"] == "test"
    assert tester.send_xml(_make_xml(u"我要测试")) is None

    with pytest.raises(ValueError) as e:
        robot.add_filter("test", ["test"])
    assert e.value.args[0] == "test is not callable"

    with pytest.raises(ValueError) as e:
        robot.add_filter(test_register, "test")
    assert e.value.args[0] == "test is not list"

    with pytest.raises(TypeError) as e:
        robot.add_filter(test_register, [["bazinga"]])
    assert e.value.args[0] == "[\'bazinga\'] is not a valid rule"
Example #2
0
def test_error_page():
    robot = WeRoBot()

    @robot.error_page
    def make_error_page(url):
        return url

    assert robot.make_error_page('喵') == '喵'
Example #3
0
def test_error_page():
    robot = WeRoBot()

    @robot.error_page
    def make_error_page(url):
        return url

    assert robot.make_error_page('喵') == '喵'
Example #4
0
def test_filter():
    import re
    import werobot.testing
    robot = WeRoBot()

    @robot.filter("喵")
    def _():
        return "喵"

    assert len(robot._handlers["text"]) == 1

    @robot.filter(re.compile(to_text(".*?呵呵.*?")))
    def _():
        return "哼"

    assert len(robot._handlers["text"]) == 2

    @robot.text
    def _():
        return "汪"

    def _make_xml(content):
        return """
            <xml>
            <ToUserName><![CDATA[toUser]]></ToUserName>
            <FromUserName><![CDATA[fromUser]]></FromUserName>
            <CreateTime>1348831860</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <MsgId>1234567890123456</MsgId>
            </xml>
        """ % content

    tester = werobot.testing.WeTest(robot)

    assert tester.send_xml(_make_xml("啊")) == "汪"
    assert tester.send_xml(_make_xml("啊呵呵")) == "哼"
    assert tester.send_xml(_make_xml("喵")) == "喵"

    robot = WeRoBot()

    @robot.filter("帮助", "跪求帮助", re.compile(".*?help.*?"))
    def _():
        return "就不帮"

    assert len(robot._handlers["text"]) == 3

    @robot.text
    def _():
        return "哦"

    tester = werobot.testing.WeTest(robot)

    assert tester.send_xml(_make_xml("啊")) == "哦"
    assert tester.send_xml(_make_xml("帮助")) == "就不帮"
    assert tester.send_xml(_make_xml("跪求帮助")) == "就不帮"
    assert tester.send_xml(_make_xml("ooohelp")) == "就不帮"
Example #5
0
def test_filter():
    import re
    import werobot.testing
    robot = WeRoBot(SESSION_STORAGE=False)

    @robot.filter("喵")
    def _1():
        return "喵"

    assert len(robot._handlers["text"]) == 1

    @robot.filter(re.compile(to_text(".*?呵呵.*?")))
    def _2():
        return "哼"

    assert len(robot._handlers["text"]) == 2

    @robot.text
    def _3():
        return "汪"

    assert len(robot._handlers["text"]) == 3

    tester = werobot.testing.WeTest(robot)

    assert tester.send_xml(_make_xml("啊"))._args['content'] == u"汪"
    assert tester.send_xml(_make_xml("啊呵呵"))._args['content'] == u"哼"
    assert tester.send_xml(_make_xml("喵"))._args['content'] == u"喵"

    try:
        os.remove(os.path.abspath("werobot_session"))
    except OSError:
        pass
    robot = WeRoBot(SESSION_STORAGE=False)

    @robot.filter("帮助", "跪求帮助", re.compile("(.*?)help.*?"))
    def _(message, session, match):
        if match and match.group(1) == u"小姐姐":
            return "本小姐就帮你一下"
        return "就不帮"

    assert len(robot._handlers["text"]) == 3

    @robot.text
    def _4():
        return "哦"

    assert len(robot._handlers["text"]) == 4

    tester = werobot.testing.WeTest(robot)

    assert tester.send_xml(_make_xml("啊"))._args['content'] == u"哦"
    assert tester.send_xml(_make_xml("帮助"))._args['content'] == u"就不帮"
    assert tester.send_xml(_make_xml("跪求帮助"))._args['content'] == u"就不帮"
    assert tester.send_xml(_make_xml("ooohelp"))._args['content'] == u"就不帮"
    assert tester.send_xml(
        _make_xml("小姐姐help"))._args['content'] == u"本小姐就帮你一下"
Example #6
0
def test_config_attribute():
    robot = WeRoBot(SESSION_STORAGE=False)
    assert not robot.token
    token = generate_token()
    robot.config["TOKEN"] = token
    assert robot.token == token

    token = generate_token()
    robot.token = token
    assert robot.config["TOKEN"] == token
Example #7
0
def test_config_attribute():
    robot = WeRoBot(enable_session=False)
    assert not robot.token
    token = generate_token()
    robot.config["TOKEN"] = token
    assert robot.token == token

    token = generate_token()
    robot.token = token
    assert robot.config["TOKEN"] == token
Example #8
0
def test_add_filter():
    import werobot.testing
    import re

    robot = WeRoBot()

    def test_register():
        return "test"

    robot.add_filter(test_register, ["test", re.compile(u".*?啦.*?")])

    tester = werobot.testing.WeTest(robot)

    assert tester.send_xml(_make_xml("test"))._args["content"] == "test"
    assert tester.send_xml(_make_xml(u"我要测试啦"))._args["content"] == "test"
    assert tester.send_xml(_make_xml(u"我要测试")) is None

    with pytest.raises(ValueError) as e:
        robot.add_filter("test", ["test"])
    assert e.value.args[0] == "test is not callable"

    with pytest.raises(ValueError) as e:
        robot.add_filter(test_register, "test")
    assert e.value.args[0] == "test is not list"

    with pytest.raises(TypeError) as e:
        robot.add_filter(test_register, [["bazinga"]])
    assert e.value.args[0] == "[\'bazinga\'] is not a valid rule"
Example #9
0
def test_filter():
    import re
    import werobot.testing
    robot = WeRoBot(enable_session=False)

    @robot.filter("喵")
    def _1():
        return "喵"

    assert len(robot._handlers["text"]) == 1

    @robot.filter(re.compile(to_text(".*?呵呵.*?")))
    def _2():
        return "哼"

    assert len(robot._handlers["text"]) == 2

    @robot.text
    def _3():
        return "汪"

    assert len(robot._handlers["text"]) == 3

    tester = werobot.testing.WeTest(robot)

    assert tester.send_xml(_make_xml("啊"))._args['content'] == u"汪"
    assert tester.send_xml(_make_xml("啊呵呵"))._args['content'] == u"哼"
    assert tester.send_xml(_make_xml("喵"))._args['content'] == u"喵"

    try:
        os.remove(os.path.abspath("werobot_session"))
    except OSError:
        pass
    robot = WeRoBot(enable_session=False)

    @robot.filter("帮助", "跪求帮助", re.compile(".*?help.*?"))
    def _():
        return "就不帮"

    assert len(robot._handlers["text"]) == 3

    @robot.text
    def _4():
        return "哦"

    assert len(robot._handlers["text"]) == 4

    tester = werobot.testing.WeTest(robot)

    assert tester.send_xml(_make_xml("啊"))._args['content'] == u"哦"
    assert tester.send_xml(_make_xml("帮助"))._args['content'] == u"就不帮"
    assert tester.send_xml(_make_xml("跪求帮助"))._args['content'] == u"就不帮"
    assert tester.send_xml(_make_xml("ooohelp"))._args['content'] == u"就不帮"
Example #10
0
def test_signature_checker():
    token = generate_token()

    robot = WeRoBot(token, SESSION_STORAGE=False)

    timestamp = str(int(time.time()))
    nonce = '12345678'

    sign = [token, timestamp, nonce]
    sign.sort()
    sign = ''.join(sign)
    sign = sign.encode()
    sign = hashlib.sha1(sign).hexdigest()

    assert robot.check_signature(timestamp, nonce, sign)
Example #11
0
def test_signature_checker():
    token = generate_token()

    robot = WeRoBot(token, enable_session=False)

    timestamp = str(int(time.time()))
    nonce = "12345678"

    sign = [token, timestamp, nonce]
    sign.sort()
    sign = "".join(sign)
    if six.PY3:
        sign = sign.encode()
    sign = hashlib.sha1(sign).hexdigest()

    assert robot.check_signature(timestamp, nonce, sign)
Example #12
0
def test_signature_checker():
    token = generate_token()

    robot = WeRoBot(token, SESSION_STORAGE=False)

    timestamp = str(int(time.time()))
    nonce = '12345678'

    sign = [token, timestamp, nonce]
    sign.sort()
    sign = ''.join(sign)
    if six.PY3:
        sign = sign.encode()
    sign = hashlib.sha1(sign).hexdigest()

    assert robot.check_signature(timestamp, nonce, sign)
Example #13
0
def test_config_ignore():
    from werobot.config import Config
    config = Config(
        TOKEN="token from config"
    )
    robot = WeRoBot(
        config=config,
        token="token2333"
    )
    assert robot.token == "token from config"
Example #14
0
def hello_robot():
    from werobot import WeRoBot
    robot = WeRoBot(token='', enable_session=False)

    @robot.text
    def hello():
        return 'hello'

    @robot.error_page
    def make_error_page(url):
        return '喵'

    return robot
Example #15
0
def hello_robot():
    from werobot import WeRoBot
    robot = WeRoBot(token='', SESSION_STORAGE=False)

    @robot.text
    def hello():
        return 'hello'

    @robot.error_page
    def make_error_page(url):
        return '喵'

    return robot
Example #16
0
def test_register_not_callable_object():
    robot = WeRoBot(enable_session=False)
    with pytest.raises(ValueError):
        robot.add_handler("s")
Example #17
0
#coding:utf-8
from werobot import WeRoBot
from werobot.reply import TextReply,MusicReply,Article,ArticlesReply
from werobot.client import *
from werobot.messages import WeChatMessage
robot = WeRoBot(token='kefengwei')


@robot.subscribe
def subscribe_me(message):
    reply = ArticlesReply(message=message)
    article = Article(
    title="WeRoBot",
    description="WeRoBot是一个微信机器人框架",
    img="https://github.com/apple-touch-icon-144.png",
    url="https://github.com/whtsky/WeRoBot"
    )
    reply.add_article(article)
    return reply

@robot.unsubscribe
def unsubscribe_me(message):
    print 'One User leave us!'

@robot.text
def hello_world(message):
    print
    print "User Info:",client.get_user_info(message.source,'en')
    content =  message.content
    print message.source
    print message.target
Example #18
0
def test_register_not_callable_object():
    robot = WeRoBot()
    robot.add_handler("s")
Example #19
0
# @Time    : 2019/12/10 12:00
# @Author  : Libuda
# @FileName: webot.py
# @Software: PyCharm
import requests
from werobot import WeRoBot
import xlrd
from xlutils.copy import copy
from check_link import get_keywords_data

appID = 'wxf74f52d6e57f9e0e'
appsecret = 'c63f351e9a9041d03da9370948de1f16'
token = 'asdfghgfdsaasdfggfdsasdf'
robot = WeRoBot(token=token)

link_file_path = r"C:\Users\lenovo\PycharmProjects\leetcode-python-\微信公众号\link.xls"
link_ecel = xlrd.open_workbook(link_file_path)
link_tables = link_ecel.sheet_by_index(0)
link_get_col = 2
link_write_col = 3
link_can_write_index = 1
link_data = [
    get_keywords_data(link_tables, i, link_get_col)
    for i in range(1, link_tables.nrows)
]

openid_file_path = r'C:\Users\lenovo\PycharmProjects\leetcode-python-\微信公众号\openid'


def write_to_excel(file_path, row, col, value):
    work_book = xlrd.open_workbook(file_path, formatting_info=False)
Example #20
0
from werobot import WeRoBot
from tencent_ai import*
from baidu_ai import*

# def get_content(plus_item):
#     # 聊天的API地址
#     url = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat"
#     # 获取请求参数
#     plus_item = plus_item.encode('utf-8')
#     payload = md5sign.get_params(plus_item)
#     # r = requests.get(url,params=payload)
#     r = requests.post(url,data=payload)
#     return r.json()["data"]["answer"]

robot = WeRoBot(enable_session=False,
        token = 'wechat',
        APP_ID = 'wxd2037f04aeb582fb',
        APP_SECRET = 'ti8e627JwSwqSVYoPDH2E6qR1GqP65cGRNqpKimdGEf')
 
@robot.text
def hello(message):   
    if is_pessimistic(message.content):
        rep = "十分抱歉给您带来的不便,我们这边马上安排工作人员和您沟通。"
        # account_sid = "ACc290a6cb0258540264b0ebb1f6a37d60"
        # auth_token = "fa5c345aedc44bc5888f843a3bbe53ed"
        # client = Client(account_sid, auth_token)
        # message = client.messages.create(to="+8617359870570",  # 区号+你的手机号码
        #                                 from_="+12023359371",  # 你的 twilio 电话号码
        #                                 body="你的客户xxx,需要你马上处理。")
        return rep
    else:    
        rep= get_content(message.content)
Example #21
0
"""

from werobot import WeRoBot
import re
from werobot.replies import ArticlesReply, MusicReply, ImageReply, Article
from .MemcacheStorage import MemcacheStorage
from servermanager.Api.blogapi import BlogApi
from servermanager.Api.commonapi import TuLing
import os
import json
from DjangoBlog.utils import get_md5
from django.conf import settings
import jsonpickle
from servermanager.models import commands

robot = WeRoBot(token='lylinux', enable_session=True)
memstorage = MemcacheStorage()
if memstorage.is_available:
    robot.config['SESSION_STORAGE'] = memstorage
else:
    from werobot.session.filestorage import FileStorage
    import os
    from django.conf import settings

    if os.path.exists(os.path.join(settings.BASE_DIR, 'werobot_session')):
        os.remove(os.path.join(settings.BASE_DIR, 'werobot_session'))
    robot.config['SESSION_STORAGE'] = FileStorage(filename='werobot_session')
blogapi = BlogApi()
tuling = TuLing()

Example #22
0
   date:          2018/12/3
-------------------------------------------------
   Change Activity:
                   2018/12/3:
-------------------------------------------------
"""
import re
from werobot import WeRoBot
from werobot.replies import TextReply
from werobot.replies import ArticlesReply, Article
from .django_api import check_auth, new_query
from .commando_query import call_fx_api
from .alarm_query import old_alarm_query, fuzzy_query
from bot.base_conf import APP_URL

myrobot = WeRoBot(token='loyowanwancc')

# app_id='wx242d734cd4057dc5', app_secret='a1ffde51020438f076e43e3b19973648',
#                   encoding_aes_key='S24igTjZOhFawPXnUbLslXjs4LMwsEEyp7lJ4fUn1xI'


@myrobot.subscribe
def hello(message):
    return '欢迎您使用“网络维护一点通”!\n' + '您的ID为:' + message.source + '\n请联系管理员添加为内部用户。'


@myrobot.image
@myrobot.voice
def unknown(message):
    return '暂不支持的消息类型,敬请期待。'
Example #23
0
 def test_robot_reuse_client(self):
     robot = WeRoBot()
     client_1 = robot.client
     client_2 = robot.client
     assert client_1 is client_2
Example #24
0
def test_register_handlers():
    robot = WeRoBot(enable_session=False)

    for type in robot.message_types:
        assert hasattr(robot, type) or \
               hasattr(robot, type.replace('_event', ''))

    @robot.text
    def text_handler():
        return "Hi"

    assert robot._handlers["text"] == [(text_handler, 0)]

    @robot.image
    def image_handler(message):
        return 'nice pic'

    assert robot._handlers["image"] == [(image_handler, 1)]

    assert robot.get_handlers("text") == [(text_handler, 0)]

    @robot.handler
    def handler(message, session):
        pass

    assert robot.get_handlers("text") == [(text_handler, 0), (handler, 2)]

    @robot.location
    def location_handler():
        pass

    assert robot._handlers["location"] == [(location_handler, 0)]

    @robot.link
    def link_handler():
        pass

    assert robot._handlers["link"] == [(link_handler, 0)]

    @robot.subscribe
    def subscribe_handler():
        pass

    assert robot._handlers["subscribe_event"] == [(subscribe_handler, 0)]

    @robot.unsubscribe
    def unsubscribe_handler():
        pass

    assert robot._handlers["unsubscribe_event"] == [(unsubscribe_handler, 0)]

    @robot.voice
    def voice_handler():
        pass

    assert robot._handlers["voice"] == [(voice_handler, 0)]

    @robot.click
    def click_handler():
        pass

    assert robot._handlers["click_event"] == [(click_handler, 0)]

    @robot.key_click("MENU")
    def menu_handler():
        pass

    assert len(robot._handlers["click_event"]) == 2
Example #25
0
 def test_robot_client(self):
     robot = WeRoBot()
     assert robot.client.config == robot.config
Example #26
0
#coding=utf8
import time
import re
from werobot import WeRoBot
from apps.blog.venaAI import venaAI
from apps.tensorflow_poems.gen_good_poems import PoemPool
from apps.blog.models import User, Poem

robot = WeRoBot(enable_session=False, token='', APP_ID='', APP_SECRET='')
poem = PoemPool()
vena = venaAI()


@robot.subscribe
def subscribe(message):
    User.objects.create(source=message.source)
    return '欢迎关注本公众号!'


@robot.text
def text_handle(message):
    cont = message.content.lower()
    source = message.source
    user = User.objects.get_or_create(source=source)[0]
    mode = user.mode
    print(cont + " end")
    print("mode: %d" % mode)
    print(re.match(r'leave', cont))
    if re.match(r'leave', cont):
        print("leaving the room")
        ret = User.room_choose(user, 1)
Example #27
0
from werobot import WeRoBot

robot = WeRoBot(token='token')


@robot.handler
def hello(message):
    return 'Hello World!'


from flask import Flask
from werobot.contrib.flask import make_view

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

app.add_url_rule(
    rule='/',  # WeRoBot 的绑定地址
    endpoint='werobot',  # Flask 的 endpoint
    view_func=make_view(robot),
    methods=['GET', 'POST'])

app.run()
Example #28
0
def test_register_handlers():  # noqa: C901
    robot = WeRoBot(SESSION_STORAGE=False)

    for type in robot.message_types:
        assert hasattr(robot,
                       type) or hasattr(robot, type.replace('_event', ''))

    @robot.text
    def text_handler():
        return "Hi"

    assert robot._handlers["text"] == [(text_handler, 0)]

    @robot.image
    def image_handler(message):
        return 'nice pic'

    assert robot._handlers["image"] == [(image_handler, 1)]

    assert robot.get_handlers("text") == [(text_handler, 0)]

    @robot.handler
    def handler(message, session):
        pass

    assert robot.get_handlers("text") == [(text_handler, 0), (handler, 2)]

    @robot.video
    def video_handler():
        pass

    assert robot._handlers["video"] == [(video_handler, 0)]
    assert robot.get_handlers("video") == [(video_handler, 0), (handler, 2)]

    @robot.shortvideo
    def shortvideo_handler():
        pass

    assert robot._handlers["shortvideo"] == [(shortvideo_handler, 0)]
    assert robot.get_handlers("shortvideo") == [
        (shortvideo_handler, 0), (handler, 2)
    ]

    @robot.location
    def location_handler():
        pass

    assert robot._handlers["location"] == [(location_handler, 0)]

    @robot.link
    def link_handler():
        pass

    assert robot._handlers["link"] == [(link_handler, 0)]

    @robot.subscribe
    def subscribe_handler():
        pass

    assert robot._handlers["subscribe_event"] == [(subscribe_handler, 0)]

    @robot.unsubscribe
    def unsubscribe_handler():
        pass

    assert robot._handlers["unsubscribe_event"] == [(unsubscribe_handler, 0)]

    @robot.voice
    def voice_handler():
        pass

    assert robot._handlers["voice"] == [(voice_handler, 0)]

    @robot.click
    def click_handler():
        pass

    assert robot._handlers["click_event"] == [(click_handler, 0)]

    @robot.key_click("MENU")
    def menu_handler():
        pass

    assert len(robot._handlers["click_event"]) == 2

    @robot.scan
    def scan_handler():
        pass

    assert robot._handlers["scan_event"] == [(scan_handler, 0)]

    @robot.scancode_push
    def scancode_push_handler():
        pass

    assert robot._handlers["scancode_push_event"] == [
        (scancode_push_handler, 0)
    ]

    @robot.scancode_waitmsg
    def scancode_waitmsg_handler():
        pass

    assert robot._handlers["scancode_waitmsg_event"] == [
        (scancode_waitmsg_handler, 0)
    ]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 11:00:36 2020

@author: cengqiqi
"""

import werobot
from werobot import WeRoBot
from werobot.replies import ArticlesReply, Article,ImageReply,TextReply

from weNewsModel.sender_wechatSender import get_title_text


robot = WeRoBot(enable_session=False,
                token='qiqi123',
                APP_ID='wx20e742b0ab9bfb54',
                APP_SECRET='be5e8743181098d92ac82bd80b758d57')

@robot.text
def echo(message):
    title, text = get_title_text()
    reply = TextReply(message=message, content=text)
    return reply

# 让服务器监听在 0.0.0.0:80
# robot.config['HOST'] = '0.0.0.0'
# robot.config['PORT'] = 443
# ß
"""
Created on Mon Aug 26 17:00:47 2019

@author: Administrator
"""

# 被关注回复'Hello World!'
# 收到 笑话 回复糗百笑话,收到收到 电影 回复电影天堂最新电影,
# 收到 blog 回复我的简书博客,收到 音乐 回复一首音乐
# 收到 fight 回复一句话

from werobot import WeRoBot
import random
from werobot.replies import ArticlesReply, Article

robot = WeRoBot(token='your_token')
# 明文模式不需要下面三项
#robot.config["APP_ID"]=''
#robot.config["APP_SECRET"]=''
#robot.config['ENCODING_AES_KEY'] = ''

# 被关注
@robot.subscribe
def subscribe(message):
    return '''Hello World!
And nice to meet you.
:)
'''

# 读取文档里的笑话,把前三行存在 data2 里,字符串太长公众号会报错
def joke_data():
Example #31
0
"""

from werobot import WeRoBot
import re
from werobot.replies import ArticlesReply, MusicReply, ImageReply, Article
from .MemcacheStorage import MemcacheStorage
from servermanager.Api.blogapi import BlogApi
from servermanager.Api.commonapi import TuLing
import os
import json
from web.utils import get_md5
from django.conf import settings
import jsonpickle
from servermanager.models import commands

robot = WeRoBot(token='lylinux', enable_session=True)
memstorage = MemcacheStorage()
# TODO 在容器中会报错 不存在文件werobot_session 但是文件在容器中是存在的 可能是操作系统的原因
# if memstorage.is_available:
#     robot.config['SESSION_STORAGE'] = memstorage
# else:
#     from werobot.session.filestorage import FileStorage
#     import os
#     from django.conf import settings
#
#     if os.path.exists(os.path.join(settings.BASE_DIR, 'werobot_session')):
#         print("=====================================")
#         print(os.path.join(settings.BASE_DIR, 'werobot_session'))
#         os.remove(os.path.join(settings.BASE_DIR, 'werobot_session'))
#     robot.config['SESSION_STORAGE'] = FileStorage(filename='werobot_session')
blogapi = BlogApi()
Example #32
0
def test_register_not_callable_object():
    robot = WeRoBot(SESSION_STORAGE=False)
    with pytest.raises(ValueError):
        robot.add_handler("s")
Example #33
0
def test_register_not_callable_object():
    robot = WeRoBot(enable_session=False)
    with pytest.raises(ValueError):
        robot.add_handler("s")
Example #34
0
def test_register_handlers():  # noqa: C901
    robot = WeRoBot(SESSION_STORAGE=False)

    for type in robot.message_types:
        assert hasattr(robot, type) or hasattr(robot, type.replace(
            '_event', ''))

    @robot.text
    def text_handler():
        return "Hi"

    assert robot._handlers["text"] == [(text_handler, 0)]

    @robot.image
    def image_handler(message):
        return 'nice pic'

    assert robot._handlers["image"] == [(image_handler, 1)]

    assert robot.get_handlers("text") == [(text_handler, 0)]

    @robot.handler
    def handler(message, session):
        pass

    assert robot.get_handlers("text") == [(text_handler, 0), (handler, 2)]

    @robot.video
    def video_handler():
        pass

    assert robot._handlers["video"] == [(video_handler, 0)]
    assert robot.get_handlers("video") == [(video_handler, 0), (handler, 2)]

    @robot.shortvideo
    def shortvideo_handler():
        pass

    assert robot._handlers["shortvideo"] == [(shortvideo_handler, 0)]
    assert robot.get_handlers("shortvideo") == [(shortvideo_handler, 0),
                                                (handler, 2)]

    @robot.location
    def location_handler():
        pass

    assert robot._handlers["location"] == [(location_handler, 0)]

    @robot.link
    def link_handler():
        pass

    assert robot._handlers["link"] == [(link_handler, 0)]

    @robot.subscribe
    def subscribe_handler():
        pass

    assert robot._handlers["subscribe_event"] == [(subscribe_handler, 0)]

    @robot.unsubscribe
    def unsubscribe_handler():
        pass

    assert robot._handlers["unsubscribe_event"] == [(unsubscribe_handler, 0)]

    @robot.voice
    def voice_handler():
        pass

    assert robot._handlers["voice"] == [(voice_handler, 0)]

    @robot.click
    def click_handler():
        pass

    assert robot._handlers["click_event"] == [(click_handler, 0)]

    @robot.key_click("MENU")
    def menu_handler():
        pass

    assert len(robot._handlers["click_event"]) == 2

    @robot.scan
    def scan_handler():
        pass

    assert robot._handlers["scan_event"] == [(scan_handler, 0)]

    @robot.scancode_push
    def scancode_push_handler():
        pass

    assert robot._handlers["scancode_push_event"] == [(scancode_push_handler,
                                                       0)]

    @robot.scancode_waitmsg
    def scancode_waitmsg_handler():
        pass

    assert robot._handlers["scancode_waitmsg_event"] == [
        (scancode_waitmsg_handler, 0)
    ]
Example #35
0
# coding:utf-8
from werobot import WeRoBot
from werobot.contrib.django import make_view
from KillMe.settings import token, APP_ID, APP_SECRET
from wechat.message.text.view import index as text_func
from wechat.message.image.view import image_func
from wechat.event.subscribe import subscribe_event
from wechat.event.face import face_to_face
from wechat.event.chat import chat_func
from wechat.event.star import star_func
from wechat.event.train import train_func
from wechat.event.wangpan import wang_func

robot = WeRoBot(
    token=token,
    APP_ID=APP_ID,
    APP_SECRET=APP_SECRET)

client = robot.client


@robot.text
def handler_text(message, session):
    reply = text_func(message, session)
    return reply


@robot.image
def handle_image(message, session):
    reply = image_func(message, session)
    return reply
Example #36
0
from werobot import WeRoBot
from config import WechatConfig


myrobot = WeRoBot(token=WechatConfig.Token)
myrobot.config["APP_ID"] = WechatConfig.AppID
myrobot.config["APP_SECRET"] = WechatConfig.AppSecret

client = myrobot.client

client.create_menu({
    "button": [{
         "type": "click",
         "name": "hha",
         "key": "test_btn"
    }]
})


@myrobot.text
def text(message):
    return "{}".format(message.content)


@myrobot.subscribe
def subscribe(message):
    return "谢谢关注!"


@myrobot.key_click("test_btn")
def abort():
Example #37
0
import random
import pandas as pd
import jieba
from sklearn.feature_extraction.text import TfidfVectorizer
import re
import numpy as np
from scipy.spatial.distance import cosine
from functools import reduce
from operator import and_
import q_a

# from chatterbot import ChatBot
# from chatterbot.trainers import ChatterBotCorpusTrainer
# global chatbot

myrobot = WeRoBot(token=cfg.token)
myrobot.config["APP_ID"] = cfg.appid
myrobot.config['ENCODING_AES_KEY'] = cfg.aeskey

# chatbot = ChatBot("ChineseChatBot")
# trainer = ChatterBotCorpusTrainer(chatbot)
# trainer.train("chatterbot.corpus.chinese")


@myrobot.image
def image_repeat(message, session):
    return message.img


@myrobot.text
def test_repeat(message):
Example #38
0
# coding:utf-8
# Filename:return_message5.py
# 被关注回复'Hello World!'
# 收到 笑话 回复糗百笑话,收到收到 电影 回复电影天堂最新电影,
# 收到 blog 回复我的简书博客,收到 音乐 回复一首音乐
# 收到 fight 回复一句话

from werobot import WeRoBot
import random
from werobot.replies import ArticlesReply, Article

robot = WeRoBot(token='wystech')

# 明文模式不需要下面三项
# robot.config["APP_ID"]=''
# robot.config["APP_SECRET"]=''
# robot.config['ENCODING_AES_KEY'] = ''


# 被关注
@robot.subscribe
def subscribe(message):
    return '''Hello World!
And nice to meet you.
:)
'''


# 读取文档里的笑话,把前三行存在 data2 里,字符串太长公众号会报错
def joke_data():
    filename = 'qiushibaike.txt'
Example #39
0
# @Version: V1.0
# @Author: wevsmy
# @License: Apache Licence
# @Contact: [email protected]
# @Site: https://blog.weii.ink
# @Software: PyCharm
# @File: robot.py
# @Time: 2020/6/8 10:52
from werobot import WeRoBot
from werobot.client import Client
from werobot.messages.messages import *

from app.config.settings import WX_PUBLIC_TOKEN

wx_robot = WeRoBot(token=WX_PUBLIC_TOKEN)

# Event
# #################################################################


# 新用户关注的消息
@wx_robot.subscribe
def subscribe(message):
    return 'Hello My Friend!'


# 取消关注事件
@wx_robot.unsubscribe
def unsubscribe(message):
    return 'unsubscribe'
Example #40
0
from werobot import WeRoBot

myrobot = WeRoBot(token='hwmobilebus')
myrobot.config["APP_ID"] = "wxd6ac78fadc53c8d5"
myrobot.config["APP_SECRET"] = "f831286ea21d818221c5df4f5247c98f"

client = myrobot.client

#@myrobot.text
#def articles(message):
#    return [
#        [
#            "title",
#            "description",
#            "img",
#            "url"
#        ],
#        [
#            "进入Mobilebus",
#            "Mobilebus",
#            "https://secure.gravatar.com/avatar/0024710771815ef9b74881ab21ba4173?s=420",
#            "http://mbus.honeywell.com.cn"
#        ]
#    ]
from werobot.replies import ArticlesReply, Article


@myrobot.handler
def reply(message):
    reply = ArticlesReply(content="HoneywellMobilebus", message=message)
    article = Article(
Example #41
0
def test_register_not_callable_object():
    robot = WeRoBot(SESSION_STORAGE=False)
    with pytest.raises(ValueError):
        robot.add_handler("s")