基于Python實(shí)現(xiàn)智能天氣提醒助手
項目概述
今天分享一個實(shí)用的Python天氣提醒助手開發(fā)方案,這個工具可以方便地集成到青龍面板或其他調(diào)度框架中使用。助手能獲取實(shí)時天氣和24小時預(yù)報,并通過AI生成貼心的生活建議,最后推送通知給用戶。
核心功能
實(shí)時天氣查詢 - 通過阿里云API獲取當(dāng)前天氣數(shù)據(jù)
天氣預(yù)報獲取 - 查詢24小時天氣變化情況
AI智能建議 - 基于天氣數(shù)據(jù)生成人文關(guān)懷建議
消息推送 - 通過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": "你是一個天氣助手..."},
{"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推送地址或設(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小時天氣失敗: {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í)際數(shù)據(jù),給用戶精準(zhǔn)的天氣數(shù)據(jù)總結(jié)和人文化的生活建議。例如:明天天氣小雨,和今天溫差較大,注意保暖,同時伴有大風(fēng),注意安全,睡覺前記得關(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"""
當(dāng)前時間是:{current_time()}
當(dāng)前天氣情況:{current_weather}
24小時天氣預(yù)報:{forecast_weather}
注意:
1. 請根據(jù)實(shí)際數(shù)據(jù),給用戶精準(zhǔn)的天氣數(shù)據(jù)總結(jié)和人文化的生活建議。
2. 請不要使用markdown格式輸出。盡量口語化
"""
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 推送時效性
'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ù)啟動")
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)
項目特點(diǎn)
模塊化設(shè)計 - 各功能解耦,便于維護(hù)和擴(kuò)展
異常處理 - 關(guān)鍵操作都有try-catch保護(hù)
環(huán)境變量配置 - 敏感信息不寫死在代碼中
輕量級 - 不依賴復(fù)雜框架,Python原生實(shí)現(xiàn)
這個天氣助手可以方便地集成到各種定時任務(wù)系統(tǒng)中,為你的日常生活提供貼心的天氣提醒服務(wù)。根據(jù)實(shí)際需要,你還可以擴(kuò)展更多的天氣API或消息推送方式。
以上就是基于Python實(shí)現(xiàn)智能天氣提醒助手的詳細(xì)內(nèi)容,更多關(guān)于Python智能天氣提醒的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python爬蟲系列Selenium定向爬取虎撲籃球圖片詳解
這篇文章主要介紹了python爬蟲系列Selenium定向爬取虎撲籃球圖片詳解,具有一定參考價值,喜歡的朋友可以了解下。2017-11-11
python實(shí)現(xiàn)超簡單的視頻對象提取功能
這篇文章主要給大家介紹了關(guān)于利用python實(shí)現(xiàn)超簡單的視頻對象提取功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06
Python 查找list中的某個元素的所有的下標(biāo)方法
今天小編就為大家分享一篇Python 查找list中的某個元素的所有的下標(biāo)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06

