訂製雲函數天氣推送

sansui-Weather v2.0

介紹:

 在寒冷的冬日給你愛的人暖暖的提示
(可增加情話api,每天推送情話及其他訂製化的推送)
Python腳本實現天氣查詢應用,提醒她注意保暖!
 

功能介紹:

  • 天氣資訊獲取推送
  • 當天天氣資訊提示推送
  • 第二天天氣資訊提示推送
  • 網易雲熱評資訊獲取推送
  • 舔狗日記資訊獲取推送
  • 疫情資訊數據獲取推送
  • 可根據個人需要,添加訂製的資訊提示

 

使用說明:

  以下資訊換為自己的,具體根據API地址申請key後進行替換
  SendKey server醬
  Weather_key 和風天氣API
  Tianapi_key 網易雲熱評API
  Storeapi_key 疫情數據API
  ApiKey 疫情數據API
  userid 接收消息的用戶,存在多個以 | 隔開
  adminUserId 管理員用戶,錯誤資訊要推送的用戶

 

下載地址:

//wwb.lanzouw.com/iwk7vzmd75c       

密碼:d0bz

 

雲函數搭建教程:

//support.qq.com/products/130099/blog/546919

 

程式碼修改教程:

//wwb.lanzoub.com/iKLJG017swba
密碼:4bpo

 

程式碼:

# -*- coding: utf8 -*-
# [url=home.php?mod=space&uid=238618]@Time[/url]    : 2021/7/19 13:16
# [url=home.php?mod=space&uid=686208]@AuThor[/url]  : Sansui
# @FileName: index.py
# @Software: PyCharm
# @Blog    ://www.cnblogs.com/sansui6/
 
 
import requests
import datetime
import time
import json
import pytz
import ssl,hashlib,string
from urllib import request,parse,error;
from urllib.parse import quote
 
SendKey = '';#pushplus申請的KEY或者server醬的KEY,這裡我自己改了
Weather_key = ''
Tianapi_key = ''
Storeapi_key = ''
ApiKey = ''
# 接收消息的用戶,存在多個以 | 隔開
userid = ''
 
adminUserId = '';
 
def get_time():
    nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime());  # 獲取當前時間
    # 由於騰訊雲時間不準確,暫時使用年月日
    nowTime_1 = time.strftime("%Y-%m-%d", time.localtime());  # 獲取當前時間
    # print(nowTime_1)
    return nowTime_1;
 
 
#獲取網易雲評論
def get_wyy():
    list = []  ## 空列表
    wyy_url = "//api.tianapi.com/txapi/hotreview/index?key=" + Tianapi_key + "";
    wyy_json = requests.post(wyy_url).json();
    wyy_code = wyy_json["code"]
    if wyy_code.__eq__(200):
        #獲取評論內容
        wyy_content = wyy_json["newslist"][0]["content"]
        #獲取歌名
        wyy_source = wyy_json["newslist"][0]["source"]
        #把評論、歌名放進數組
        list.append(wyy_content)
        list.append(wyy_source)
        return list;
    else:
        list.append('獲取失敗!')
        return list;
 
#2021/8/4 因疫情較為嚴重,新增加疫情提示
def ncov():
    api_url = '//yupn.api.storeapi.net/api/94/221';
    appid = 13948;
    secret = Storeapi_key;
    data = {
        'appid': appid,
        'city_name': '蘇州',
        'format': 'json',
        'time': '1644207719',
    };
    data['appid'] = appid;
    data['time'] = round(time.time());  # 當前伺服器時間
    keysArr = list(data.keys())  # 取出字典key
    keysArr.sort()  # 對字典key進行排序
    md5String = '';
    params = []
    for key in keysArr:
        if data[key]:
            val = str(data[key])
            md5String += key + val
            params.append(key + "=" + val)
    md5String += secret;
    m = hashlib.md5()
    b = md5String.encode(encoding='utf-8')
    m.update(b)
    sign = m.hexdigest()
 
    params.append('sign=' + sign)  # 加入計算後的sign值去請求
    params = '&'.join(tuple(params));  # 把列錶轉成元組後用&分隔,最終轉換成字元串 a=b&c=d&e=f
 
    ssl._create_default_https_context = ssl._create_unverified_context
    url = api_url + '?' + params;
    url = quote(url, safe=string.printable)
    req = requests.get(url).json()
    #city 所選城市
    #confirm 確診病例數量
    #curConfirm 當前確診數量
    #died  死亡數量
    #heal  治癒數量
    #asymptomatic 無癥狀感染數量
    #print(req["retdata"])
    return req["retdata"]
 
#獲取實時疫情資訊,如分風險地區、疫情概況、疫情新聞等
def nCoV_news(num):
    url="//api.tianapi.com/txapi/ncov/index?key="+Tianapi_key;
    nCoV_news_json = requests.get(url).json()
    nCoV_news_code = nCoV_news_json["code"]
    print(nCoV_news_json)
    nCoV_news_newslist = nCoV_news_json["newslist"]
    i=0;
    if(nCoV_news_code.__eq__(200)):
        if (num.__eq__(1)):
            # 獲取當前數據資訊
            return nCoV_news_newslist[0]["desc"]
        elif(num.__eq__(2)):
            #返回全國風險地區,high高風險、mid中風險
            riskarea_high_text = "| -------- | 高風險地區 | --------: |";
            for riskarea_high in nCoV_news_newslist[0]["riskarea"]["high"]:
                if("江蘇省" in riskarea_high):
                    # 因為高風險地區逐漸增多,消息已經存放不下,現調整通知格式為具體數量,不再是具體地區。
                    i=i+1;
            return "\n江蘇省高風險地區共:" + str(i) + "個。\n"
        elif(num.__eq__(0)):
            riskarea_mid_text = "| -------- | 中風險地區 | --------: |";
            for riskarea_mid in nCoV_news_newslist[0]["riskarea"]["mid"]:
                # print(riskarea_high)
                if ("江蘇省" in riskarea_mid):
                    #因為中風險地區逐漸增多,消息已經存放不下,現調整通知格式為具體數量,不再是具體地區。
                    #riskarea_mid_text +="\n" + riskarea_mid;
                    # riskarea_high_text=riskarea_high;
                    i=i+1;
            # return nCoV_news_newslist[0]["riskarea"]
            #print(riskarea_mid_text)
            #return riskarea_mid_text;
            return "\n江蘇省中風險地區共:"+str(i)+"個。"
 
 
#獲取當天天氣,不過沒有最高溫度,最低溫度
def get_Weather():
    city_id = get_location();
    Weather_url = f'//devapi.qweather.com/v7/weather/now?key={Weather_key}&location={city_id}'
    Weather_json = requests.get(Weather_url).json()
    #print(Weather_url)
    Weather_code = Weather_json["code"]
    Weather_now = Weather_json["now"]
    if(Weather_code.__eq__("200")):
      #print(Weather_now)
      return Weather_now;
 
#獲取包括今天在內的未來三天天氣
def get_3d_Weather(num):
    date = get_time();
    date_tomorrow = (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d");
    city_id = get_location();
    Weather_url = f'//devapi.qweather.com/v7/weather/3d?key={Weather_key}&location={city_id}';
    #print(Weather_url)
    Weather_json = requests.get(Weather_url).json();
    Weather_3d = Weather_json["daily"]
    for weather in Weather_3d:
        #print("6666666"+weather)
        if(num.__eq__(1)):
            if(weather["fxDate"].__eq__(date)):
                #print("當天天氣獲取成功")
                return weather;
            else:
                print("查詢的不是今天日期的天氣")
                return "查詢的不是今天日期的天氣"
                break;
        elif(num.__eq__(0)):
            if (weather["fxDate"].__eq__(date_tomorrow)):
                #print(weather);
                return weather;
        else:
            print("非法參數!")
            return "非法參數!"
 
#獲取當前天氣地區id
def get_location():
    # 調整所在的區域
    location='蘇州'
    Weather_city_url = f'//geoapi.qweather.com/v2/city/lookup?key={Weather_key}&location={location}'
    city_json =requests.get(Weather_city_url).json();
    city_code = city_json["code"]
    if city_code.__eq__("200"):
     #print(Weather_city_url)
     for Weather_city in city_json["location"]:
         Weather_city_name = Weather_city["name"]
         if Weather_city_name.__eq__("蘇州"):
             #print(Weather_city)
             city_id = Weather_city["id"]
             #print(city_id)
             return city_id;
 
    else:
      print("訪問獲取地區介面失敗!")
      return "訪問獲取地區介面失敗!";
 
def get_tiangou():
    url="//api.tianapi.com/tiangou/index?key="+Tianapi_key;
    tiangou_json = requests.get(url).json()
    tiangou = tiangou_json["newslist"][0]["content"]
    return tiangou
 
#拼接消息
def get_desp():
 
    wyy_content = get_wyy()[0];  # 評論內容
    wyy_source = get_wyy()[1];  # 歌名
    date_tomorrow = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d");
 
    Weather = get_Weather() #獲取當天天氣資訊
    Weather_text = Weather["text"] #獲取當天天氣文字
    Weather_temp = Weather["temp"] #實時獲取當前溫度
    Weather_feelsLike = Weather["feelsLike"] #獲取當前體感溫度
 
    Weather_3d_day = get_3d_Weather(1)  # 獲取當天的預報天氣
    Weather_3d_day_tempMax = Weather_3d_day["tempMax"] #獲取當天預報最高溫度
    Weather_3d_day_tempMin = Weather_3d_day["tempMin"] #獲取當天預報最低溫度
    Weather_3d_day_uvIndex = Weather_3d_day["uvIndex"] #獲取當天紫外線強度
 
    Weather_3d_tomorrow = get_3d_Weather(0)  # 獲取明天天氣
    Weather_3d_tomorrow_textDay = Weather_3d_day["textDay"]  # 獲取第二天天氣文字
    Weather_3d_tomorrow_tempMax = Weather_3d_day["tempMax"]  # 獲取第二天預報最高溫度
    Weather_3d_tomorrow_tempMin = Weather_3d_day["tempMin"]  # 獲取第二天預報最低溫度
    Weather_3d_tomorrow_uvIndex = Weather_3d_day["uvIndex"]  # 獲取第二天紫外線強度
    # 獲取舔狗日記
 
    tiangou = get_tiangou();
 
    cur_time = time.time()
    #print(cur_time)
    local_tz = pytz.timezone("Asia/Shanghai")
    local_time = datetime.datetime.fromtimestamp(cur_time, tz=local_tz).hour
    # print(local_time)
 
    Ncov_zz = ncov();    
    Ncov_city = Ncov_zz["city"];
    # confirm 確診病例數量
    Ncov_confirm = Ncov_zz["confirm"];
    # curConfirm 當前確診數量
    Ncov_curConfirm = Ncov_zz["curConfirm"];
    # died  死亡數量
    # heal  治癒數量
    Ncov_heal = Ncov_zz["heal"];
    # asymptomatic 無癥狀感染數量
    # nCoV_news_mid = nCoV_news(0);  # 獲取疫情中風險地區
    # time.sleep(1000)
    nCoV_news_num = nCoV_news(1);#獲取全國疫情數據
    # time.sleep(1000)
    # nCoV_news_high = nCoV_news(2);  # 獲取疫情高風險地區
    currentConfirmedCount  = nCoV_news_num["currentConfirmedCount"]#現存確診人數
    seriousCount = nCoV_news_num["seriousCount"] #現存無癥狀
    beijing_Time = datetime.datetime.fromtimestamp(cur_time, tz=local_tz).strftime("%Y-%m-%d %H:%M:%S");
 
    Ncov_desp = ("\n| -------- |全國疫情實時播報|----------------: |\n"+
    "截至北京時間 "+beijing_Time+"\n"+
    "全國現存確診病例:" + str(currentConfirmedCount)+"\n"+
    "全國現存無癥狀病例:" + str(seriousCount) + "\n" +
    Ncov_city +"現存確診病例:" + str(Ncov_curConfirm)  + ""
                 )
 
 
    desp_Weather_temp_text = "";
    desp_Weather_text = "";
    desp_Weather_3d_tomorrow_textDay_text = "";
    desp_Weather_3d_day_tempMax_text = "";
    desp_Weather_3d_tomorrow_tempMax_text = "";
    desp_day = "";
    desp_tomorrow = "";
    desp_Weather_3d_day_uvIndex = "";
 
    # 晚上八點 查詢第二天天氣情況,然後根據當前時間,訂製化推送當前提醒
    if (local_time >= 20 and local_time <= 23):
        # 如果有雨,不校驗最高溫度
        # 判斷天氣
        if ("" in Weather_3d_tomorrow_textDay):
            if Weather_3d_tomorrow_textDay.__eq__("大雨"):
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
                desp_Weather_3d_tomorrow_textDay_text = "\n明天"+ Weather_3d_tomorrow_textDay + ",傻瓜,記得帶傘,記得早點出門,晚上早點睡\n"
            elif Weather_3d_tomorrow_textDay.__eq__("中雨"):
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
                desp_Weather_3d_tomorrow_textDay_text = "\n明天" + Weather_3d_tomorrow_textDay + ",傻瓜,記得帶傘,記得早點出門,晚上早點睡\n"
            elif Weather_3d_tomorrow_textDay.__eq__("雷陣雨"):
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
                desp_Weather_3d_tomorrow_textDay_text = "\n明天" + Weather_3d_tomorrow_textDay + ",小心打雷,抱抱傻瓜,不怕不怕\n"
            else:
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
                desp_Weather_3d_tomorrow_textDay_text = "\n明天" + Weather_3d_tomorrow_textDay + ",記得帶傘,請注意天氣\n"
        # 沒雨的情況下,根據溫度提醒明天天氣
        else:
            desp_Weather_3d_tomorrow_textDay_text = "\n";
            if (int(Weather_3d_tomorrow_tempMax) >= 33):
                desp_Weather_3d_tomorrow_tempMax_text = "\n明天天氣較熱,注意防晒!\n"
            else:
                desp_Weather_3d_tomorrow_tempMax_text = "\n";
 
        desp_tomorrow = (
                    "明天 " + date_tomorrow + "\n天氣:" + Weather_3d_tomorrow_textDay + desp_Weather_3d_tomorrow_textDay_text +
                    "明天最高溫度:" + Weather_3d_tomorrow_tempMax + "℃。" + desp_Weather_3d_tomorrow_tempMax_text +
                    "明天最低溫度:" + Weather_3d_tomorrow_tempMin + "℃。"
                    );
    elif (local_time >= 0 and local_time < 20):
        # desp_Weather_3d_tomorrow_textDay_text = "\n";
        # desp_Weather_3d_tomorrow_tempMax_text = "\n";
        # 判斷當前溫度
        if (int(Weather_temp) >= 33):
            if (8 < local_time < 16):
                desp_Weather_temp_text = ",天氣有點熱喔!\n"
            else:
                desp_Weather_temp_text = "。\n";
        else:
            desp_Weather_temp_text = "。\n";
 
        # 判斷紫外線等級
        if (8 <= local_time < 16):
            if (4 < int(Weather_3d_day_uvIndex) <= 6):
                desp_Weather_3d_day_uvIndex = "\n今天紫外線等級" + Weather_3d_day_uvIndex + ",適合戶外運動。\n"
            elif (6 < int(Weather_3d_day_uvIndex) <= 9):
                desp_Weather_3d_day_uvIndex = "\n今天紫外線等級" + Weather_3d_day_uvIndex + ",請注意防晒。\n"
            elif (9 < int(Weather_3d_day_uvIndex)):
                desp_Weather_3d_day_uvIndex = "\n今天紫外線等級" + Weather_3d_day_uvIndex + ",寶,外邊太曬了,能不出去就不要出去了。\n"
            else:
                desp_Weather_3d_day_uvIndex = "\n";
        else:
            desp_Weather_3d_day_uvIndex = "\n";
 
            # 判斷當天是否有雨,有雨不判斷當天最高溫度
            Weather_text = ""
        if ("" in Weather_text):
            if Weather_text.__eq__("大雨"):
                desp_Weather_3d_day_tempMax_text = "\n";
                desp_Weather_text = "\n當前有" + Weather_text + ",傻瓜,趕緊避雨,不要再外出啦\n"
            elif Weather_text.__eq__("中雨"):
                desp_Weather_3d_day_tempMax_text = "\n"
                desp_Weather_text = "\n當前有" + Weather_text + ",傻瓜,趕緊避雨,不要再外出啦\n"
            elif Weather_text.__eq__("雷陣雨"):
                desp_Weather_3d_day_tempMax_text = "\n"
                desp_Weather_text = "\n當前有" + Weather_text + ",小心打雷,抱抱傻瓜,不怕不怕\n"
            else:
                desp_Weather_3d_day_tempMax_text = "\n"
                desp_Weather_text = "\n當前有" + Weather_text + ",請注意天氣\n"
        else:
            desp_Weather_text = "\n";
            # 判斷當天最高溫度
            if (int(Weather_3d_day_tempMax) >= 33):
                # 下午16點以後不用提示
                if (local_time > 16):
                    desp_Weather_3d_day_tempMax_text = "\n";
                else:
                    desp_Weather_3d_day_tempMax_text = "\n今天天氣較熱,注意防晒!\n"
            else:
                desp_Weather_3d_day_tempMax_text = "\n";
 
        desp_day = (
                "當前天氣:" + Weather_text + desp_Weather_text +
                "當前溫度:" + Weather_temp + "" + desp_Weather_temp_text +
                "今天最高溫度:" + Weather_3d_day_tempMax + "℃。" + desp_Weather_3d_day_tempMax_text +
                "最低溫度:" + Weather_3d_day_tempMin + "℃。" + desp_Weather_3d_day_uvIndex # 紫外線 16點後不提示
            + "\n" +wyy_content + "\n來自:網易雲音樂《" + wyy_source + "" +
                "\n| -----------------舔狗日記-----------------: |\n" +
                tiangou + "\n來自:舔狗日記\n"
 
        );
    ##以下是通知內容!
    desp = "蘇州\n" + desp_day + desp_tomorrow + Ncov_desp;
    return desp;
 
 
# 程式入口,消息推送
def main():
    title = '每日推送';
    desp = get_desp();
    #url = f"//sctapi.ftqq.com/{SendKey}.send?title={title}&desp={desp}&openid={userid}";    
    token = SendKey #在pushpush網站中可以找到    
    content = desp #改成你要的正文內容
    pushurl = '//www.pushplus.plus/send'
    data = {
    "token":token,
    "title":title,
    "content":content
    }
    body=json.dumps(data).encode(encoding='utf-8')
    headers = {'Content-Type':'application/json'}
    requests.post(pushurl,data=body,headers=headers)
    res = requests.post(pushurl);
    if res.status_code == 200:
        print("成功!")
    else:
       title = "天氣推送失敗!"
       ##desp = "尊敬的管理員,消息推送失敗\n推送日誌"+res.json();
       print(res.status_code)
       #url = f"//sctapi.ftqq.com/{SendKey}.send?title={title}&desp={desp}&openid={adminUserId}";
       #res = requests.post(url);
       print("錯誤日誌推送成功 !")
 
 
 
 
def main_handler(event, context):
   main()
 
if __name__ == '__main__':
   main()

詳細程式碼