There are actually many things you don’t know about WeChat. Python WeChat platform development and writing records

There are actually many things you don’t know about WeChat. Python WeChat platform development and writing records

This article mainly describes how to use Python to develop the WeChat public platform.

Note: If you are a Python novice or a web crawler novice, and find the code in this course obscure and difficult to understand, it doesn't matter. You don't need to understand it. Just follow the steps step by step. In this section, we mainly build a framework, and there is almost no real web crawler code. You may only use these codes and operations once in your life. In the next section, we will talk about how to expand our web crawler program based on this framework.

Required Action:

  • Application for WeChat public account.
  • Obtaining WeChat interface, setting SAE, etc.
  • Simple Python crawler code writing

Knowledge points to master:

  • Understand the connection between WeChat public accounts and cloud computing platforms and clarify their operating mechanisms.
  • Understand the concept of web.py and the mechanism of wsgi.
  • Understand simple python crawler knowledge, json parsing, API calls, and urllib library functions.

How automatic reply works

First, let's understand what kind of mechanism can realize the automatic reply function of WeChat? (Not the automatic reply of the WeChat system) The principle is that the WeChat platform sends the text entered by the user to the cloud platform, and then the program running on the cloud platform captures this text information and returns a result, and then the cloud platform returns the result to the WeChat platform. Finally, the WeChat platform displays the returned result to the user. Let's use a picture to show it:

WeChat developer mode and SAE settings

I will try to explain this section in detail. If there is still something unclear, you can send me a private message.

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

  • WeChat public platform; this application is relatively simple. As long as you have an email address, you can apply for a personal subscription account for free. No more details.
  • Cloud computing platform; I use SAE here (Sina didn’t charge any fees last year, which was a rip-off. They started charging this year, and the minimum price for simple code hosting is 0.1 cent per day), or you can use Tencent Cloud.

Specific steps:

Application for WeChat public account.

As long as you have an email address, you can apply for a personal subscription account for free. No more details.

Application and setup of SAE

After registering and logging in to SAE, select SAE

Create a new project. SAE currently only supports Python 2.7, and Python 3 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, then Git is the best choice. Here, SVN is selected.

Creating the first version

You can start editing now~

Write config.yaml and index.wsgi files.

WSGI is Python Web Server Gateway Interface. We use the web.py framework. Other powerful frameworks of the same type include Django, Flask, etc. Why choose web.py? Because it is lightweight and has good XML parsing capabilities. As an aside, the developer of web.py, Aaron H. Swartz, was a genius, but unfortunately died young. There is a documentary about him that I recommend watching: The Internet's Son.

Okay, let's get back to the topic. Let's first write config.yaml

  1. name : pifuhandashu
  2. version: 1
  3. libraries:
  4. - name : webpy
  5. version: "0.36"  
  6. - name : lxml
  7. version: "2.3.4"  
  8. ...

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

  1. # coding: utf-8
  2. import os
  3. import sae
  4. import web
  5. from weixinInterface import WeixinInterface
  6. urls = ( '/weixin' , 'WeixinInterface' )
  7. app_root = os.path.dirname(__file__)
  8. templates_root = os.path.join (app_root, 'templates' )
  9. render = web.template.render(templates_root)
  10. app = web.application(urls, globals()).wsgifunc()
  11. application = sae.create_wsgi_app(app)

Here is some simple knowledge of Python web development using web.py. Set up the root directory, template directory, /weixin route, and start the application.

In order to make the page look neater, we created a new py file weixinInterface.py (weixinInterface.py and index.wsgi are in the same directory, see the screenshot below).

  • Edit weixinInterface.py. Be sure to read the capitalization carefully, otherwise it is easy to make mistakes. Remember to fill in a unique token, which will be used in the WeChat public account settings later.
  1. # -*- coding: utf-8 -*-
  2. import hashlib
  3. import web
  4. import lxml
  5. import time  
  6. import os
  7. import urllib2,json
  8. from lxml import etree
  9. class WeixinInterface:
  10. def __init__(self):
  11. self.app_root = os.path.dirname(__file__)
  12. self.templates_root = os.path.join (self.app_root, 'templates' )
  13. self.render = web.template.render(self.templates_root)
  14. def GET(self):
  15. #Get input parameters
  16. data = web.input()
  17. signature = data.signature
  18. timestamp = data.timestamp  
  19. nonce = data.nonce
  20. echostr = data.echostr
  21. #Own token
  22. token = "XXXXXXXXXXX" #Note: Fill in the token entered in the WeChat public platform later! ! !
  23. # Lexicographic sorting
  24. list = [token, timestamp , nonce]
  25. list.sort()
  26. sha1 = hashlib.sha1()
  27. map( sha1.update ,list)
  28. hashcode = sha1.hexdigest()
  29. #sha1 encryption algorithm
  30. #If it is a request from WeChat, reply echostr
  31. if hashcode == signature:
  32. return echostr

Let's briefly explain the code. def __init__(self) tells us where the template file is loaded. def GET(self) is a token verification required by the WeChat public platform. The verification here uses a hash algorithm. For details, please refer to the official WeChat interface access instructions: WeChat public platform access guide. There is a PHP example in it. This article uses Python implementation.

WeChat developer mode settings

Basic Settings


Modify the configuration

The URL must be filled in carefully and checked carefully.

For example, view url application information:

Token must be the same as the one you just filled in Sina SAE. EncodingAESKey can be randomly generated. After filling in, click Submit. If it prompts "Submission successful". Congratulations, the most critical step has been completed. This stage may take a long time. After completion, be sure to enable the developer mode!!!! Remember!!!

WeChat robot implementation

After the previous step is completed, we can do something interesting: WeChat robot. But before that, there is still a small step to complete: template creation. Since WeChat development is in the form of XML. In order to realize automatic reply in text form first (later you can realize reply in the form of audio, text and pictures, etc.), first create a new template folder templates, and then create a reply_text.xml file in the templates folder (see the screenshot below for the file location). According to the passive reply of WeChat message, fill in the following code:

  1. $def with (toUser,fromUser,createTime,content)
  2. <xml>
  3. <ToUserName><![CDATA[$toUser]]></ToUserName>
  4. <FromUserName><![CDATA[$fromUser]]></FromUserName>
  5. <CreateTime>$createTime</CreateTime>
  6. <MsgType><![CDATA[text]]></MsgType>
  7. <Content>$content</Content>
  8. </xml>

Then, write the POST function after def GET(self) in weixinInterface.py. This function is used to obtain the user's ID, the type of message sent, the time of sending, etc. Determine the type of message sent by the user. If it is a plain text type, if mstype == 'text', then you can proceed to the next step.

  1. def POST(self):
  2. str_xml = web.data() #Get the data from post
  3. xml = etree.fromstring(str_xml)# XML parsing
  4. mstype = xml.find( "MsgType" ).text#Message type
  5. fromUser = xml.find( "FromUserName" ).text
  6. toUser = xml.find( "ToUserName" ).text

In order to implement WeChat robot, we need to implement automatic reply content. There are two ways to do this.

  • Crawl the content of the robot replies on the Internet. For example, if I can’t find the interface of the little yellow chicken, I will crawl its reply results with my own crawler.
  • Call the robot API that can automatically reply.

Here I choose the second method, which uses the Turing Robot API. This method is convenient and fast, and is generally not blocked. However, it has low freedom and poor scalability.

Register a Turing robot account. Note that you should use Turing's web API instead of authorization. Get the key for Turing robot replies. You can get automatic replies from WeChat robots with just a few lines of code~

Source code display

index.wsgi source code

  1. # coding: utf-8
  2. import os
  3. import sae
  4. import web
  5. from weixinInterface import WeixinInterface
  6. urls = (
  7. '/weixin' , 'WeixinInterface' ,
  8. )
  9. app_root = os.path.dirname(__file__)
  10. templates_root = os.path.join (app_root, 'templates' )
  11. render = web.template.render(templates_root)
  12. app = web.application(urls, globals()).wsgifunc()
  13. application = sae.create_wsgi_app(app)

config.yaml source code

  1. name : myzhihu
  2. version: 1
  3. libraries:
  4. - name : webpy
  5. version: "0.36"  
  6. - name : lxml
  7. version: "2.3.4"  
  8. ...

reply_text.xml source code under templates

  1. $def with (toUser,fromUser,createTime,content)
  2. <xml>
  3. <ToUserName><![CDATA[$toUser]]></ToUserName>
  4. <FromUserName><![CDATA[$fromUser]]></FromUserName>
  5. <CreateTime>$createTime</CreateTime>
  6. <MsgType><![CDATA[text]]></MsgType>
  7. <Content>$content</Content>
  8. </xml>

weixinInterface.py source code

  1. # -*- coding: utf-8 -*-
  2. import hashlib
  3. import web
  4. import lxml
  5. import time  
  6. import os
  7. import json
  8. import urllib
  9. from lxml import etree
  10. class WeixinInterface:
  11. def __init__(self):
  12. self.app_root = os.path.dirname(__file__)
  13. self.templates_root = os.path.join (self.app_root, 'templates' )
  14. self.render = web.template.render(self.templates_root)
  15. def GET(self):
  16. #Get input parameters
  17. data = web.input()
  18. signature=data.signature
  19. timestamp = data.timestamp  
  20. nonce=data.nonce
  21. echostr=data.echostr
  22. #Own token
  23. token = "#################" #Fill in the token entered in the WeChat public platform
  24. # Lexicographic sorting
  25. list=[token, timestamp ,nonce]
  26. list.sort()
  27. sha1 = hashlib.sha1()
  28. map( sha1.update ,list)
  29. hashcode = sha1.hexdigest()
  30. #sha1 encryption algorithm
  31. #If it is a request from WeChat, reply echostr
  32. if hashcode == signature:
  33. return echostr
  34.   
  35. def POST(self):
  36. str_xml = web.data() #Get the data from post
  37. xml = etree.fromstring(str_xml)# XML parsing
  38. mstype = xml.find( "MsgType" ).text
  39. fromUser = xml.find( "FromUserName" ).text
  40. toUser = xml.find( "ToUserName" ).text
  41.   
  42. if mstype == 'text' :
  43. content = xml.find( "Content" ).text#Get the content entered by the user
  44. key = '######################' ###Turing robot's key   
  45. api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='   
  46. info = content.encode( 'UTF-8' )
  47. url = api + info
  48. page = urllib.urlopen(url)
  49. html = page.read ()
  50. dic_json = json.loads(html)
  51. reply_content = dic_json[ 'text' ]
  52. return self.render.reply_text(fromUser,toUser, int ( time . time ()),reply_content)

Postscript

This tutorial uses Python to develop a WeChat public platform that can automatically reply to user input text. It includes the settings of the WeChat public platform, the settings of SAE, and the writing of related codes.

<<:  It’s 2020 now. Which is better, fingerprint recognition or facial recognition?

>>:  What does Android unified push bring to users? No messages will be missed, power consumption is significantly reduced

Recommend

Case analysis of information flow promotion in the automotive industry

As an information flow person in the automotive i...

How should marketing campaigns be designed?

The purpose of marketing activities is mainly to ...

I think this is a good way for Alipay to do it!

Our classmates at Alibaba have always had a hat o...

A Brief Discussion on iOS Crash (Part 2)

A Brief Discussion on iOS Crash (Part 1) 1. Zombi...

A brief discussion on iOS screen adaptation practice

Screen adaptation in front-end development is act...

Qualcomm and Huawei are increasingly competing for the first 5G chip

Qualcomm, which was overshadowed by Huawei's ...

Can eating dark chocolate help you lose weight? Why not do these 4 things!

Author: Xue Qingxin, registered dietitian Reviewe...