preface

A few days ago, I saw an article on the Internet called “Teach you to say good night to your girlfriend every day by wechat”. I felt it was very magical. Then I studied it. Okay, let’s get started! The server is there, the Python environment is there, the IDE is open… However… However… I realized a very serious problem… No girlfriend (T_T)…

WeChat development has been active for a long time, have a magic in the WeChat development interface called template message interface, it can be based on user openid from the server to the user to push a custom template, because of this, we can use this feature on the server side, from time to time, send to users to push messages (premise is that the user pay attention to the public).

Three points are summarized: 1. The format of template messages can be customized; 2. The content of template messages can be customized; 3. The time at which template messages are sent can be customized. So we can use these properties to make a good morning app for ourselves!

Experimental environment

  • Aliyun Linux server
  • Python 2.7

Iciba daily one API introduction

Call the address: http://open.iciba.com/dsapi/ request: GET request parameters:

parameter Will choose type instructions
date no string The format is 2013-05-06. If date is, the value is the current day by default
type no string The options are last and next; Based on date, last returns the previous day, and next returns the next day

Example request:

The Python example

#! /usr/bin/python
#coding=utf-8
import json
import urllib2
def get_iciba(a):
  url = 'http://open.iciba.com/dsapi/'
  request = urllib2.Request(url)
  response = urllib2.urlopen(request)
  json_data = response.read()
  data = json.loads(json_data)
  return data
print get_iciba()
Copy the code

The PHP sample


      
function https_request($url, $data = null){
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_HEADER, 0);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  if (!empty($data)) {
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  }
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $output = curl_exec($curl);
  curl_close($curl);
  return $output;
}
function get_iciba(a){
  $url = 'http://open.iciba.com/dsapi/'
  $result = https_request($url);
  $data = json_decode($result);
  return $data;
}
echo get_iciba();
Copy the code

Return type: JSON

The property name Attribute value type instructions
sid string ID of the Day
tts string Audio address
content string English content
note string Chinese content
love string One sentence a day like number
translation string Here small make up
picture string Picture address
picture2 string Big picture address
caption string The title
dateline string time
s_pv string Browse the number
sp_pv string Voice review views
tags string Relevant tags
fenxiang_img string Synthetic picture, suggested to share the micro blog with

An example is returned normally:

{
  "sid": "3080"."tts": "http://news.iciba.com/admin/tts/2018-08-01-day.mp3"."content": "No matter how hard we try to be mature, we will always be a kid when we all get hurt and cry. "."note": "No matter how hard we try to grow up, when we get hurt and cry, we're still like children."."love": "1966"."translation": This sentence comes from the novel Peter Pan. Time is always young, we slowly old. No matter how you change, you will finally find: retaining a childish heart, is a matter of pride. Sometimes it's easy to grow up, but it's not always easy to enjoy everything with a childlike innocence."."picture": "http://cdn.iciba.com/news/word/20180801.jpg"."picture2": "http://cdn.iciba.com/news/word/big_20180801b.jpg"."caption": "Iciba sentence of the Day"."dateline": "2018-08-01"."s_pv": "0"."sp_pv": "0"."tags": [{"id": null."name": null}]."fenxiang_img": "http://cdn.iciba.com/web/news/longweibo/imag/2018-08-01.jpg"
}
Copy the code

This interface (daily sentence) official document: http://open.iciba.com/?c=wiki reference: Kingsoft Powerword · development platform

Log in to the wechat public platform interface test account

Scan log on to the public platform test, application test, the address of the https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

Confirm login on your phone

Find the new test template and add the template message

Fill in the following sentence in the template title

{{content.DATA}}
{{note.DATA}}
{{translation.DATA}}
Copy the code

After you commit and save, remember the template ID, which you’ll use later

Find the test number information, remember appID and AppSecret, which we’ll use in a moment

Find the qr code of the test number. Mobile phone scan this TWO-DIMENSIONAL code, after attention, your nickname will appear in the right list, remember the micro signal, will be used in a moment (note: this micro signal is not your real micro signal)

Send wechat template message program

This procedure you only need to modify 4 places, please see the notes

#! /usr/bin/python
#coding=utf-8
import json
import urllib2

class iciba:
    # initialization
    def __init__(self, wechat_config):
        self.appid = wechat_config['appid']
        self.appsecret = wechat_config['appsecret']
        self.template_id = wechat_config['template_id']
        self.access_token = ' '

    # get access_token
    def get_access_token(self, appid, appsecret):
        url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (appid, appsecret)
        request = urllib2.Request(url)
        response = urllib2.urlopen(request)
        json_data = response.read()
        data = json.loads(json_data)
        access_token = data['access_token']
        self.access_token = access_token
        return self.access_token

    # send a message
    def send_msg(self, openid, template_id, iciba_everyday):
        msg = {
            'touser': openid,
            'template_id': template_id,
            'url': iciba_everyday['fenxiang_img'].'data': {
                'content': {
                    'value': iciba_everyday['content'].'color': '#0000CD'
                    },
                'note': {
                    'value': iciba_everyday['note'],},'translation': {
                    'value': iciba_everyday['translation'],
                }
            }
        }
        json_data = json.dumps(msg)
        if self.access_token == ' ':
            self.get_access_token(self.appid, self.appsecret)
        access_token = self.access_token
        url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % str(access_token)
        request = urllib2.Request(url, data=json_data)
        response = urllib2.urlopen(request)
        result = response.read()
        return json.loads(result)

    # Get iciba sentence of the day
    def get_iciba_everyday(self):
        url = 'http://open.iciba.com/dsapi/'
        request = urllib2.Request(url)
        response = urllib2.urlopen(request)
        json_data = response.read()
        data = json.loads(json_data)
        return data

    # send a message for the set user list
    def send_everyday_words(self, openids):
        everyday_words = self.get_iciba_everyday()
        for openid in openids:
            result = self.send_msg(openid, self.template_id, everyday_words)
            if result['errcode'] = =0:
                print ' [INFO] send to %s is success' % openid
            else:
                print ' [ERROR] send to %s is error' % openid

    # to perform
    def run(self, openids):
        self.send_everyday_words(openids)


if __name__ == '__main__':
    # wechat configuration
    wechat_config = {
        'appid': 'xxxxxx'.Fill in your appID here
        'appsecret': 'xxxxxxx'.Fill in your AppSecret here
        'template_id': 'xxxxx' Fill in your template message ID here
    }
    # user list
    openids = [
        'xxxxx'.Fill in your wechat id here
        #' XXXX ', # if there are more than one user
    #'xxxx',
    ]
    # to perform
    icb = iciba(wechat_config)
    icb.run(openids)
Copy the code

The test program

Execute the program on Linux

The deployment process

Set a scheduled task on Linux

crontab -e

Add the following

0 6 * * * python /root/python/iciba/main-v1.0.py

Note: At 6:00 p.m. each day, execute this Python program to see if the scheduled task has been set successfully

crontab -l

So far, the program deployment is complete, please check it at 6:00 tomorrow!

The renderings are as follows:

The final good news

Purchase server deployment, Tencent cloud’s biggest ever event:

Registration is full 1000 minus 750 volumes, cloud server at least 2 off, 1 core 1G memory 50G hard disk 1M bandwidth 1 year only 325 yuan! Stamp this direct activity scene!


From https://www.cnblogs.com/connect/p/python-wechat-iciba.html