最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Python實(shí)現(xiàn)智能天氣提醒助手

 更新時(shí)間:2025年05月28日 11:02:48   作者:嘆一曲當(dāng)時(shí)只道是尋常  
這篇文章主要來(lái)和大家分享一個(gè)實(shí)用的Python天氣提醒助手開(kāi)發(fā)方案,這個(gè)工具可以方便地集成到青龍面板或其他調(diào)度框架中使用,有需要的小伙伴可以參考一下

項(xiàng)目概述

今天分享一個(gè)實(shí)用的Python天氣提醒助手開(kāi)發(fā)方案,這個(gè)工具可以方便地集成到青龍面板或其他調(diào)度框架中使用。助手能獲取實(shí)時(shí)天氣和24小時(shí)預(yù)報(bào),并通過(guò)AI生成貼心的生活建議,最后推送通知給用戶。

核心功能

實(shí)時(shí)天氣查詢 - 通過(guò)阿里云API獲取當(dāng)前天氣數(shù)據(jù)

天氣預(yù)報(bào)獲取 - 查詢24小時(shí)天氣變化情況

AI智能建議 - 基于天氣數(shù)據(jù)生成人文關(guān)懷建議

消息推送 - 通過(guò)Bark服務(wù)發(fā)送通知到iOS設(shè)備

技術(shù)實(shí)現(xiàn)

1. 天氣API集成

def now_weather():
    try:
        host = 'https://ali-weather.showapi.com'
        path = '/hour24'
        appcode = os.getenv("AppCode")
        querys = 'area=xxx'
        url = host + path + '?' + querys
        headers = {'Authorization': 'APPCODE ' + appcode}
        resp = requests.get(url, headers=headers)
        resp.raise_for_status()
        return resp.json()

2. AI建議生成

def get_ai_advice(prompt):
    try:
        client = OpenAI(
            base_url=os.getenv("BaseURL"),
            api_key=os.getenv("APIKEY")
        )
        response = client.chat.completions.create(
            model=os.getenv("MODEL"),
            messages=[
                {"role": "assistant", "content": "你是一個(gè)天氣助手..."},
                {"role": "user", "content": prompt},
            ],
        )
        return response.choices[0].message.content

3. 消息推送

def bark(title: str, content: str) -> None:
    BARK_PUSH = os.getenv("BARK_PUSH")
    url = f'https://api.day.app/{BARK_PUSH}' if not BARK_PUSH.startswith("http") else BARK_PUSH
    data = {"title": title, "body": content}
    response = requests.post(url, data=json.dumps(data), headers=headers, timeout=15).json()

環(huán)境配置

使用時(shí)需要配置以下環(huán)境變量:

AppCode        # 阿里云API的AppCode
BaseURL        # OpenAI API地址
APIKEY         # OpenAI API密鑰
MODEL          # 使用的AI模型
BARK_PUSH      # Bark推送地址或設(shè)備碼

使用方法

if __name__ == "__main__":
    advice = main()  # 獲取天氣建議
    bark("天氣情況", advice)  # 推送通知

完整代碼

import logging
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 配置日志
logger = logging.getLogger('weather')
import requests, json, os, re
from datetime import datetime
from openai import OpenAI

def now_weather():
    try:
        host = 'https://ali-weather.showapi.com'
        path = '/hour24'
        appcode = os.getenv("AppCode")
        querys = 'area=xxx'
        url = host + path + '?' + querys
        headers = {
            'Authorization': 'APPCODE ' + appcode
        }
        resp = requests.get(url, headers=headers)
        resp.raise_for_status()
        return resp.json()
    except Exception as e:
        log.error(f"獲取當(dāng)前天氣失敗: {str(e)}")
        return None

def get_hour24():
    try:
        host = 'https://ali-weather.showapi.com'
        path = '/hour24'
        appcode = os.getenv("AppCode")
        querys = 'area=xxx'
        url = host + path + '?' + querys
        headers = {
            'Authorization': 'APPCODE ' + appcode
        }
        resp = requests.get(url, headers=headers)
        resp.raise_for_status()
        return resp.json()
    except Exception as e:
        log.error(f"獲取24小時(shí)天氣失敗: {str(e)}")
        return None
   
def current_time():
    datiem = datetime.now()
    return datiem.strftime("%Y-%m-%d %H:%M:%S")

def get_ai_advice(prompt):
    try:
        client = OpenAI(
            base_url=os.getenv("BaseURL"),  # 使用配置的base_url
            api_key=os.getenv("APIKEY")  # 使用配置的api_key
        )
        response = client.chat.completions.create(
            model=os.getenv("MODEL"),
            messages=[
                {"role": "assistant", "content": "你是一個(gè)天氣助手,根據(jù)實(shí)際數(shù)據(jù),給用戶精準(zhǔn)的天氣數(shù)據(jù)總結(jié)和人文化的生活建議。例如:明天天氣小雨,和今天溫差較大,注意保暖,同時(shí)伴有大風(fēng),注意安全,睡覺(jué)前記得關(guān)緊門(mén)窗。"},
                {
                    "role": "user",
                    "content": prompt,
                },
            ],
        )
        return response.choices[0].message.content
    except Exception as e:
        log.error(f"獲取AI建議失敗: {str(e)}")
        return "無(wú)法獲取AI建議"


def main():
    current_weather = now_weather()
    forecast_weather = get_hour24()
    
    promot = f"""
    當(dāng)前時(shí)間是:{current_time()}
    當(dāng)前天氣情況:{current_weather}
    24小時(shí)天氣預(yù)報(bào):{forecast_weather}
    注意:
    1. 請(qǐng)根據(jù)實(shí)際數(shù)據(jù),給用戶精準(zhǔn)的天氣數(shù)據(jù)總結(jié)和人文化的生活建議。
    2. 請(qǐng)不要使用markdown格式輸出。盡量口語(yǔ)化
    """
    print(promot)
    return get_ai_advice(promot)


push_config = {
    'BARK_PUSH': '',                    # bark IP 或設(shè)備碼,例:https://api.day.app/DxHcxxxxxRxxxxxxcm/
    'BARK_ARCHIVE': '',                 # bark 推送是否存檔
    'BARK_GROUP': '',                   # bark 推送分組
    'BARK_SOUND': '',                   # bark 推送聲音
    'BARK_ICON': '',                    # bark 推送圖標(biāo)
    'BARK_LEVEL': '',                   # bark 推送時(shí)效性
    'BARK_URL': '',                     # bark 推送跳轉(zhuǎn)URL
}


def bark(title: str, content: str) -> None:
    """
    使用 bark 推送消息。
    """
    BARK_PUSH = os.getenv("BARK_PUSH")
    if not BARK_PUSH:
        print("bark 服務(wù)的 BARK_PUSH 未設(shè)置!!\n取消推送")
        return
    print("bark 服務(wù)啟動(dòng)")

    if BARK_PUSH.startswith("http"):
        url = f'{BARK_PUSH}'
    else:
        url = f'https://api.day.app/{BARK_PUSH}'

    bark_params = {
        "BARK_ARCHIVE": "isArchive",
        "BARK_GROUP": "group",
        "BARK_SOUND": "sound",
        "BARK_ICON": "icon",
        "BARK_LEVEL": "level",
        "BARK_URL": "url",
    }
    data = {
        "title": title,
        "body": content,
    }
    for pair in filter(
        lambda pairs: pairs[0].startswith("BARK_")
        and pairs[0] != "BARK_PUSH"
        and pairs[1]
        and bark_params.get(pairs[0]),
        push_config.items(),
    ):
        data[bark_params.get(pair[0])] = pair[1]
    headers = {"Content-Type": "application/json;charset=utf-8"}
    response = requests.post(
        url=url, data=json.dumps(data), headers=headers, timeout=15
    ).json()

    if response["code"] == 200:
        print("bark 推送成功!")
    else:
        print("bark 推送失??!")


advice = main()
print(advice)
bark("天氣情況",advice)

項(xiàng)目特點(diǎn)

模塊化設(shè)計(jì) - 各功能解耦,便于維護(hù)和擴(kuò)展

異常處理 - 關(guān)鍵操作都有try-catch保護(hù)

環(huán)境變量配置 - 敏感信息不寫(xiě)死在代碼中

輕量級(jí) - 不依賴復(fù)雜框架,Python原生實(shí)現(xiàn)

這個(gè)天氣助手可以方便地集成到各種定時(shí)任務(wù)系統(tǒng)中,為你的日常生活提供貼心的天氣提醒服務(wù)。根據(jù)實(shí)際需要,你還可以擴(kuò)展更多的天氣API或消息推送方式。

以上就是基于Python實(shí)現(xiàn)智能天氣提醒助手的詳細(xì)內(nèi)容,更多關(guān)于Python智能天氣提醒的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

虞城县| 南木林县| 龙口市| 梅河口市| 晋宁县| 敦煌市| 许昌县| 西昌市| 宁陵县| 容城县| 嘉禾县| 伊春市| 鲁甸县| 南充市| 卢龙县| 新蔡县| 棋牌| 改则县| 瑞丽市| 长寿区| 平湖市| 固镇县| 昂仁县| 丰台区| 铁岭县| 平江县| 苗栗县| 东安县| 百色市| 大同县| 竹溪县| 马龙县| 施甸县| 安远县| 宁德市| 台中县| 泸西县| 乐昌市| 七台河市| 淄博市| 鄂尔多斯市|