基于Python實現(xiàn)智能天氣提醒助手
項目概述
今天分享一個實用的Python天氣提醒助手開發(fā)方案,這個工具可以方便地集成到青龍面板或其他調(diào)度框架中使用。助手能獲取實時天氣和24小時預報,并通過AI生成貼心的生活建議,最后推送通知給用戶。
核心功能
實時天氣查詢 - 通過阿里云API獲取當前天氣數(shù)據(jù)
天氣預報獲取 - 查詢24小時天氣變化情況
AI智能建議 - 基于天氣數(shù)據(jù)生成人文關(guān)懷建議
消息推送 - 通過Bark服務發(fā)送通知到iOS設備
技術(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": "你是一個天氣助手..."},
{"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)境配置
使用時需要配置以下環(huán)境變量:
AppCode # 阿里云API的AppCode BaseURL # OpenAI API地址 APIKEY # OpenAI API密鑰 MODEL # 使用的AI模型 BARK_PUSH # Bark推送地址或設備碼
使用方法
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"獲取當前天氣失敗: {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小時天氣失敗: {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": "你是一個天氣助手,根據(jù)實際數(shù)據(jù),給用戶精準的天氣數(shù)據(jù)總結(jié)和人文化的生活建議。例如:明天天氣小雨,和今天溫差較大,注意保暖,同時伴有大風,注意安全,睡覺前記得關(guān)緊門窗。"},
{
"role": "user",
"content": prompt,
},
],
)
return response.choices[0].message.content
except Exception as e:
log.error(f"獲取AI建議失敗: {str(e)}")
return "無法獲取AI建議"
def main():
current_weather = now_weather()
forecast_weather = get_hour24()
promot = f"""
當前時間是:{current_time()}
當前天氣情況:{current_weather}
24小時天氣預報:{forecast_weather}
注意:
1. 請根據(jù)實際數(shù)據(jù),給用戶精準的天氣數(shù)據(jù)總結(jié)和人文化的生活建議。
2. 請不要使用markdown格式輸出。盡量口語化
"""
print(promot)
return get_ai_advice(promot)
push_config = {
'BARK_PUSH': '', # bark IP 或設備碼,例:https://api.day.app/DxHcxxxxxRxxxxxxcm/
'BARK_ARCHIVE': '', # bark 推送是否存檔
'BARK_GROUP': '', # bark 推送分組
'BARK_SOUND': '', # bark 推送聲音
'BARK_ICON': '', # bark 推送圖標
'BARK_LEVEL': '', # bark 推送時效性
'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 服務的 BARK_PUSH 未設置!!\n取消推送")
return
print("bark 服務啟動")
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)
項目特點
模塊化設計 - 各功能解耦,便于維護和擴展
異常處理 - 關(guān)鍵操作都有try-catch保護
環(huán)境變量配置 - 敏感信息不寫死在代碼中
輕量級 - 不依賴復雜框架,Python原生實現(xiàn)
這個天氣助手可以方便地集成到各種定時任務系統(tǒng)中,為你的日常生活提供貼心的天氣提醒服務。根據(jù)實際需要,你還可以擴展更多的天氣API或消息推送方式。
以上就是基于Python實現(xiàn)智能天氣提醒助手的詳細內(nèi)容,更多關(guān)于Python智能天氣提醒的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Flask框架運用Axios庫實現(xiàn)前后端交互詳解
Axios 是一個基于promise的HTTP庫,該庫是一個更好的替代ajax向后端發(fā)送數(shù)據(jù)或請求數(shù)據(jù)的前端組件庫。本文通過示例為大家介紹了如何運用Axios庫實現(xiàn)前后端交互,感興趣的可以了解一下2022-12-12
對django 2.x版本中models.ForeignKey()外鍵說明介紹
這篇文章主要介紹了對django 2.x版本中models.ForeignKey()外鍵說明介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
詳解Python如何利用pymysql封裝項目通用的連接和查詢
一個項目通常都需要有數(shù)據(jù)庫,本文就來為大家詳細講講Python如何利用pymysql簡單分裝一個通用的連接,關(guān)閉和查詢,需要的可以參考一下2022-07-07
專家解析Python文件讀寫的理論與實踐(從基礎概念到工程應用)
本文講解Python文件讀寫的基礎與工程實踐,從文件對象、打開與關(guān)閉、上下文管理,到文本與二進制文件讀寫、文件指針、編碼問題及異常處理,輔以豐富代碼示例與性能、安全提示,通過日志分析工具的實際項目案例,展示大文件處理、流式讀取、隨機訪問和編碼容錯的應用方法2026-01-01
對python實現(xiàn)二維函數(shù)高次擬合的示例詳解
今天小編就為大家分享一篇對python實現(xiàn)二維函數(shù)高次擬合的示例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12

