Python development-quickly build the function of auto-Reply to WeChat official account, and python auto-reply

Source: Internet
Author: User

Python development-quickly set up the function of auto-Reply to public accounts, and python auto-reply

In a previous article, Python used AIML and Tornado to set up a chatbot subscription number and used aiml to implement a simple English chatbot subscription number. However, only English messages can be processed. Now we use the Turing robot to implement a Chinese chatbot subscription number.

This section describes how to use the Tornado Web framework of Python and the python development kit of the wechat-Python-sdk public platform to quickly build a public account.

The complete public code GitHub address: green. As some features of this public Code are currently under development, the complete code will be different from the code described below, however, the auto-reply function is retained.

The public number set up in this article is Ms_haoqi. You can scan the QR code to check the effect.

Automatic response:

Install Python Library

Install wechat-python-sdk, Requests, and Tornado Through pip

pip install tornadopip install wechat-sdkpip install requests

Subscription number Application

To set up a subscription number, you must first register it on the official website of the public platform.

Currently, individual users can apply for a subscription number for free. Although many permissions cannot be applied for, there is no problem with basic message reply.

Server access

For detailed access steps, refer to the access guide on the official website.

The subscription number is configured as follows:

The URL in the configuration provides the backend url path of the subscription number for the server. The source code used in this article is http: // server_ip/wx, where server_ip is the public IP address of the host running the source code.

Token can be set to any string.

EncodingAESKey can be randomly generated.

The message encryption mode can be set to a simple plaintext mode.

The key code for receiving and processing access requests sent by the server is a Handle, wx. py of Tornado:

Import tornado. escapeimport tornado. webfrom wechat_sdk import WechatConfconf = WechatConf (token = 'your _ token', # your public account Tokenappid = 'your _ appid ', # your public account AppIDappsecret = 'your _ appsecret', # your public account AppSecretencrypt_mode = 'safe ', # option: normal/compatible/safe, corresponding to plaintext/compatible/security mode, respectively, encoding_aes_key = 'your _ encoding_aes_key '# if this value is input, you must ensure that both the token and appid are input) from wechat_sdk import WechatBasicwechat = WechatBasic Nf) class WX (tornado. web. requestHandler): def get (self): signature = self. get_argument ('signature', 'default') timestamp = self. get_argument ('timestamp', 'default') nonce = self. get_argument ('nonce ', 'default') echostr = self. get_argument ('echo str', 'default') if signature! = 'Default' and timestamp! = 'Default' and nonce! = 'Default' and echostr! = 'Default' \ and wechat. check_signature (signature, timestamp, nonce): self. write (echostr) else: self. write ('not open ')

The purpose of this Code is to verify that an echostr message is returned directly from the official server.

Start the main. py code in the background:

import tornado.webimport tornado.httpserverfrom tornado.options import define, optionssettings = {'static_path': os.path.join(os.path.dirname(__file__), 'static'),'template_path': os.path.join(os.path.dirname(__file__), 'view'),'cookie_secret': 'e440769943b4e8442f09de341f3fea28462d2341f483a0ed9a3d5d3859f==78d','login_url': '/','session_secret': "3cdcb1f07693b6e75ab50b466a40b9977db123440c28307f428b25e2231f1bcc",'session_timeout': 3600,'port': 5601,'wx_token': 'weixin',}web_handlers = [(r'/wx', wx.WX),]define("port", default=settings['port'], help="run on the given port", type=int)if __name__ == '__main__':app = tornado.web.Application(web_handlers, **settings)tornado.options.parse_command_line()http_server = tornado.httpserver.HTTPServer(app)http_server.listen(options.port)tornado.ioloop.IOLoop.instance().start()

After the source code is configured, run the program. After confirming the operation is correct, click submit on the public account setting page. If the program runs normally, the access is successful.

Access Turing Robot

To access the Turing robot, you must first apply for an API Key on the official website.

After application, you can use the following code to encapsulate an automatic reply interface:

# -*- coding: utf-8 -*-import jsonimport requestsimport tracebackclass TulingAutoReply:def __init__(self, tuling_key, tuling_url):self.key = tuling_keyself.url = tuling_urldef reply(self, unicode_str):body = {'key': self.key, 'info': unicode_str.encode('utf-8')}r = requests.post(self.url, data=body)r.encoding = 'utf-8'resp = r.textif resp is None or len(resp) == 0:return Nonetry:js = json.loads(resp)if js['code'] == 100000:return js['text'].replace('<br>', '\n')elif js['code'] == 200000:return js['url']else:return Noneexcept Exception:traceback.print_exc()return None

Write the automatic response code for the Public Account

With the wechat-python-sdk public platform Python Development Kit, you can easily process all messages of the public account.

The following is the Tornado Handler object that processes the public account message from the official server (this code will get the user message received by the Public Account and call the self-Signed Turing robot API to automatically reply) wx. py code:

#-*-Coding: UTF-8-*-import tornado. escapeimport tornado. webauto_reply = TulingAutoReply (key, url) # enter the Turing key and url you have applied for and the urlclass WX (tornado. web. requestHandler): def wx_proc_msg (self, body): try: wechat. parse_data (body) failed t ParseError: print 'invalid Body text' returnif isinstance (wechat. message, TextMessage): # The message is text message content = wechat. message. contentreply = auto_reply.reply (content) if reply I S not None: return wechat. response_text (content = reply) else: return wechat. response_text (content = u "Don't know what you are talking about") return wechat. response_text (content = U' knows ') def post (self): signature = self. get_argument ('signature', 'default') timestamp = self. get_argument ('timestamp', 'default') nonce = self. get_argument ('nonce ', 'default') if signature! = 'Default' and timestamp! = 'Default' and nonce! = 'Default' \ and wechat. check_signature (signature, timestamp, nonce): body = self. request. body. decode ('utf-8') try: result = self. wx_proc_msg (body) if result is not None: self. write (result) handle T IOError, e: return

I would like to introduce so much about the function of setting up an automatic public account for Python development. I hope it will be helpful to you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.