基于Python的智能天气提醒助手开发指南
文章目录
- 🌦️ 基于Python的智能天气提醒助手开发指南
- 📌 项目概述
- 🔧 核心功能
- 🛠️ 技术实现
- 1. 天气API集成
- 2. AI建议生成
- 3. 消息推送
- ⚙️ 环境配置
- 🚀 使用方法
- 📋️ 完整代码
- 📝 项目特点
🌦️ 基于Python的智能天气提醒助手开发指南
📌 项目概述
今天分享一个实用的Python天气提醒助手开发方案,这个工具可以方便地集成到青龙面板或其他调度框架中使用。助手能获取实时天气和24小时预报,并通过AI生成贴心的生活建议,最后推送通知给用户。
🔧 核心功能
- 实时天气查询 - 通过阿里云API获取当前天气数据
- 天气预报获取 - 查询24小时天气变化情况
- AI智能建议 - 基于天气数据生成人文关怀建议
- 消息推送 - 通过Bark服务发送通知到iOS设备
🛠️ 技术实现
1. 天气API集成
def now_weather():try:host = 'https://ali-weather.showapi.com'path = '/hour24'appcode = os.getenv("AppCode")querys = 'area=xxx'url = host + path + '?' + querysheaders = {'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_PUSHdata = {"title": title, "body": content}response = requests.post(url, data=json.dumps(data), headers=headers, timeout=15).json()
⚙️ 环境配置
使用时需要配置以下环境变量:
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 OpenAIdef now_weather():try:host = 'https://ali-weather.showapi.com'path = '/hour24'appcode = os.getenv("AppCode")querys = 'area=xxx'url = host + path + '?' + querysheaders = {'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 Nonedef get_hour24():try:host = 'https://ali-weather.showapi.com'path = '/hour24'appcode = os.getenv("AppCode")querys = 'area=xxx'url = host + path + '?' + querysheaders = {'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 Nonedef 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_urlapi_key=os.getenv("APIKEY") # 使用配置的api_key)response = client.chat.completions.create(model=os.getenv("MODEL"),messages=[{"role": "assistant", "content": "你是一个天气助手,根据实际数据,给用户精准的天气数据总结和人文化的生活建议。例如:明天天气小雨,和今天温差较大,注意保暖,同时伴有大风,注意安全,睡觉前记得关紧门窗。"},{"role": "user","content": prompt,},],)return response.choices[0].message.contentexcept 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. 请根据实际数据,给用户精准的天气数据总结和人文化的生活建议。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 推送跳转URL
}def bark(title: str, content: str) -> None:"""使用 bark 推送消息。"""BARK_PUSH = os.getenv("BARK_PUSH")if not BARK_PUSH:print("bark 服务的 BARK_PUSH 未设置!!\n取消推送")returnprint("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)
📝 项目特点
- 模块化设计 - 各功能解耦,便于维护和扩展
- 异常处理 - 关键操作都有try-catch保护
- 环境变量配置 - 敏感信息不写死在代码中
- 轻量级 - 不依赖复杂框架,Python原生实现
这个天气助手可以方便地集成到各种定时任务系统中,为你的日常生活提供贴心的天气提醒服务。根据实际需要,你还可以扩展更多的天气API或消息推送方式。