Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to develop Wechat Public platform

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use Python to develop Wechat public platform". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Python to develop Wechat public platform".

Implementation principle of automatic reply

First of all, what kind of mechanism can realize the automatic reply function of Wechat? (not an automatic reply from Wechat system) the principle is that Wechat platform sends the text entered by the user to the cloud platform, then the program running on the cloud platform captures this text message and return a result, and then the cloud platform returns the result to Wechat platform. Finally, the Wechat platform presents the returned results to the users. Show it with a picture:

Wechat developer Mode and SAE setting

I will try my best to be more detailed in this section. If there is anything unclear, you can trust me privately.

First of all, we need two major platforms to support:

Wechat public platform; this application is relatively simple. As long as you have a mailbox, you can apply for a personal version of Subscription account for free. I won't repeat it.

Cloud computing platform; the SAE I use here (Sina didn't charge for it last year, but it starts to charge this year, with a minimum of 10 cents a day for simple code hosting). You can also use Tencent Cloud.

Specific steps:

The application for the official account of Wechat.

As long as you have a mailbox, you can apply for a personal version of Subscription account for free. I won't repeat it.

Application and setup of SAE

After registering to log in to SAE, select SAE

To create a new project, SAE only supports Python2.7,Python3 and cannot be used for the time being.

If the project is small, it is recommended to fill in SVN because it can be edited online. If the project is large, Git it. SVN is chosen here.

Create the first version

You can start editing ~

Write config.yaml and index.wsgi files.

WSGI is the PythonWeb server gateway interface (PythonWeb Server Gateway Interface). We are using the web.py framework. More powerful frameworks of the same type are Django,Flask and so on. Why web.py is chosen because it is lightweight and has good xml parsing capabilities. By the way, AaronH, the developer of web.py. Swartz was a complete genius, but he died young. There is a documentary about him, recommended to see: the son of the Internet.

All right, let's get down to business. Let's write config.yaml first.

Name: pifuhandashu version: 1 libraries:-name: webpy version: "0.36"-name: lxml version: "2.3.4".

Here we introduce the web.py framework and the lxml module, and then we write the index.wsgi file.

# coding: utf-8 import os import sae import web from weixinInterface import WeixinInterface urls = ('/ weixin','WeixinInterface') app_root = os.path.dirname (_ _ file__) templates_root = os.path.join (app_root, 'templates') render = web.template.render (templates_root) app = web.application (urls, globals ()). Wsgifunc () application = sae.create_wsgi_app (app)

Here is the simple knowledge that python uses web.py web page development. Set up the root directory, template directory, / weixin routing, open the application.

To make the page look cleaner, we created a new py file, weixinInterface.py (weixinInterface.py and index.wsgi are in the same level directory, see the screenshot below).

Edit weixinInterface.py, be sure to read the case clearly, otherwise it is easy to make mistakes. Be careful to fill in an exclusive token, which will be useful in the official account setting of Wechat later.

#-*-coding: utf-8-*-import hashlib import web import lxml import time import os import urllib2,json from lxml import etree class WeixinInterface: def _ _ init__ (self): self.app_root = os.path.dirname (_ _ file__) self.templates_root = os.path.join (self.app_root 'templates') self.render = web.template.render (self.templates_root) def GET (self): # get the input parameter data = web.input () signature = data.signature timestamp = data.timestamp nonce = data.nonce echostr = data.echostr # own token token = "XXXXXXXXXXX" # Note: enter the tokenboxes entered in the Wechat public platform! # Dictionary sort list = [token, timestamp, nonce] list.sort () sha1 = hashlib.sha1 () map (sha1.update,list) hashcode = sha1.hexdigest () # sha1 encryption algorithm # if it is a request from Wechat, reply echostr if hashcode = = signature: return echostr

The code outlines that def _ _ init__ (self) tells us where the template file is loaded. Def GET (self) is a token verification conducted at the request of Wechat public platform. The verification here uses the hash algorithm. For more information, please see Wechat official API access instruction: Wechat Public platform access Guide. There is an example of php. This paper uses python implementation.

Wechat developer mode settings

Basic settings

Modify configuration

URL must fill in carefully and check carefully.

For example, check the url application information:

Token fill in the token you just filled in in Sina SAE. It must be consistent. EncodingAESKey can be generated randomly. Click submit when you are finished. If prompted "submit successfully". Congratulations, the most critical step has been completed. This stage may take a long time. When you are finished, be sure to enable developer mode! Remember!

Implementation of Wechat Robot

After the last step is completed, we can do some interesting things: Wechat robot. Before that, however, there is one small step to complete: the creation of the template. Because Wechat development is in the form of xml. In order to first achieve automatic reply in text form (in the form of reply audio, picture and text messages, etc.), first create a new template folder templates, and then create a reply_text.xml file under the templates folder (see the screenshot below where the files are placed). As shown in the passive response to the Wechat message, fill in the following code:

$def with (toUser,fromUser,createTime,content) $createTime $content

Then, write the POST function after def GET (self) in weixinInterface.py. This function is used to get the user's ID, the type of message sent, the time it was sent, and so on. Determine the type of message the user sends. If it is plain text, if mstype = = 'text', then you can proceed to the next step.

Def POST (self): str_xml = web.data () # get the data from post xml = etree.fromstring (str_xml) # do XML parsing mstype = xml.find ("MsgType") .text # message type fromUser = xml.find ("FromUserName"). Text toUser = xml.find ("ToUserName"). Text

In order to achieve the Wechat robot, we need to achieve automatic reply to the content. There are two ways.

Crawl the content of the reply from the robot on the Internet, for example, if I can't find the interface of the little yellow chicken, I will crawl its reply result by myself.

Call the robot API that can reply automatically.

Here I choose the second method, which uses the API of the Turing robot. This method is convenient and fast, and generally will not be covered by the wall. But the degree of freedom is not high and the extensibility is poor.

Sign up for Turing Robot account, pay attention to using Turing's web page api, not authorized. Get the key replied by the Turing robot. The Wechat robot can reply automatically in a few lines of code.

Source code display

Index.wsgi source code

# coding: utf-8 import os import sae import web from weixinInterface import WeixinInterface urls = ('/ weixin','WeixinInterface',) app_root = os.path.dirname (_ _ file__) templates_root = os.path.join (app_root, 'templates') render = web.template.render (templates_root) app = web.application (urls, globals ()). Wsgifunc () application = sae.create_wsgi_app (app)

Config.yaml source code

Name: myzhihu version: 1 libraries:-name: webpy version: "0.36"-name: lxml version: "2.3.4".

Reply_text.xml source code under templates

$def with (toUser,fromUser,createTime,content) $createTime $content

WeixinInterface.py source code

#-*-coding: utf-8-*-import hashlib import web import lxml import time import os import json import urllib from lxml import etree class WeixinInterface: def _ _ init__ (self): self.app_root = os.path.dirname (_ _ file__) self.templates_root = os.path.join (self.app_root 'templates') self.render = web.template.render (self.templates_root) def GET (self): # get the input parameter data = web.input () signature=data.signature timestamp=data.timestamp nonce=data.nonce echostr=data.echostr # your own token token= "#" # here fill in the token # dictionary sort list= entered in the public platform of Wechat [token,timestamp Nonce] list.sort () sha1=hashlib.sha1 () map (sha1.update,list) hashcode=sha1.hexdigest () # sha1 encryption algorithm # if it is a request from Wechat Then reply echostr if hashcode = = signature: return echostr def POST (self): str_xml = web.data () # to get the data from post xml = etree.fromstring (str_xml) # for XML parsing mstype = xml.find ("MsgType"). Text fromUser = xml.find ("FromUserName"). Text toUser = xml.find ("ToUserName"). Text if mstype = 'text': content = xml.find ("Content") .text # to get the input by the user Incoming content key ='#'# key api = 'http://www.tuling123.com/openapi/api?key=' + key +' & info=' info= content.encode ('UTF-8') url = api + info page = urllib.urlopen (url) html = page.read () dic_json = json.loads (html) reply_content = Dic_json ['text'] return self.render.reply_text (fromUser ToUser,int (time.time ()), reply_content) Thank you for your reading The above is the content of "how to use Python to develop Wechat public platform". After the study of this article, I believe you have a deeper understanding of how to use Python to develop Wechat public platform, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report