WeRoBot Documentation

repository·master·Indexed 26 days ago

https://github.com/offu/werobot

A Python framework for developing WeChat Official Accounts that simplifies message handling and platform interaction. It includes a Client for managing access tokens, custom menus, media assets, user groups, and tags. WeRoBot provides multiple session storage backends (File, SQLite, MySQL, PostgreSQL, MongoDB, Redis, SaeKVDB) and offers integration support for Django, Flask, and Bottle.

Tokens
14.1K
Snippets
33
Records
114
Agent score
88%

What's inside WeRoBot

  1. Customize the error page for failed Signature verification

    master

    By default, WeRoBot provides a built-in error page that is returned when Signature verification fails. You can override this behavior by using the @robot.error_page decorator on a function. This function must accept a url argument and return a string containing the HTML content for the error page.

    @robot.error_page
    def make_error_page(url):
        return "<h1>喵喵喵 %s 不是给麻瓜访问的快走开</h1>" % url
  2. Create a Hello World WeChat Official Account

    master

    To create a basic WeChat Official Account that responds to all text messages with 'Hello World!', initialize a WeRoBot instance with your security token, use the @robot.text decorator to define the response logic, and call robot.run() to start the server.

    import werobot
    
    robot = werobot.WeRoBot(token='tokenhere')
    
    @robot.text
    def hello_world():
        return 'Hello World!'
    
    robot.run()
  3. Integrate WeRoBot with Bottle

    master

    To integrate WeRoBot into a Bottle application, use werobot.contrib.bottle.make_view within the app.route method.

    from werobot import WeRoBot
    
    myrobot = WeRoBot(token='token')
    
    @myrobot.handler
    def hello(message):
        return 'Hello World!'
    
    from bottle import Bottle
    from werobot.contrib.bottle import make_view
    
    app = Bottle()
    app.route('/robot',  # WeRoBot mount path
             ['GET', 'POST'],
             make_view(myrobot))
  4. Integrate WeRoBot with Django

    master

    WeRoBot supports Django 2.2+. To integrate, first define your WeRoBot instance in a file (e.g., robot.py). Then, use werobot.contrib.django.make_view in your project's urls.py to map a URL pattern to the robot instance.

    # Filename: robot.py
    from werobot import WeRoBot
    
    myrobot = WeRoBot(token='token')
    
    @myrobot.handler
    def hello(message):
        return 'Hello World!'
    
    # In your Django urls.py
    from django.conf.urls import patterns, include, url
    from werobot.contrib.django import make_view
    from robot import myrobot
    
    urlpatterns = patterns('',
        url(r'^robot/', make_view(myrobot)),
    )
  5. Use Session to track user state

    master

    You can use the session object to record and manage user state across different interactions. When a handler is configured to use sessions, the session object is passed as a second argument to the handler function and behaves like a standard Python dictionary.

    from werobot import WeRoBot
    robot = WeRoBot(token=werobot.utils.generate_token())
    
    @robot.text
    def first(message, session):
        if 'last' in session:
            return
        session['last'] = message.content
        return message.content
    
    robot.run()
  6. Filter handlers by message type

    master

    To prevent a handler from processing every message, you can use specific decorators to filter by message type (e.g., text, image, location) or event type (e.g., subscribe, click).

    You can also stack decorators to handle multiple types with a single function, or use add_handler with a type argument.

    import werobot
    
    robot = werobot.WeRoBot(token='tokenhere')
    
    # Handle only new subscriptions
    @robot.subscribe
    def subscribe(message):
        return 'Hello My Friend!'
    
    # Handle only text messages
    @robot.text
    def echo(message):
        return message.content
    
    # Handle multiple types (text AND location)
    @robot.text
    @robot.location
    def handler(message):
        pass
    
    # Using add_handler with type filtering
    def handler(message):
        pass
    
    robot.add_handler(handler, type='text')
    robot.add_handler(handler, type='location')
    
    robot.run()
  7. Integrate WeRoBot with Flask

    master

    To integrate WeRoBot into a Flask application, define your WeRoBot instance and then use werobot.contrib.flask.make_view as the view_func in app.add_url_rule.

    # Filename: robot.py
    from werobot import WeRoBot
    
    myrobot = WeRoBot(token='token')
    
    @myrobot.handler
    def hello(message):
        return 'Hello World!'
    
    # In your Flask app
    from flask import Flask
    from robot import myrobot
    from werobot.contrib.flask import make_view
    
    app = Flask(__name__)
    app.add_url_rule(rule='/robot/', # WeRoBot mount path
                     endpoint='werobot',
                     view_func=make_view(myrobot),
                     methods=['GET', 'POST'])
  8. Manage user state using Session

    master

    The Session feature allows you to record and persist user states. Session functionality is enabled by default and uses SQLite for storage. You can access the session object as an argument in your handler functions to check for existing keys or set new ones.

    @robot.text
    def first(message, session):
        if 'first' in session:
            return '你之前给我发过消息'
        session['first'] = True
        return '你之前没给我发过消息'
  9. Deploy WeRoBot on a standalone server using `werobot.run`

    master

    You can start a WSGI server directly using werobot.run. Configure the listening address and port via robot.config.

    Note: You need root or administrator privileges to listen on ports below 1024.

    By default, server is set to 'auto', which attempts to use available servers in this order: Waitress, Paste, Twisted, CherryPy, and WSGIRef.

    Warning: WSGIRef has very poor performance and should only be used for development. For production, ensure a different server is installed and used.

    import werobot
    
    robot = werobot.WeRoBot(token='tokenhere')
    
    @robot.handler
    def echo(message):
        return 'Hello World!'
    
    robot.config['HOST'] = '0.0.0.0'
    robot.config['PORT'] = 80
    
    # You can also specify a server explicitly, e.g., robot.run(server='gevent')
    robot.run()
  10. Modify Handlers to accept the session parameter

    master

    If Session is enabled, you can choose how your handlers interact with it:

    1. Without Session usage: Keep the handler signature as is (e.g., def handler(message):).
    2. With Session usage: Modify the handler to accept a second parameter named session (e.g., def handler(message, session):). The session parameter is a standard Python dictionary.
    # Handler using session to track message count
    @robot.text
    def hello(message, session):
        count = session.get("count", 0) + 1
        session["count"] = count
        return "Hello! You have sent %s messages to me" % count
  11. Create custom WeChat menus via Client API

    master

    You can use the werobot.client.Client to interact with WeChat APIs, such as creating custom menus. To use the client, you must first configure your APP_ID and APP_SECRET in the robot.config dictionary.

    Note: The menu creation code only needs to be executed once. After creating the menu, use the @robot.key_click decorator to handle the button clicks.

    from werobot import WeRoBot
    robot = WeRoBot()
    robot.config["APP_ID"] = "你的 AppID"
    robot.config["APP_SECRET"] = "你的 AppSecret"
    
    client = robot.client
    
    # Create the menu
    client.create_menu({
        "button":[{\n             "type": "click",
                 "name": "今日歌曲",
                 "key": "music"
            }]
    })
    
    # Handle the menu click
    @robot.key_click("music")
    def music(message):
        return '你点击了“今日歌曲”按钮'
  12. Add handlers to WeRoBot

    master

    WeRoBot processes incoming requests by executing handlers in sequence. If a handler returns a non-empty value, WeRoBot uses that value to create a response and stops executing subsequent handlers.

    You can add handlers using decorators or the add_handler method.

    import werobot
    
    robot = werobot.WeRoBot(token='tokenhere')
    
    # Using decorators
    @robot.handler
    def echo(message):
        return 'Hello World!'
    
    # Using add_handler
    def echo(message):
        return 'Hello World!'
    robot.add_handler(echo)