100行程式碼,每天早上喝一碗雞湯

Fi7z發表於2019-03-02

在開始之前,我們先來介紹一下雞湯的載體。在這裡要介紹一個東西,Server醬

關於Server醬,簡單來說,就是可以通過伺服器以微信公眾號的形式給微信發訊息的一個工具,傳送的內容支援Markdown語法。而且每天醒來第一件事就是開啟微信,這是一件必定會做的事情,沒有任何東西比Server醬更合適當雞湯的載體了。

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

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醬的目的是伺服器異常報警,請勿濫用。

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

效果圖

我們看到,需要獲取的內容有雞湯文和天氣。雞湯我用的是金山詞霸的介面 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"
}
複製程式碼

我們需要的是日期、英文、中午翻譯和小編的話,所以可以這樣寫:

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…,你們可以選擇其他的。

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()
複製程式碼

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

相關文章