Python WXPY implements the WeChat monitoring and alarm function code, pythonwxpy

Source: Internet
Author: User

Python WXPY implements the monitoring and alarm function code, pythonwxpy

Overview:

This article mainly shares a small program developed by the blogger while learning wxpy. The blogger recently had a need to complete monitoring and alarms, and was learning wxpy, so he skillfully linked his work and learning.

The main technologies used in this blog are Python, Redis, and Java. Many technologies are involved, but the main language is developed based on Python.

The architecture involves the use of producer and consumer models, and the use of Redis as a message queue for decoupling operations.

The main architecture involves the following:

  

Next we will introduce the implementation process of the program, mainly to explain wxpy-> python. redis-> Java. redis

1. Initial Wxpy experience

The python version used by the project is 3.5, so the syntax will be different from the 2.x version. wxpy supports python 3.6-And python2.7 versions, so you don't have to worry too much about python version.

1.1 install wxpy

By default, you have installed pip. We need to install wxpy and wechat_sender packages. We recommend that you use the Chinese Douban source. If your network speed is high, ignore it ....

pip install wxpy -i "https://pypi.doubanio.com/simple/"pip install wechat_sender -i "https://pypi.doubanio.com/simple/" 

1.2 wxpy Login

Wxpy is very easy to use. We only need to create a bot object. After the program runs, a QR code will pop up. After scanning the QR code, the login is successful.

The following code will send "hello world!" To our file transfer assistant after login !". (Each program requires a hello world)

from wxpy import *bot = Bot()bot.file_helper.send('hello world!')print("ending")

For descriptions of relevant parameters of the Bot () object, we can see in the comments in the source code:

: Param cache_path:
* Set the cache path for the current session and enable the cache function. If it is set to 'None' (default), the cache function is not enabled.
* After the cache is enabled, you can avoid repeated code scanning within a short period of time. If the cache fails, you will be requested to log on again.
* When set to 'true', use the default cache path 'wxpy. pkl '.

: Param console_qr:
* The login QR code is displayed on the terminal. You need to install the pillow module ('pip3 install pillow ').
* It can be an integer (int), indicating the width of the Two-dimensional code cell, usually 2 (when set to 'true', it will also be considered as 2 internally ).
* It can also be a negative number, indicating that the two-dimensional code is displayed in Reversed colors. It is applicable to the command line interface with simple words.
* For example, in most Linux systems, it can be set to 'true' or 2, and in the default white background color of macOS Terminal, it should be set to-2.

: Param qr_path: path for saving the QR code

: Param qr_callback: the callback after obtaining the QR code. It can be used to define the processing method of the QR code. The receiving parameters include uuid, status, and qrcode.

: Param login_callback: callback after successful login. If this parameter is not specified, the screen is cleared and the QR code file is deleted.

: Param logout_callback: callback for logout

Here we will introduce two main parameters used:

  • Cache_path: it can be set to True during the development process to avoid re-scanning every login, which has the function of caching.
  • Qr_path: used to save the QR code to generate images. It mainly solves the problem of inconvenient display of images on the server.

1.3 wxpy friends and chat groups

As shown in the code, we can use the Bot. friends and Bot. group to get all friends and chat groups. Note that the chat group must be saved to the address book. Otherwise, the chat group may not be found.

In the search method, you can provide the following parameters: name, city, province, sex, and other variables.

For more information about friend API documentation, see --- friend API

From wxpy import * bot = Bot () # Get all friends = bot. friends () # traverse the output friend name for friend in friends: print (friend) # Find friend = bot. friends. search ('waybill ') [0] print (friend) friend. send ("hello world! ") # Obtain all chat groups = bot. groups () for group in groups: print (group) # Find the target group = groups. search ("409") [0] group. send ("hello world! ")

1.4 wxpy Message Processing

Next, we will introduce the types of messages sent by users. Currently, wxpy supports sending text, images, videos, and files. The main sending method is shown in the Code:

What is important here is the use of @ bot. register (). This annotation is mainly used to register a message receiver. We can configure different message receivers according to specific requirements.

Bot. register (chats = None, msg_types = None, effect_self = True, run_async = True, enabled = True) details can be viewed in the source code

For the message processing API, you can view the detailed configuration under this address, which is not described too much here.

The embed () method is used in the code to block processes and prevent messages from being received due to the end of the program running.

From wxpy import * bot = Bot () # Get friend my_friend = bot. friends (). search ('waybill ') [0] # search information messages = bot. messages. search (keywords = 'test', sender = bot. self) for message in messages: print (message) # send the text my_friend.send ('hello, WeChat! ') # Send the image my_friend.send_image('my_picture.png') # send the video my_friend.send_video ('My _ video. mov ') # sender file my_friend.send_file('my_file.zip') # sender public account my_friend.send_raw_msg (# original business card Message Type raw_type = 42, # note that 'username' should be ID here, and the sent business card must be your friend raw_content = '<msg username = "wxpy_bot" nickname = "wxpy robot"/>') # message receiving listener @ bot. register () def print_others (msg): # print (msg) of the listening message output # reply message msg. reply ("hello world") embed ()

1.4 wxpy Turing Robot

Wxpy's access to the Turing robot is quite convenient. First, we need to register with the Turing's recent official website.

By registering the Tuling object, when we receive the message, we can directly use the tuling robot to help us reply. You can complete the corresponding logic based on your own business needs.

From wxpy import * bot = Bot () # Get FRIEND dear = bot. friends (). search ('waybill ') [0] # register for personal Turing robot key and fill in tuling = Tuling (api_key = '******') # Use the Turing robot to automatically chat with specified friends @ bot. register (dear) def reply_my_friend (msg): print (msg) tuling. do_reply (msg) embed ()

1.5 wechat_sender

After getting familiar with wxpy related operations, we will introduce the next major tool. Due to the wxpy design, some business operations are not easy to implement. So here we introduce a tool class: wechat_sender.

First, we need to log in as usual, and then use listen () to listen to our bot () object.

Here we can see the difference from the above Code. Here we use listen (), and above we use embed () for listening. After using listen to objects, you can set the corresponding configuration. The default receiver of the listener is self. file_helper. You can configure the receiver of the message by setting receivers.

# Login. pyfrom wxpy import * from wechat_sender import * bot = Bot () friend = bot. friends (). search ('waybill ') [0] listen (bot, token = 'test', receivers = [friend])
# sender.py coding: utf-8from wechat_sender import Sendersender = Sender(token='test')sender.send('hello world!')

In other python files, we only need to create a Sender () object and then call the Sender. send () method to send messages to the specified message receiver.

Sender () can be set through specific parameters during creation. For example, token is used here to avoid sender confusion caused by multiple listen. You can also set the receiver in sender to select the object for receiving messages from listen.

1.6 wxpy code implementation in the monitoring module

Login module:

From wechat_sender import * from wxpy import * bot = Bot (qr_path = "qr.png") group = bot. groups (). search ('monitoring alert ') [0] print ("Login successful! Monitoring alarm function! ") Print (group) # listen (bot, token = 'test', receivers = [group])

Business Processing Module:

Import redisfrom wechat_sender import * sender = Sender (token = 'test', receivers = 'monitoring alert ') while true: # do anything sender. send (message = data) # do anythingp. unsubscribe ('cardniu-monitor') print ('unsubscribe ')

2. Python-Redis

In this module, we will briefly describe python's support for Redis. First, we need to install python-redis related modules:

2.1 install Python-redis

  • Download the compressed package: Any door of Doraemon
  • Decompress the package to the Redis directory.
  • Run the following command: python setup. py install

2.2 Python simple Redis operations

Since Python operations on Redis are not the main content here, it is a simple review of Python's support for Redis.

import redisr = redis.Redis(host='ip', port=6379, db=15, password='****')r.set('name', 'Jaycekon')value = r.get('name')print(value)

2.3 Redis publishing and subscription Mode

Before explaining the publishing and subscription modes of Redis, let's take a look at the producer and consumer models:

Let's take a look at my soul plot. The core idea of producer consumers is to decouple through a refrigerator, that is, our chefs do not need to go out of the kitchen, and customers do not need to go to the kitchen for food. A refrigerator is used for intermediate decoupling.

The following is a producer-consumer model that we implement through python. chefs keep cooking and customers keep eating .. Everyone has no influence on each other.

From threading import Threadqueues = queue. queue (10) class Producer (Thread): def run (self): while True: elem = random. randrange (9) queues. put (elem) print ("cook {} made {} meals --- {} meals left not sold out ". format (self. name, elem, queues. qsize () time. sleep (random. random () class Consumer (Thread): def run (self): while True: elem = queues. get () print ("Food {} has eaten {} meals --- and {} meals can be eaten ". format (self. name, elem, queues. qsize () time. sleep (random. random () def main (): for I in range (3): p = Producer () p. start () for I in range (2): c = Consumer () c. start () if _ name _ = '_ main _': main ()

Let's take a look at why the Redis publishing and subscription mode is used.

Redis is mainly used as a message queue in the current program. We have not used the popular RabbitMq and ActiveMq to decouple message queues. The main reason is that our service is not large and the message volume is small. Therefore, Redis is used as the Message Queue Based on the architecture that does not affect the program.

The key aspect of message queue is that after a producer publishes a message, the consumer must be able to receive the message quickly. The Publish/subscribe mode can help us solve the problem well. When a message arrives, the program can immediately respond to the operation.

Redis message publishing:

Import redispool = redis. connectionPool (host = 'IP', port = 6379, db = 4, password = '***') r = redis. strictRedis (connection_pool = pool) while True: inputs = input ("publish:") r. publish ('spub ', inputs) if inputs = 'over': print ('stop publishing') break

Redis message subscription:

Import redispool = redis. connectionPool (host = 'IP', port = 6379, db = 4, password = '***') r = redis. strictRedis (connection_pool = pool) p = r. pubsub () p. subscribe ('cardniu-monitor') for item in p. listen (): print (item) if item ['type'] = 'message': data = item ['data'] print ("message Queue received information: ", data) if item ['data'] = 'over': breakp. unsubscribe ('cardniu-monitor') print ('unsubscribe ')

2.4 wxpy + Redis: consumer of the Monitoring System

Finally, the consumer of the monitoring system implemented in python is as follows:

Login module:

From wechat_sender import * from wxpy import * bot = Bot (qr_path = "qr.png") group = bot. groups (). search ('monitoring alert ') [0] print ("Login successful! Monitoring alarm function! ") Print (group) # listen (bot, token = 'test', receivers = [group])

Redis message subscription module:

Import redisfrom wechat_sender import * sender = Sender (token = 'test', receivers = 'monitoring alert ') pool = redis. connectionPool (host = '10. 201.3.18 ', port = 6379, db = 4, password = 'kntest % pw _ @ dk2') r = redis. strictRedis (connection_pool = pool) p = r. pubsub () p. subscribe ('cardniu-monitor') for item in p. listen (): print (item) if item ['type'] = 'message': data = item ['data'] print ("message Queue received information: ", data) sender. send (message = data) if item ['data'] = 'over': breakp. unsubscribe ('cardniu-monitor') print ('unsubscribe ')

3. Java-Redis

Finally, the producer is the core part of our monitoring system. When an exception occurs in our Java system, we can send a message to Redis, and finally the consumer can send the message.

The following is a brief description of the producer code, but the code design company does not describe it too much.

Spring-redis.xml

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: util = "http://www.springframework.org/schema/util" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring- Beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd "> <! -- Redis connection pool configuration --> <bean id = "jedisPoolConfig" class = "redis. clients. jedis. jedisPoolConfig "> <property name =" maxTotal "value =" $ {redis. pool. maxTotal} "/> <property name =" maxIdle "value =" $ {redis. pool. maxIdle} "/> <property name =" minIdle "value =" $ {redis. pool. minIdle} "/> <property name =" maxWaitMillis "value =" $ {redis. pool. maxWaitMillis} "/> <property name =" testOnBorrow "value =" $ {redis. pool. testOnBorrow} "/> <property name =" testOnReturn "value =" $ {redis. pool. testOnReturn} "/> </bean> <bean id =" sentinelJedisPool "class =" redis. clients. jedis. jedisSentinelPool "> <constructor-arg index =" 0 "value =" $ {redis. sentinel. masterName} "/> <constructor-arg index =" 1 "value =" # {'$ {redis. sentinels }'. split (',')} "/> <constructor-arg index =" 2 "ref =" jedisPoolConfig "/> <constructor-arg index =" 3 "value =" $ {redis. sentinel. timeout} "type =" int "/> <constructor-arg index =" 4 "value =" $ {redis. sentinel. password} "/> <constructor-arg index =" 5 "value =" $ {redis. sentinel. database} "type =" int "/> </bean> </beans>

JedisUtils. java

@ Autowired private JedisSentinelPool jedisPool; @ PostConstruct private void init () throws Exception {/* cache initialization */JedisUtils. setJedisPool (jedisPool);} public static void setJedisPool (Pool <Jedis> jedisPool) throws Exception {JedisCache. jedisPool = jedisPool; Jedis jedis = null; try {jedis = jedisPool. getResource (); isInitSuc = true; logger.info ("redis start success! ");} Catch (Exception e) {if (null! = Jedis) jedisPool. returnBrokenResource (jedis); logger. error ("redis start exception !!! Error: {} ", e. getMessage (), e); if (e instanceof redis. clients. jedis. exceptions. jedisConnectionException) {throw e ;}} finally {if (null! = Jedis) jedisPool. returnResource (jedis) ;}} public static Long publish (String chanel, String value) {Jedis jedis = null; try {jedis = jedisPool. getResource (); return jedis. publish (chanel, value);} catch (Exception e) {if (null! = Jedis) {jedisPool. returnBrokenResource (jedis); jedis = null;} logger. error ("redis exception :{}", e. getMessage (), e); return 0L;} finally {if (null! = Jedis) jedisPool. returnResource (jedis );}}

NoticeTask. java

@ Scheduled (cron = "*/5 ****? ") Public void runMonitor () {try {List <T> notices; List <EbankNotice> result; while (notices = QueueHolder. noticeBlockingQueue. take ())! = Null) {// consume if (notices. isEmpty () {continue;} result = service. calculateNotice (notices); result. forEach (notice-> {JedisUtils. publish ("cardniu-monitor", notice. getTitle () + "," + DateUtils. format (notice. getPostTime (), "yyyy-MM-dd hh: mm: ss") + "," + notice. getLinkAddress () ;}}} catch (InterruptedException e) {logger. error ("scheduled email sending task exception, {}", e. getMessage (), e );}}

4. Summary

The core of this project is the application of wxpy and the design philosophy of producer and consumer. If the language is used, the core python wxpy can be used as the producer in any other language.

Github address: https://github.com/jaycekon/WxpyDemo

Refer:

Wxpy API: http://wxpy.readthedocs.io/zh/latest/messages.html

Wechat_sender Api: https://pypi.python.org/pypi/wechat-sender/0.1.3

Python-redis: https://pypi.python.org/pypi/redis

Java-Redis: http://docs.spring.io/spring-data/redis/docs/2.0.0.M4/reference/html/

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.