### Setting Up Development Environment Source: https://github.com/offu/werobot/blob/master/docs/contribution-guide.rst Instructions for setting up a virtual environment for WeRoBot development using virtualenv and installing necessary packages. ```shell # Python 3.5 python -m venv venv ``` ```shell # virtualenv is highly recommended. virtualenv venv # Activate virtualenv. source venv/bin/activate # Install dev packages. pip install -r dev-requirements.txt ``` -------------------------------- ### Install WeRoBot Source: https://github.com/offu/werobot/blob/master/README.rst This command installs the WeRoBot framework using pip, the Python package installer. It's the recommended method for setting up the library. ```bash pip install werobot ``` -------------------------------- ### Running WeRoBot with WSGI Server Source: https://github.com/offu/werobot/blob/master/docs/deploy.rst This snippet demonstrates how to start a WeRoBot application using the `werobot.run` function, which can be configured to listen on a specific host and port. It also shows how to specify a WSGI server like 'gevent'. ```python 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 robot.run() # Example with a specific server: # robot.run(server='gevent') ``` -------------------------------- ### Hello World Example Source: https://github.com/offu/werobot/blob/master/docs/start.rst A simple 'Hello World' example that replies to every incoming message with 'Hello World!'. It also configures the server host and port. ```python import werobot robot = werobot.WeRoBot(token='tokenhere') @robot.handler def hello(message): return 'Hello World!' # 让服务器监听在 0.0.0.0:80 robot.config['HOST'] = '0.0.0.0' robot.config['PORT'] = 80 robot.run() ``` -------------------------------- ### WeRoBot Deployment on SAE Source: https://github.com/offu/werobot/blob/master/docs/deploy.rst This demonstrates the setup for deploying WeRoBot on Sina App Engine (SAE). It involves creating a `robot.py` file with the WeRoBot instance and an `index.wsgi` file to integrate it with SAE's WSGI application. ```python # filename: robot.py import werobot robot = werobot.WeRoBot(token='tokenhere') @robot.handler def echo(message): return 'Hello World!' # filename: index.wsgi import sae from robot import robot application = sae.create_wsgi_app(robot.wsgi) ``` -------------------------------- ### Code Formatting with yapf Source: https://github.com/offu/werobot/blob/master/docs/contribution-guide.rst How to format WeRoBot code using yapf, including installation and command-line usage for recursive formatting. ```shell # Install yapf pip install yapf # format code yapf -i -p -r werobot/ tests/ *.py ``` -------------------------------- ### Deploying WeRoBot with Gunicorn Source: https://github.com/offu/werobot/blob/master/docs/deploy.rst This example shows how to deploy a WeRoBot application using Gunicorn, a popular WSGI HTTP Server. It assumes the WeRoBot instance is named 'robot' and is accessible via 'robot:robot.wsgi'. ```bash gunicorn robot:robot.wsgi ``` -------------------------------- ### WeRoBot Hello World Example Source: https://github.com/offu/werobot/blob/master/README.rst A basic example demonstrating how to create a WeChat official account bot using WeRoBot. This bot replies with 'Hello World!' to any incoming text message. It requires a token for authentication. ```python import werobot robot = werobot.WeRoBot(token='tokenhere') @robot.text def hello_world(): return 'Hello World!' robot.run() ``` -------------------------------- ### Running Tests Locally Source: https://github.com/offu/werobot/blob/master/docs/contribution-guide.rst Commands to run tests locally for WeRoBot, including basic testing via setup.py and multi-version compatibility testing with tox. ```shell # Run tests locally. python setup.py test ``` ```shell # Run multi-version tests locally. tox ``` -------------------------------- ### Install cryptography Source: https://github.com/offu/werobot/blob/master/docs/encryption.rst Installs the 'cryptography' library, which is a dependency for WeRoBot's message encryption feature. This command should be run in your terminal or command prompt. ```bash pip install cryptography ``` -------------------------------- ### Supervisor Configuration for WeRoBot Source: https://github.com/offu/werobot/blob/master/docs/deploy.rst This configuration snippet is for Supervisor, a process control system. It defines how to run a WeRoBot application as a daemon, specifying the command, user, and log file locations. ```bash [program:wechat_robot] command = python /home//robot.py user = redirect_stderr = true stdout_logfile = /home//logs/robot.log stdout_errfile = /home//logs/robot_error.log ``` -------------------------------- ### MusicReply Usage Example Source: https://github.com/offu/werobot/blob/master/docs/replies.rst Demonstrates returning a list of three or four elements to automatically convert into a MusicReply. ```python import werobot robot = werobot.WeRoBot(token='tokenhere') @robot.text def music(message): return [ "title", "description", "music_url", "hq_music_url" ] @robot.text def music2(message): return [ "微信你不懂爱", "龚琳娜最新力作", "http://weixin.com/budongai.mp3", ] robot.run() ``` -------------------------------- ### Handling Menu Clicks Source: https://github.com/offu/werobot/blob/master/docs/start.rst Provides an example of a handler that responds to a custom menu button click. The `@robot.key_click("music")` decorator links the handler to the menu item with the key 'music'. ```python @robot.key_click("music") def music(message): return '你点击了“今日歌曲”按钮' ``` -------------------------------- ### ArticlesReply Usage Example Source: https://github.com/offu/werobot/blob/master/docs/replies.rst Shows how to create an ArticlesReply and add an Article to it, and an alternative method returning a list of articles. ```python from werobot.replies import ArticlesReply, Article 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) ``` ```python import werobot robot = werobot.WeRoBot(token='tokenhere') @robot.text def articles(message): return [ [ "title", "description", "img", "url" ], [ "whtsky", "I wrote WeRoBot", "https://secure.gravatar.com/avatar/0024710771815ef9b74881ab21ba4173?s=420", "http://whouz.com/" ] ] robot.run() ``` -------------------------------- ### Using Session for User State Source: https://github.com/offu/werobot/blob/master/docs/start.rst Shows how to use the Session feature to track user states. This example checks if a user has sent a message before and updates the session accordingly. Session is enabled by default and uses SQLite for storage. ```python @robot.text def first(message, session): if 'first' in session: return '你之前给我发过消息' session['first'] = True return '你之前没给我发过消息' ``` -------------------------------- ### Nginx Reverse Proxy Configuration Source: https://github.com/offu/werobot/blob/master/docs/deploy.rst This Nginx configuration sets up a reverse proxy to forward requests from the public internet (port 80) to a WeRoBot application running on a local port (e.g., 12233). ```nginx server { server_name example.com; listen 80; location / { proxy_pass_header Server; proxy_redirect off; proxy_pass http://127.0.0.1:12233; } } ``` -------------------------------- ### WeRoBot Client Initialization Source: https://github.com/offu/werobot/blob/master/docs/client.rst Demonstrates the initialization of the WeRoBot Client with necessary parameters like token, App ID, and App Secret. ```python from werobot.client import Client client = Client(token='your_token', appid='your_appid', appsecret='your_appsecret') ``` -------------------------------- ### WeRoBot Configuration Initialization and Update Source: https://github.com/offu/werobot/blob/master/docs/config.rst Demonstrates how to initialize WeRoBot with default or custom configurations and how to update configuration settings using dictionary-like operations. ```python from werobot import WeRoBot robot = WeRoBot(token='2333') robot.config.update( HOST='0.0.0.0', PORT=80 ) ``` ```python from werobot.config import Config config = Config( TOKEN="token from config!" ) robot = WeRoBot(config=config, token="token from init") assert robot.token == "token from config!" ``` -------------------------------- ### WeRoBot Error Handling Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Addresses an issue where a 500 error was returned when directly GET accessing the Robot's homepage. ```python # No specific code snippet, this was a bug fix in the framework's routing or request handling. ``` -------------------------------- ### WeChat Backend Configuration for WeRoBot Source: https://github.com/offu/werobot/blob/master/werobot/contrib/error.html Instructions for setting up a WeRoBot application in the WeChat backend. This involves configuring the URL and Token to enable communication between WeChat and the bot. ```text 想要使用本机器人,请在微信后台中将 URL 设置为 {url} 并将 Token 值设置正确。 更多信息请与网站所有者联系 ``` -------------------------------- ### Importing Configuration from Objects and Files Source: https://github.com/offu/werobot/blob/master/docs/config.rst Shows how to load configuration settings into WeRoBot's config object from a Python object or a configuration file. ```python from werobot import WeRoBot robot = WeRoBot(token='2333') class MyConfig(object): HOST = '0.0.0.0' PORT = 80 robot.config.from_object(MyConfig) robot.config.from_pyfile("config.py") ``` -------------------------------- ### Handler Modification for Session Usage Source: https://github.com/offu/werobot/blob/master/docs/session.rst Illustrates how to modify a WeRoBot handler to accept and use the 'session' object. The example increments a counter stored in the session for each message received. ```python @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 ``` -------------------------------- ### werobot.robot.BaseRoBot Initialization and Parameters Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Demonstrates how to initialize the BaseRoBot class, including the ability to pass a configuration object and the implications of doing so. It also mentions deprecated parameters. ```python from werobot.robot import BaseRoBot # Initialize with a config object # If config is provided, BaseRoBot ignores other parameters except 'config' and 'logger' config = { "SESSION_STORAGE": False } robot = BaseRoBot(config=config) # Deprecated parameter example (should be avoided in new code) # robot = BaseRoBot(enable_session=False) ``` -------------------------------- ### werobot Session Storage Options Source: https://github.com/offu/werobot/blob/master/docs/api.rst Documentation for various session storage implementations in werobot, including SQLite, File, MongoDB, Redis, SaeKV, MySQL, and PostgreSQL. These classes manage user session data. ```APIDOC .. module:: werobot.session.sqlitestorage .. autoclass:: SQLiteStorage .. module:: werobot.session.filestorage .. autoclass:: FileStorage .. module:: werobot.session.mongodbstorage .. autoclass:: MongoDBStorage .. module:: werobot.session.redisstorage .. autoclass:: RedisStorage .. module:: werobot.session.saekvstorage .. autoclass:: SaeKVStorage .. module:: werobot.session.mysqlstorage .. autoclass:: MySQLStorage .. module:: werobot.session.postgresqlstorage .. autoclass:: PostgreSQLStorage ``` -------------------------------- ### werobot.client.Client.create_menu: Fix Documentation Error Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Corrects an error found in the documentation for the `create_menu` method of `werobot.client.Client`. ```python def create_menu(self, ...): # ... implementation details ... # Documentation error fixed ``` -------------------------------- ### WeRoBot Integration with Tornado Source: https://github.com/offu/werobot/blob/master/docs/contrib.rst Integrates WeRoBot with a Tornado web application by creating a Tornado RequestHandler using `make_handler`. This allows Tornado to serve WeRoBot requests. ```python import tornado.ioloop import tornado.web from werobot import WeRoBot from werobot.contrib.tornado import make_handler myrobot = WeRoBot(token='token') @myrobot.handler def hello(message): return 'Hello World!' ``` ```tornado application = tornado.web.Application([ (r"/robot/", make_handler(myrobot)), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### werobot.session.saekvstorage.SaeKVDBStorage Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Includes tests for `SaeKVDBStorage`, a session storage solution for SAE (Sina App Engine) Key-Value database. ```python class SaeKVDBStorage: # ... implementation details ... # Tests for SaeKVDBStorage added ``` -------------------------------- ### Creating Custom Menus Source: https://github.com/offu/werobot/blob/master/docs/start.rst This snippet demonstrates how to create a custom menu for a WeChat official account using WeRoBot's client. It requires AppID and AppSecret for authentication and defines a 'click' type button. ```python from werobot import WeRoBot robot = WeRoBot() robot.config["APP_ID"] = "你的 AppID" robot.config["APP_SECRET"] = "你的 AppSecret" client = robot.client client.create_menu({ "button":[{ "type": "click", "name": "今日歌曲", "key": "music" }] }) ``` -------------------------------- ### werobot API Documentation Source: https://github.com/offu/werobot/blob/master/docs/client.rst This section details the werobot API for interacting with the WeChat platform. It covers media retrieval, user tag management (creation, retrieval, update, deletion), and managing user-tag associations, as well as sending template messages. ```APIDOC Client.get_media_list() Retrieves a list of media items. Reference: http://mp.weixin.qq.com/wiki/15/8386c11b7bc4cdd1499c572bfe2e95b3.html User Tag Management: Reference: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837 Client.create_tag(tag_name) Creates a new tag. Parameters: tag_name: The name of the tag to create. Client.get_tags() Retrieves all tags created for the public account. Returns: A list of tags. Client.update_tag(tag_id, new_tag_name) Updates an existing tag. Parameters: tag_id: The ID of the tag to update. new_tag_name: The new name for the tag. Client.delete_tag(tag_id) Deletes a tag. Parameters: tag_id: The ID of the tag to delete. Client.get_users_by_tag(tag_id, next_openid=None) Retrieves a list of users belonging to a specific tag. Parameters: tag_id: The ID of the tag. next_openid: The openid of the next user to fetch (for pagination). Client.tag_users(user_ids, tag_id) Batch assigns a tag to multiple users. Parameters: user_ids: A list of user openids. tag_id: The ID of the tag to assign. Client.untag_users(user_ids, tag_id) Batch removes a tag from multiple users. Parameters: user_ids: A list of user openids. tag_id: The ID of the tag to remove. Client.get_tags_by_user(user_id) Retrieves all tags associated with a specific user. Parameters: user_id: The openid of the user. Returns: A list of tag IDs. Client.send_template_message(message_data) Sends a template message to a user. Parameters: message_data: A dictionary containing the message details. Error Code Explanation: 48001 -- API Unauthorized Meaning: Indicates that the WeChat public account lacks the permission to call the requested API. Resolution: Verify the API permissions configured for your WeChat public account. Reference: https://mp.weixin.qq.com/wiki/13/8d4957b72037e3308a0ca1b21f25ae8d.html ``` -------------------------------- ### WeRoBot Integration with Bottle Source: https://github.com/offu/werobot/blob/master/docs/contrib.rst Integrates WeRoBot with a Bottle application by defining a route for the Bottle app instance. This enables WeRoBot to process incoming requests. ```python from werobot import WeRoBot myrobot = WeRoBot(token='token') @myrobot.handler def hello(message): return 'Hello World!' ``` ```bottle from bottle import Bottle from werobot.contrib.bottle import make_view app = Bottle() app.route('/robot', # WeRoBot 挂载地址 ['GET', 'POST'], make_view(myrobot)) ``` -------------------------------- ### WeRoBot Integration with Django Source: https://github.com/offu/werobot/blob/master/docs/contrib.rst Integrates WeRoBot with a Django project by defining a URL pattern that points to the WeRoBot view. Requires Django 2.2+. ```python from werobot import WeRoBot myrobot = WeRoBot(token='token') @myrobot.handler def hello(message): return 'Hello World!' ``` ```django 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)), ) ``` -------------------------------- ### WeRoBot Smart Args and Friendly 403 Page Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Mentions the use of 'smart args' for more flexible argument handling and the implementation of a user-friendly 403 error page. ```python # Smart args likely refers to improved argument parsing or binding. # Friendly 403 page is a UI/UX improvement. ``` -------------------------------- ### WeRoBot Default Configuration Source: https://github.com/offu/werobot/blob/master/docs/config.rst Lists the default configuration parameters provided by WeRoBot. ```APIDOC dict( TOKEN=None, SERVER="auto", HOST="127.0.0.1", PORT="8888", SESSION_STORAGE=None, APP_ID=None, APP_SECRET=None, ENCODING_AES_KEY=None ) ``` -------------------------------- ### Responding to Custom Menu Clicks (Key Click) Source: https://github.com/offu/werobot/blob/master/docs/handlers.rst Illustrates how to create a handler for a specific custom menu key using the `key_click` decorator. ```python @robot.key_click("abort") def abort(): return "I'm a robot" ``` -------------------------------- ### WeChat API Operations with WeRoBot Client Source: https://github.com/offu/werobot/blob/master/docs/client.rst This section provides API documentation for the WeRoBot Client class, which handles various WeChat API operations. It includes methods for obtaining access tokens, managing custom menus, sending different types of messages, managing users and their groups, and handling media uploads and downloads. ```APIDOC WeRoBot.Client: __init__(token, appid=None, appsecret=None) Initializes the WeRoBot Client. Parameters: token: The WeRoBot token. appid: The WeChat App ID (optional). appsecret: The WeChat App Secret (optional). grant_token(): Obtains an access token from WeChat. Reference: http://mp.weixin.qq.com/wiki/14/9f9c82c1af308e3b14ba9b973f99a8ba.html get_access_token(): Retrieves the current access token. Note: Client operations automatically handle access token acquisition and refresh. Override for specific needs like multi-process deployment. get_ip_list(): Retrieves a list of WeChat server IP addresses. Reference: http://mp.weixin.qq.com/wiki/4/41ef0843d6e108cf6b5649480207561c.html create_menu(menu): Creates a custom menu. Reference: http://mp.weixin.qq.com/wiki/10/0234e39a2025342c17a7d23595c6b40a.html get_menu(): Retrieves the current custom menu configuration. Reference: http://mp.weixin.qq.com/wiki/5/f287d1a5b78a35a8884326312ac3e4ed.html delete_menu(): Deletes the custom menu. Reference: http://mp.weixin.qq.com/wiki/3/de21624f2d0d3dafde085dafaa226743.html create_custom_menu(menu): Creates a personalized menu. Reference: http://mp.weixin.qq.com/wiki/0/c48ccd12b69ae023159b4bfaa7c39c20.html delete_custom_menu(menuid): Deletes a personalized menu. Reference: http://mp.weixin.qq.com/wiki/0/c48ccd12b69ae023159b4bfaa7c39c20.html match_custom_menu(user): Matches a personalized menu for a user. Reference: http://mp.weixin.qq.com/wiki/0/c48ccd12b69ae023159b4bfaa7c39c20.html get_custom_menu_config(): Retrieves the configuration of custom menus. Reference: http://mp.weixin.qq.com/wiki/14/293d0cb8de95e916d1216a33fcb81fd6.html add_custom_service_account(account): Adds a custom service account. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html update_custom_service_account(account): Updates a custom service account. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html delete_custom_service_account(kf_account): Deletes a custom service account. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html upload_custom_service_account_avatar(kf_account, media_file): Uploads an avatar for a custom service account. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html get_custom_service_account_list(): Retrieves the list of custom service accounts. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html get_online_custom_service_account_list(): Retrieves the list of online custom service accounts. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_text_message(target, content): Sends a text message. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_image_message(target, media_id): Sends an image message. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_voice_message(target, media_id): Sends a voice message. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_video_message(target, media_id, title=None, description=None): Sends a video message. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_music_message(target, title, description, musicurl, hqmusicurl, thumb_media_id): Sends a music message. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_article_message(target, articles): Sends an article message. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_news_message(target, articles): Sends a news message. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_miniprogrampage_message(target, title, description, appid, pagepath, thumb_media_id): Sends a mini program page message. Reference: http://mp.weixin.qq.com/wiki/11/c88c270ae8935291626538f9c64bd123.html send_mass_msg(data): Sends a mass message. delete_mass_msg(msgid): Deletes a mass message. send_mass_preview_to_user(data): Sends a mass preview message to a user. get_mass_msg_status(msgid): Retrieves the status of a mass message. get_mass_msg_speed(msgid): Retrieves the speed of a mass message. create_group(name): Creates a user group. Reference: http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html get_groups(): Retrieves all user groups. Reference: http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html get_group_by_id(groupid): Retrieves a user group by its ID. Reference: http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html update_group(groupid, name): Updates a user group. Reference: http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html move_user(groupid, openid): Moves a user to a different group. Reference: http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html move_users(groupid, openids): Moves multiple users to a different group. Reference: http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html delete_group(groupid): Deletes a user group. Reference: http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html remark_user(openid, remark): Sets a remark name for a user. Reference: http://mp.weixin.qq.com/wiki/16/528098c4a6a87b05120a7665c8db0460.html get_user_info(openid): Retrieves basic information for a user. Reference: http://mp.weixin.qq.com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html get_users_info(openids): Retrieves basic information for multiple users. Reference: http://mp.weixin.qq.com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html create_qrcode(action_name, action_info): Creates a QR code with parameters. Reference: http://mp.weixin.qq.com/wiki/18/167e7d94df85d8389df6c94a7a8f78ba.html show_qrcode(ticket): Shows a QR code. Reference: http://mp.weixin.qq.com/wiki/18/167e7d94df85d8389df6c94a7a8f78ba.html get_followers(): Retrieves the list of followers. Reference: http://mp.weixin.qq.com/wiki/12/54773ff6da7b8bdc95b7d2667d84b1d4.html upload_media(media_file, media_type): Uploads temporary media. Reference: http://mp.weixin.qq.com/wiki/15/2d353966323806a202cd2deaafe8e557.html download_media(media_id): Downloads temporary media. Reference: http://mp.weixin.qq.com/wiki/9/677a85e3f3849af35de54bb5516c2521.html add_news(articles): Adds a news article. Reference: http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html upload_news_picture(media_file): Uploads a picture for a news article. Reference: http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html upload_permanent_media(media_file, media_type, description=None): Uploads permanent media. Reference: http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html upload_permanent_video(media_file, title, description): Uploads permanent video media. Reference: http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html download_permanent_media(media_id): Downloads permanent media. Reference: http://mp.weixin.qq.com/wiki/12/3c12fac7c14cb4d0e0d4fe2fbc87b638.html delete_permanent_media(media_id): Deletes permanent media. Reference: http://mp.weixin.qq.com/wiki/7/2212203f4e17253b9aef77dc788f5337.html upload_news(articles): Uploads a news article. Reference: http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html update_news(media_id, articles): Updates a news article. Reference: http://mp.weixin.qq.com/wiki/10/c7bad9a463db20ff8ccefeedeef51f9e.html get_media_count(): Retrieves the total count of media materials. Reference: http://mp.weixin.qq.com/wiki/5/a641fd7b5db7a6a946ebebe2ac166885.html get_media_list(offset=0, count=10): Retrieves a list of media materials. Reference: http://mp.weixin.qq.com/wiki/5/a641fd7b5db7a6a946ebebe2ac166885.html ``` -------------------------------- ### werobot Configuration Object Source: https://github.com/offu/werobot/blob/master/docs/api.rst API documentation for the Config class in werobot, used for managing bot configurations such as tokens, message handlers, and other settings. ```APIDOC .. module:: werobot.config .. autoclass:: Config :members: ``` -------------------------------- ### MusicReply API Documentation Source: https://github.com/offu/werobot/blob/master/docs/replies.rst Defines the parameters for the MusicReply constructor, used for replying with music messages. Also shows an alternative return format. ```APIDOC MusicReply: __init__(target: str, source: str, time: int = None, title: str, description: str, url: str, hq_url: str = None) target: The target user of the message. Usually the robot user. source: The source user of the message. Usually the user sending the message. time: The time the message was sent, a UNIX timestamp. Defaults to the current time. title: The title. description: The description. url: The music link. hq_url: High-quality music link, preferred in WIFI environment. Can be empty. ``` -------------------------------- ### Basic Handler Registration Source: https://github.com/offu/werobot/blob/master/docs/handlers.rst Demonstrates how to register a handler using both the @robot.handler decorator and the add_handler method. Handlers are executed sequentially, and the first handler to return a non-null value determines the reply. ```python import werobot robot = werobot.WeRoBot(token='tokenhere') # 通过修饰符添加handler @robot.handler def echo(message): return 'Hello World!' # 通过`add_handler`添加handler def echo(message): return 'Hello World!' robot.add_handler(echo) ``` -------------------------------- ### WeRoBot CSS Styling Source: https://github.com/offu/werobot/blob/master/werobot/contrib/error.html Provides basic CSS rules for styling the WeRoBot application, including body, link, and image elements. It ensures a consistent and responsive layout. ```css body, html { height: 100%; width: 100%; color: #424242; margin: 0; } body { display: -webkit-flex; display: -moz-flex; display: -ms-flex; display: -o-flex; display: flex; -webkit-flex-direction: column; -moz-flex-direction: column; -ms-flex-direction: column; -o-flex-direction: column; flex-direction: column; -ms-align-items: center; align-items: center; justify-content: center; background-color: #f5f5f5; } a { color: #424242; text-decoration: none; border-bottom: 0; transition: all ease-in-out 0.5s; -webkit-transition: all ease-in-out 0.5s; border-color: #f5f5f5; } a:hover { border-bottom: 1px solid transparent; border-color: #424242; } img { margin-bottom: 1em; height: 300px; width: 300px; } ``` -------------------------------- ### werobot.robot.BaseRoBot: Add 'client' property Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Introduces a `client` property to the `werobot.robot.BaseRoBot` class, providing direct access to the client instance. ```python class BaseRoBot: @property def client(self): # ... return self._client ... # Added 'client' property ``` -------------------------------- ### WeRoBot Framework Integrations Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Lists the web frameworks that WeRoBot now supports for integration, including Django, Flask, Bottle, and Tornado. ```python # Example integration with Flask (conceptual) from flask import Flask from werobot.robot import BaseRoBot app = Flask(__name__) robot = BaseRoBot(token='your_token') @app.route('/wechat', methods=['GET', 'POST']) def wechat_reply(): return robot.run(request.data, request.method, request.headers) ``` -------------------------------- ### WeRoBot Session Storage Implementations Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Introduces new session storage backends, FileStorage (with PyPy compatibility fix) and SQLiteStorage. SQLiteStorage is now the default. ```python from werobot.session import FileStorage, SQLiteStorage # Using FileStorage (compatible with PyPy) file_session = FileStorage('/path/to/session/data') # Using SQLiteStorage (default) sqlite_session = SQLiteStorage('/path/to/session.db') ``` -------------------------------- ### Configuring Custom Session Storage Source: https://github.com/offu/werobot/blob/master/docs/session.rst Shows how to change the default session storage backend to a custom one, like FileStorage, by modifying the SESSION_STORAGE configuration. ```python from werobot import WeRoBot from werobot.session.filestorage import FileStorage robot = WeRoBot(token="token") robot.config['SESSION_STORAGE'] = FileStorage() ``` -------------------------------- ### werobot.client.Client.send_miniprogrampage_message: Support Mini Program Card Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Introduces `send_miniprogrampage_message` to `werobot.client.Client` for sending Mini Program page cards. ```python def send_miniprogrampage_message(self, ...): # ... implementation details ... # Supports sending Mini Program cards ``` -------------------------------- ### WeRoBot API Documentation Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst This section details the various API endpoints and functionalities provided by the WeRoBot library, including client interactions for custom menus, message management, media management, user management, and account management. ```apidoc client: Custom Menu: create_menu(menu): Creates a custom menu. Parameters: menu: A dictionary representing the menu structure. Returns: API response. get_menu(): Retrieves the current custom menu. Returns: API response. delete_menu(): Deletes the custom menu. Returns: API response. Message Management: get_message(msgid): Retrieves a specific message by its ID. Parameters: msgid: The ID of the message. Returns: Message details. get_mass_send_status(msgid): Gets the status of a mass message. Parameters: msgid: The ID of the mass message. Returns: Status details. Media Management: upload_media(media_type, media_file): Uploads media to be used in messages. Parameters: media_type: The type of media (e.g., 'image', 'voice'). media_file: The file object of the media. Returns: Media ID. get_media(media_id): Retrieves media by its ID. Parameters: media_id: The ID of the media. Returns: Media content. User Management: get_user_list(next_openid=None): Retrieves a list of users. Parameters: next_openid: The OpenID to start retrieving from (for pagination). Returns: User list. get_user_info(openid): Retrieves information for a specific user. Parameters: openid: The OpenID of the user. Returns: User information. Account Management: get_account_info(): Retrieves account information. Returns: Account details. Material Management: upload_material(material_type, material_data): Uploads material (e.g., articles, images). Parameters: material_type: The type of material. material_data: The data for the material. Returns: Material ID. get_material(material_id): Retrieves material by its ID. Parameters: material_id: The ID of the material. Returns: Material content. ``` -------------------------------- ### werobot.client.Client.get_media_list: Fix Call Parameters Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Corrects an issue with the call parameters for the `get_media_list` method in `werobot.client.Client`. ```python def get_media_list(self, ...): # ... corrected implementation ... # Fixed incorrect call parameters ``` -------------------------------- ### werobot Logging Utility Source: https://github.com/offu/werobot/blob/master/docs/api.rst API documentation for the enable_pretty_logging function in werobot, used to enable enhanced logging for the bot's operations. ```APIDOC .. module:: werobot.logger .. autofunction:: enable_pretty_logging ``` -------------------------------- ### VideoReply API Documentation Source: https://github.com/offu/werobot/blob/master/docs/replies.rst Defines the parameters for the VideoReply constructor, used for replying with video messages. ```APIDOC VideoReply: __init__(media_id: str, title: str = None, description: str = None, target: str, source: str, time: int = None) media_id: The ID obtained by uploading a multimedia file through the material management interface. title: The title of the video message. Can be empty. description: The description of the video message. Can be empty. target: The target user of the message. Usually the robot user. source: The source user of the message. Usually the user sending the message. time: The time the message was sent, a UNIX timestamp. Defaults to the current time. ``` -------------------------------- ### werobot SubscribeEvent Source: https://github.com/offu/werobot/blob/master/docs/events.rst Handles subscription events, including when a user subscribes to the official account. It may contain a key and ticket if the subscription is initiated by scanning a QR code. ```APIDOC SubscribeEvent: type: 'subscribe_event' key: Event key value. Present only when an unofficial account scans a QR code. ticket: QR code ticket. Present only when an unofficial account scans a QR code. ``` -------------------------------- ### werobot.client.Client: Support Uploading Rich Media Materials Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Enhances the `werobot.client.Client` to support the 'upload rich media materials' functionality, likely for sending images, videos, etc. ```python def upload_material(self, ...): # ... implementation details ... # Supports uploading rich media materials ``` -------------------------------- ### werobot.client.Client.send_music_message: Thumbnail Display Note Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Adds a note to the documentation of `send_music_message` in `werobot.client.Client` regarding potential issues with thumbnail display. ```python def send_music_message(self, ...): # ... implementation details ... # Note: Potential thumbnail display issues may occur. ``` -------------------------------- ### WeRoBot Session and Logging Support (Version 0.4.0) Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Adds session support and logging capabilities to WeRoBot. The testing module was renamed from werobot.test to werobot.testing. Handlers added via @robot.handler now have the lowest priority. ```python from werobot.robot import BaseRoBot # Initialize with session and logging enabled robot = BaseRoBot(token='your_token', enable_session=True, enable_logging=True) # Renamed module # import werobot.testing ``` -------------------------------- ### ArticlesReply API Documentation Source: https://github.com/offu/werobot/blob/master/docs/replies.rst Defines the parameters for the ArticlesReply constructor, used for replying with news messages. Also details the Article class. ```APIDOC ArticlesReply: __init__(content: str = None, target: str, source: str, time: int = None) content: The body of the message. Can be empty. target: The target user of the message. Usually the robot user. source: The source user of the message. Usually the user sending the message. time: The time the message was sent, a UNIX timestamp. Defaults to the current time. add_article(article: Article) Adds an Article object to the ArticlesReply. Article: __init__(title: str, description: str, img: str, url: str) title: The title. description: The description. img: The image link. url: The link to jump to when the image is clicked. ``` -------------------------------- ### WeRoBot run Parameters Source: https://github.com/offu/werobot/blob/master/docs/changelog.rst Details the addition of the 'host' and 'server' parameters to the werobot.run function for more control over the running application. ```python from werobot import run # Example usage: # run(robot, host='0.0.0.0', port=8080, server='werkzeug') ``` -------------------------------- ### User Scan Product Events Source: https://github.com/offu/werobot/blob/master/docs/events.rst Defines events related to user interactions with products via scanning. Includes events for entering a session, asynchronous location updates, and verification actions. ```APIDOC UserScanProductEnterSessionEvent: type: 'user_scan_product_enter_session_event' key_standard: Product code standard. key_str: Product code content. ext_info: Extinfo passed when calling the 'Get Product QR Code Interface', used as an identifier parameter. UserScanProductAsyncEvent: type: 'user_scan_product_async_event' key_standard: Product code standard. key_str: Product code content. ext_info: Extinfo passed when calling the 'Get Product QR Code Interface', used as an identifier parameter. region_code: User's real-time geographical location information (currently only precise to the province level). Refer to http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201504/t20150415_712722.html for corresponding details on the National Bureau of Statistics website. UserScanProductVerifyActionEvent: type: 'user_scan_product_verify_action_event' key_standard: Product code standard. key_str: Product code content. result: Verification result. 'verify_ok' indicates approval, 'verify_not_pass' indicates rejection. reason_msg: Reason for verification failure. ```