WeChat public development method of using message reception
Mar 23, 2017 pm 01:15 PM成成
Because I previously designed a WeChat robot to respond to users’ articles, this app is very simple and does not require particularly in-depth design, and my idea is: use Anyway, there are so many blog systems written in Python on GitHub. I only need to implement the WeChat response part, which is to get the article data from the database, and then package the article title, URL, pictures and other information into xml format. Return to the WeChat server, and the server returns it to the user. And I found that it would be much better to have a menu, like a complete app, where you can directly click to view an article instead of rigidly replying. I used a blog system written by others to transform it - saepy-log. And this blog system is based on the tornado framework. I didn't originally plan to get involved in tornado, but I had to bite the bullet and delve into it. I encountered a lot of difficulties, and I gained a lot in terms of writing like SQL statements and viewing documents.
Deployment and Development
Let me explain in advance that because I have gone through all kinds of troubles, I may not be able to do it according to this article. After downloading the source code of saepy-log and uploading it according to the operations here, you can install the blog system on the sae platform, and then use svn to synchronize the code to the local working directory, and everything is ready.
What we want to modify is that blog.py is the core function of the blog, and model.py is the key to the data model. We are going to extend the data model function to complete our WeChat function.
Add our WeChat function class weixin.py in blog.py (since it uses the tornado framework, the method is slightly different from that in django):
Import the packages that need to be used
# weixin used package import xml.etree.ElementTree as ET import urllib,urllib2,time,hashlib import tornado.wsgi import tornado.escape
Mainly xml parsing and some packages for processing strings. Next we define the main body of the weixin class:
# 添加微信推送帳號 class WeiXinPoster(BaseHandler): #----------------------------------------------------------------------- # 處理get方法 對應check_signature def get(self): global TOKEN signature = self.get_argument("signature") timestamp = self.get_argument("timestamp") nonce = self.get_argument("nonce") echoStr = self.get_argument("echostr") token = TOKEN tmpList = [token,timestamp,nonce] tmpList.sort() tmpstr = "%s%s%s" % tuple(tmpList) tmpstr = hashlib.sha1(tmpstr).hexdigest() if tmpstr == signature: self.write(echoStr) #return echoStr else: self.write(None); #return None # 處理post方法,對應response_msg def post(self): global SORRY # 從request中獲取請求文本 rawStr = self.request.body # 將文本進行解析,得到請求的數(shù)據(jù) msg = self.parse_request_xml(ET.fromstring(rawStr)) # 根據(jù)請求消息來處理內容返回 query_str = msg.get("Content") query_str = tornado.escape.utf8(query_str) # TODO 用戶發(fā)來的數(shù)據(jù)類型可能多樣,所以需要判別 response_msg = "" return_data = "" # 使用簡單的處理邏輯,有待擴展 if query_str[0] == "h": # send help menu to user response_msg = self.get_help_menu() # 返回消息 # 包括post_msg,和對應的 response_msg if response_msg: return_data = self.pack_text_xml(msg, response_msg) else: response_msg = SORRY return_data = self.pack_text_xml(msg, response_msg) self.write(return_data) # 分類 elif query_str[0] =="c": category = query_str[1:] response_msg = self.get_category_articles(category) if response_msg: return_data = self.pack_news_xml(msg, response_msg) else: response_msg = SORRY return_data = self.pack_text_xml(msg, response_msg) self.write(return_data) # 列出文章列表 elif query_str[0] =="l": response_msg = self.get_article_list() if response_msg: return_data = self.pack_text_xml(msg, response_msg) else: response_msg = SORRY return_data = self.pack_text_xml(msg, response_msg) self.write(return_data) # 直接獲取某篇文章 elif query_str[0] == "a": # 直接獲取文章的id,然后在數(shù)據(jù)庫中查詢 article_id = int(query_str[1:]) # 進行操作 response_msg = self.get_response_article_by_id(article_id) if response_msg: return_data = self.pack_news_xml(msg, response_msg) else: response_msg = SORRY return_data = self.pack_text_xml(msg, response_msg) self.write(return_data) # 還要考慮其他 elif query_str[0] == "s": keyword = str(query_str[1:]) # 搜索關鍵詞,返回相關文章 response_msg = self.get_response_article(keyword) # 返回圖文信息 if response_msg: return_data = self.pack_news_xml(msg, response_msg) else: response_msg = SORRY return_data = self.pack_text_xml(msg, response_msg) self.write(return_data) elif query_str[0] == "n": response_msg = self.get_latest_articles() # 返回圖文信息 if response_msg: return_data = self.pack_news_xml(msg, response_msg) else: response_msg = SORRY return_data = self.pack_text_xml(msg, response_msg) self.write(return_data) # 如果找不到,返回幫助信息 else: response_msg = get_help_menu() if response_msg: return_data = response_msg else: return_data = SORRY self.write(return_data) # n for 獲取最新的文章 def get_latest_articles(self): global MAX_ARTICLE global PIC_URL article_list = Article.get_articles_by_latest() article_list_length = len(article_list) count = (article_list_length < MAX_ARTICLE) and article_list_length or MAX_ARTICLE if article_list: # 構造圖文消息 articles_msg = {'articles':[]} for i in range(0,count): article = { 'title': article_list[i].slug, 'description':article_list[i].description, 'picUrl':PIC_URL, 'url':article_list[i].absolute_url } # 插入文章 articles_msg['articles'].append(article) article = {} # 返回文章 return articles_msg #----------------------------------------------------------------------- # 解析請求,拆解到一個字典里 def parse_request_xml(self,root_elem): msg = {} if root_elem.tag == 'xml': for child in root_elem: msg[child.tag] = child.text # 獲得內容 return msg #----------------------------------------------------------------------- def get_help_menu(self): menu_msg = '''歡迎關注南苑隨筆,在這里你能獲得關于校園的資訊和故事?;貜腿缦掳存I則可以完成得到相應的回應 h :幫助(help) l :文章列表(article list) f : 獲得分類列表 n : 獲取最新文章 a + 數(shù)字 :察看某篇文章 a2 察看第2篇文章 s + 關鍵字 : 搜索相關文章 s科研 察看科研相關 c + 分類名 : 獲取分類文章 c校園生活 察看校園生活分類 其他 : 功能有待豐富''' return menu_msg #----------------------------------------------------------------------- # 獲取文章列表 def get_article_list(self): # 查詢數(shù)據(jù)庫獲取文章列表 article_list = Article.get_all_article_list() article_list_str = "最新文章列表供您點閱,回復a+數(shù)字即可閱讀: \n" for i in range(len(article_list)): art_id = str(article_list[i].id) art_id = tornado.escape.native_str(art_id) art_title = article_list[i].title art_title = tornado.escape.native_str(art_title) art_category = article_list[i].category art_category = tornado.escape.native_str(art_category) article_list_str += art_id + ' ' + art_title + ' ' + art_category + '\n' return article_list_str # 按照分類查找 def get_category_articles(self, category): global MAX_ARTICLE global PIC_URL article_list = Article.get_articles_by_category(category) article_list_length = len(article_list) count = (article_list_length < MAX_ARTICLE) and article_list_length or MAX_ARTICLE if article_list: # 構造圖文消息 articles_msg = {'articles':[]} for i in range(0,count): article = { 'title': article_list[i].slug, 'description':article_list[i].description, 'picUrl':PIC_URL, 'url':article_list[i].absolute_url } # 插入文章 articles_msg['articles'].append(article) article = {} # 返回文章 return articles_msg #----------------------------------------------------------------------- # 獲取用于返回的msg def get_response_article(self, keyword): global PIC_URL keyword = str(keyword) # 從數(shù)據(jù)庫查詢得到若干文章 article = Article.get_article_by_keyword(keyword) # 這里先用測試數(shù)據(jù) if article: title = article.slug description = article.description picUrl = PIC_URL url = article.absolute_url count = 1 # 也有可能是若干篇 # 這里實現(xiàn)相關邏輯,從數(shù)據(jù)庫中獲取內容 # 構造圖文消息 articles_msg = {'articles':[]} for i in range(0,count): article = { 'title':title, 'description':description, 'picUrl':picUrl, 'url':url } # 插入文章 articles_msg['articles'].append(article) article = {} # 返回文章 return articles_msg else: return def get_response_article_by_id(self, post_id): global PIC_URL # 從數(shù)據(jù)庫查詢得到若干文章 article = Article.get_article_by_id_detail(post_id) # postId為文章id if article: title = article.slug description = article.description picUrl = PIC_URL url = article.absolute_url count = 1 # 這里實現(xiàn)相關邏輯,從數(shù)據(jù)庫中獲取內容 # 構造圖文消息 articles_msg = {'articles':[]} for i in range(0,count): article = { 'title':title, 'description':description, 'picUrl':picUrl, 'url':url } # 插入文章 articles_msg['articles'].append(article) article = {} # 返回文章 return articles_msg else: return
It can be seen that the difficulty of the app is not great, and it is still the same as the last time I used WeChat In the API, several global variables that need to be used need to be defined by yourself, such as token, PIC_URL, etc. The principle of the program is actually to parse user requests. If it starts with h, it will provide a help menu. If it starts with a number, it will provide a certain article, etc., and then provide corresponding functions for processing. The explanation here is more complicated, so just get the classification Let’s talk about the article:
You need to analyze the user request string:
# 分類 elif query_str[0] =="c": category = query_str[1:] response_msg = self.get_category_articles(category) if response_msg: return_data = self.pack_news_xml(msg, response_msg) else: response_msg = SORRY return_data = self.pack_text_xml(msg, response_msg) self.write(return_data)
The function of get_category_articles(category) needs to be provided here, so you need to implement such a function in the weixin class:
# 按照分類查找 def get_category_articles(self, category): global MAX_ARTICLE global PIC_URL article_list = Article.get_articles_by_category(category) article_list_length = len(article_list) count = (article_list_length < MAX_ARTICLE) and article_list_length or MAX_ARTICLE if article_list: # 構造圖文消息 articles_msg = {'articles':[]} for i in range(0,count): article = { 'title': article_list[i].slug, 'description':article_list[i].description, 'picUrl':PIC_URL, 'url':article_list[i].absolute_url } # 插入文章 articles_msg['articles'].append(article) article = {} # 返回文章 return articles_msg
Obviously, we need to deal with the database model Article here to see if Article implements this function. Unfortunately, it does not, so we have to roll up our sleeves and do it ourselves - extend Article, so we move to model.py In the file, I wrote the following code:
# 返回一個包含若干篇文章的數(shù)組 limit 5 def get_articles_by_category(self, category): sdb._ensure_connected() article_list = sdb.query('SELECT * FROM `sp_posts` WHERE `category` = %s LIMIT 5', str(category)) for i in range(len(article_list)): article_list[i] = post_detail_formate(article_list[i]) return article_list
Here, a database query is performed, the category parameter is passed in, 5 articles with category as the parameter are selected, and the package is returned. post_detail_formate is already written in the blog system, we just need to use it. In Python, you must be very careful when writing SQL statements. When you encounter parameters that need to be passed in, it is best to separate them with commas instead of using % to fill the parameters. Especially when using like, we often need to write such sql statements:
SELECT * FROM `sp_posts` WHERE `category` LIKE '%study%'
But it is used in python %s is used as a parameter placeholder, so it will cause many unnecessary errors, such as here. In short, to use them safely, it is best to pass them as parameters. Python will separate them from the % in the original string.
The above is the detailed content of WeChat public development method of using message reception. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform
