100行代碼,天天早上喝一碗雞湯

在開始以前,咱們先來介紹一下雞湯的載體。在這裏要介紹一個東西,Server醬python

關於Server醬,簡單來講,就是能夠經過服務器以微信公衆號的形式給微信發消息的一個工具,發送的內容支持Markdown語法。並且天天醒來第一件事就是打開微信,這是一件一定會作的事情,沒有任何東西比Server醬更合適當雞湯的載體了。web

通過我喝了差很少3個月的雞湯,發現Server醬是很穩定的,沒有錯過任何一天的雞湯。日誌爲證:json

nohup: ignoring input
2018-07-09 10:55:25 開始執行任務
2018-07-10 08:00:00 推送成功。
2018-07-11 08:00:00 推送成功。
2018-07-12 08:00:00 推送成功。
2018-07-13 08:00:00 推送成功。
2018-07-14 08:00:00 推送成功。
2018-07-15 08:00:00 推送成功。
2018-07-16 08:00:00 推送成功。
2018-07-17 08:00:00 推送成功。
2018-07-18 08:00:01 推送成功。
2018-07-19 08:00:00 推送成功。
2018-07-20 08:00:00 推送成功。
2018-07-21 08:00:00 推送成功。
2018-07-22 08:00:00 推送成功。
2018-07-23 08:00:00 推送成功。
2018-07-24 08:00:00 推送成功。
2018-07-25 08:00:00 推送成功。
2018-07-26 08:00:00 推送成功。
2018-07-27 08:00:00 推送成功。
2018-07-28 08:00:00 推送成功。
2018-07-29 08:00:00 推送成功。
2018-07-30 08:00:00 推送成功。
2018-07-31 08:00:00 推送成功。
2018-08-01 08:00:00 推送成功。
2018-08-02 08:00:00 推送成功。
2018-08-03 08:00:00 推送成功。
2018-08-04 08:00:00 推送成功。
2018-08-05 08:00:00 推送成功。
2018-08-06 08:00:00 推送成功。
2018-08-07 08:00:00 推送成功。
2018-08-08 08:00:00 推送成功。
2018-08-09 08:00:00 推送成功。
2018-08-10 08:00:00 推送成功。
2018-08-11 08:00:00 推送成功。
2018-08-12 08:00:00 推送成功。
2018-08-13 08:00:00 推送成功。
2018-08-14 08:00:00 推送成功。
2018-08-15 08:00:00 推送成功。
2018-08-16 08:00:00 推送成功。
2018-08-17 08:00:00 推送成功。
2018-08-18 08:00:00 推送成功。
2018-08-19 08:00:00 推送成功。
2018-08-20 08:00:00 推送成功。
2018-08-21 08:00:01 推送成功。
2018-08-22 08:00:00 推送成功。
2018-08-23 08:00:00 推送成功。
2018-08-24 08:00:01 推送成功。
2018-08-25 08:00:00 推送成功。
2018-08-26 08:00:00 推送成功。
2018-08-27 08:00:00 推送成功。
2018-08-28 08:00:00 推送成功。
2018-08-29 08:00:00 推送成功。
2018-08-30 08:00:00 推送成功。
2018-08-31 08:00:00 推送成功。
2018-09-01 08:00:00 推送成功。
2018-09-02 08:00:00 推送成功。
2018-09-03 08:00:00 推送成功。
2018-09-04 08:00:00 推送成功。
2018-09-05 08:00:00 推送成功。
2018-09-06 08:00:00 推送成功。
2018-09-07 08:00:00 推送成功。
2018-09-08 08:00:00 推送成功。
2018-09-09 08:00:00 推送成功。
2018-09-10 08:00:00 推送成功。
2018-09-11 08:00:00 推送成功。
2018-09-12 08:00:00 推送成功。
2018-09-13 08:00:00 推送成功。
2018-09-14 08:00:00 推送成功。
2018-09-15 08:00:00 推送成功。
2018-09-16 08:00:00 推送成功。
2018-09-17 08:00:00 推送成功。
2018-09-18 08:00:00 推送成功。
2018-09-19 08:00:00 推送成功。
2018-09-20 08:00:01 推送成功。
2018-09-21 08:00:00 推送成功。
2018-09-22 08:00:00 推送成功。
2018-09-23 08:00:00 推送成功。
2018-09-24 08:00:00 推送成功。
2018-09-25 08:00:00 推送成功。
2018-09-26 08:00:00 推送成功。
2018-09-27 08:00:00 推送成功。
2018-09-28 08:00:00 推送成功。
2018-09-29 08:00:00 推送成功。
2018-09-30 08:00:00 推送成功。
2018-10-01 08:00:00 推送成功。
複製代碼

關於Server醬詳細的介紹和用法,請查看Server醬的使用說明,很詳細也很簡單。 另外,Server醬的目的是服務器異常報警,請勿濫用。api

沒圖說個...好吧,先看圖: bash

效果圖

咱們看到,須要獲取的內容有雞湯文和天氣。雞湯我用的是金山詞霸的接口 open.iciba.com/dsapi/,獲取天氣則是順手用了高德的地圖的接口。服務器

獲取雞湯

金山詞霸每日一文的接口是GET方式調用直接返回,格式以下:微信

{
	"sid": "3143",
	"tts": "http://news.iciba.com/admin/tts/2018-10-01-day.mp3",
	"content": "A man has free choice to begin love, but not to end it.",
	"note": "一我的能夠選擇愛上誰,當他要結束愛情時,他是沒有選擇的。",
	"love": "1150",
	"translation": "小編的話:愛情一直是不變的話題。碰見了心愛的人,能夠說是幸運的,不管結局怎樣,均可以說是幸福的。白頭到老,當然很好,若是分手,或者爲愛情傷心,也很幸福,由於畢竟愛過。每一個人對愛情的理解不盡相同,畢竟感情這東西,如人飲水冷暖自知。",
	"picture": "http://cdn.iciba.com/news/word/20181001.jpg",
	"picture2": "http://cdn.iciba.com/news/word/big_20181001b.jpg",
	"caption": "詞霸每日一句",
	"dateline": "2018-10-01",
	"s_pv": "0",
	"sp_pv": "0",
	"tags": [{
		"id": null,
		"name": null
	}],
	"fenxiang_img": "http://cdn.iciba.com/web/news/longweibo/imag/2018-10-01.jpg"
}
複製代碼

咱們須要的是日期、英文、中午翻譯和小編的話,因此能夠這樣寫:ide

def get_soup():
    """ 獲取雞湯 """
    response = requests.get(soup_url)
    json_data = response.json()

    date = json_data['dateline']
    content = json_data['content']
    note = json_data['note']
    picture = json_data['picture']
    translation = json_data['translation']

    return date, content, note, picture, translation
複製代碼

這裏咱們用到了requests這個庫,基本操做。工具

獲取天氣

我用的是高德地圖的天氣接口 lbs.amap.com/api/webserv…,大家能夠選擇其餘的。ui

def get_weather():
    """ 獲取天氣 """
    response = requests.get(weather_url)
    json_data = response.json()

    if json_data['status'] == '1':
        return json_data['forecasts'][0]['casts'][0]
    else:
        print(get_time() + " 天氣獲取失敗:" + json_data['info'])
        return None
複製代碼

製做雞湯

咱們須要把獲取到的天氣和雞湯內容按照Markdown格式拼接起來:

def make_soup():
    """ 製做雞湯 """
    soup = get_soup()

    weather = get_weather()

    if weather is None:
        time.sleep(3)
        weather = get_weather()

    title = "早上好!"
    desp = "#### {date}\n\n白天{dayweather},夜晚{nightweather},溫度{nighttemp}℃ ~ {daytemp}℃。\n\n" \
           "*{content}*\n\n{note}\n\n![]({picture})\n\n{translation}" \
        .format(date=soup[0],
                dayweather=weather['dayweather'],
                nightweather=weather['nightweather'],
                nighttemp=weather['nighttemp'],
                daytemp=weather['daytemp'],
                content=soup[1],
                note=soup[2],
                picture=soup[3],
                translation=soup[4])

    push_wx(title, desp)
複製代碼

推送雞湯

而後經過調用Server醬的接口,將雞湯送出去,以供享用~

def push_wx(text=None, desp=""):
    """ 推送消息到微信 """
    params = {
        "text": text,
        "desp": desp
    }

    response = requests.get(server_url, params=params)
    json_data = response.json()

    if json_data['errno'] == 0:
        print(get_time() + " 推送成功。")
    else:
        print("{0} 推送失敗:{1} \n {2}".format(get_time(), json_data['errno'], json_data['errmsg']))
複製代碼

天天發送雞湯

這雞湯確定是不能天天手動發的啦,咱們須要一個定時任務,天天同一時間點去發送。這時候,就須要寫一個定時任務了。這裏咱們用到了APScheduler這個庫,不瞭解的去看一下官方文檔,這裏以天天早上8點鐘爲例。

最後一步,啓動整個任務:

if __name__ == '__main__':
    print(get_time() + " 開始執行任務")
    scheduler.add_job(make_soup, 'cron', day_of_week='0-6', hour=8, minute=00, second=00)
    scheduler.start()
複製代碼

在服務器上運行

把這個py文件上傳到本身的服務器,以Python3,CentOS爲例,經過命令:

nohup python3 -u chicken_soup.py > nohup.out 2>&1 &
複製代碼

去啓動腳本,這樣把終端關掉也能夠在後臺運行了,並且會生成一個文件用於保存打印的內容。

完整代碼以下:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import requests
import time
from apscheduler.schedulers.blocking import BlockingScheduler

server_url = "https://sc.ftqq.com/Server醬SCKEY.send"
soup_url = "http://open.iciba.com/dsapi/"
weather_url = "http://restapi.amap.com/v3/weather/weatherInfo?city=城市id&key=高德地圖key&extensions=all"

scheduler = BlockingScheduler()


def get_time():
    """ 獲取當前時間 """
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


def push_wx(text=None, desp=""):
    """ 推送消息到微信 """
    params = {
        "text": text,
        "desp": desp
    }

    response = requests.get(server_url, params=params)
    json_data = response.json()

    if json_data['errno'] == 0:
        print(get_time() + " 推送成功。")
    else:
        print("{0} 推送失敗:{1} \n {2}".format(get_time(), json_data['errno'], json_data['errmsg']))


def get_soup():
    """ 獲取雞湯 """
    response = requests.get(soup_url)
    json_data = response.json()

    date = json_data['dateline']
    content = json_data['content']
    note = json_data['note']
    picture = json_data['picture']
    translation = json_data['translation']

    return date, content, note, picture, translation


def get_weather():
    """ 獲取天氣 """
    response = requests.get(weather_url)
    json_data = response.json()

    if json_data['status'] == '1':
        return json_data['forecasts'][0]['casts'][0]
    else:
        print(get_time() + " 天氣獲取失敗:" + json_data['info'])
        return None


def make_soup():
    """ 製做雞湯 """
    soup = get_soup()

    weather = get_weather()

    if weather is None:
        time.sleep(3)
        weather = get_weather()

    title = "早上好!"
    desp = "#### {date}\n\n白天{dayweather},夜晚{nightweather},溫度{nighttemp}℃ ~ {daytemp}℃。\n\n" \
           "*{content}*\n\n{note}\n\n![]({picture})\n\n{translation}" \
        .format(date=soup[0], dayweather=weather['dayweather'], nightweather=weather['nightweather'],
                nighttemp=weather['nighttemp'], daytemp=weather['daytemp'],
                content=soup[1],
                note=soup[2],
                picture=soup[3],
                translation=soup[4])

    push_wx(title, desp)


if __name__ == '__main__':
    print(get_time() + " 開始執行任務")
    scheduler.add_job(make_soup, 'cron', day_of_week='0-6', hour=8, minute=00, second=00)
    scheduler.start()
複製代碼

本篇教程到此結束,去愉快的玩耍吧。

相關文章
相關標籤/搜索