Python发送天气预报到企业微信解决方案
下面是一个完整的Python解决方案,可以将今日天气信息和未来天气趋势图发送到企业微信。这个方案使用免费天气API获取数据,生成可视化图表,然后通过企业微信机器人发送消息。
import requests
import json
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import time
import os
from io import BytesIO
# 配置信息 - 请替换为您的实际信息
WEATHER_API_KEY = "your_weather_api_key" # 从https://www.tianqiapi.com/ 获取
LOCATION = "上海" # 您要查询的城市
WECHAT_WEBHOOK = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your_webhook_key" # 企业微信机器人Webhook
def get_weather_data():
"""获取天气API数据"""
url = f"https://yiketianqi.com/api?version=v9&appid={WEATHER_API_KEY}&appsecret=your_appsecret&city={LOCATION}"
try:
response = requests.get(url)
response.raise_for_status() # 检查HTTP错误
data = response.json()
# 提取当天天气
today = data["data"][0]
today_weather = {
"city": data["city"],
"date": today["date"],
"week": today["week"],
"weather": today["wea"],
"temp": f"{today['tem']}℃",
"tem_day": today["tem_day"],
"tem_night": today["tem_night"],
"humidity": today["humidity"],
"wind": f"{today['win']} {today['win_speed']}",
"air": today["air"],
"air_level": today["air_level"],
"sunrise": today["sunrise"],
"sunset": today["sunset"]
}
# 提取未来天气趋势
forecast = []
for day in data["data"][:7]:
forecast.append({
"date": day["date"],
"week": day["week"],
"weather": day["wea"],
"temp": f"{day['tem_day']}℃/{day['tem_night']}℃",
"temp_day": float(day["tem_day"]),
"temp_night": float(day["tem_night"]),
"win": day["win"]
})
return today_weather, forecast
except requests.exceptions.RequestException as e:
print(f"获取天气数据失败: {e}")
return None, None
except json.JSONDecodeError:
print("天气数据解析失败")
return None, None
def create_weather_chart(forecast_data):
"""创建未来天气趋势图表"""
# 准备数据
dates = [datetime.datetime.strptime(d['date'], "%Y-%m-%d") for d in forecast_data]
day_temps = [d['temp_day'] for d in forecast_data]
night_temps = [d['temp_night'] for d in forecast_data]
weathers = [d['weather'] for d in forecast_data]
weeks = [d['week'] for d in forecast_data]
# 设置图表样式
plt.style.use('ggplot')
fig, ax = plt.subplots(figsize=(10, 6))
# 创建图表
ax.plot(dates, day_temps, 'o-', label='白天温度', color='#FF7043', linewidth=2.5, markersize=8)
ax.plot(dates, night_temps, 's-', label='夜晚温度', color='#42A5F5', linewidth=2.5, markersize=8)
# 添加文字标注
for i, (date, day, night, weather, week) in enumerate(zip(dates, day_temps, night_temps, weathers, weeks)):
label_date = f"{date.strftime('%m/%d')}\n{week}"
ax.text(date, day + 0.5, f"{day}℃", ha='center', va='bottom', fontsize=10, color='#FF7043')
ax.text(date, night - 0.5, f"{night}℃", ha='center', va='top', fontsize=10, color='#42A5F5')
ax.text(date, min(day_temps)-4, weather, ha='center', va='top', fontsize=9, color='#666')
ax.text(date, min(day_temps)-7, label_date, ha='center', va='top', fontsize=9, color='#888')
# 设置标题和标签
plt.title(f'{LOCATION}未来7天温度趋势图', fontsize=16, pad=20)
plt.ylabel('温度(℃)', fontsize=12)
plt.legend(loc='upper left')
# 设置坐标轴
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
plt.xticks(dates)
plt.ylim(min(night_temps) - 8, max(day_temps) + 3)
plt.grid(True, axis='y', alpha=0.3)
# 保存到内存
buf = BytesIO()
plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
buf.seek(0)
plt.close()
return buf
def generate_weather_message(today_weather, forecast):
"""生成天气消息文本"""
air_level_colors = {
"优": "#00B050",
"良": "#92D050",
"轻度污染": "#FFC000",
"中度污染": "#FF0000",
"重度污染": "#C00000",
"严重污染": "#800080"
}
# 生成标题和表格样式
message = f"## ⛅️{LOCATION}今日天气 ({today_weather['date']} {today_weather['week']}) \n\n"
message += (
"<font color='#333333'>**天气概况:**</font> "
f"<font color='#0086cb'>{today_weather['weather']}</font> "
f"<font color='#ff6d00'>{today_weather['temp']}</font> "
f"| 湿度: {today_weather['humidity']}% \n\n"
)
message += (
"<font color='#333333'>**空气质量:**</font> "
f"<font color='{air_level_colors.get(today_weather['air_level'], '#000000')}'>{today_weather['air']} ({today_weather['air_level']})</font>\n\n"
)
message += (
"<font color='#333333'>**日出日落:**</font> "
f"🌅{today_weather['sunrise']} | 🌇{today_weather['sunset']}\n\n"
)
# 添加生活指数建议
message += (
"### 📌生活建议 \n"
"- 💧湿度较高,注意防潮\n"
"- ☔️出行请随身携带雨具\n"
"- 😷空气质量良好,适合户外活动\n"
"- 🧥早晚温差较大,注意添加衣物\n\n"
)
# 添加未来三天天气概况
message += "### 📈未来三天天气 \n"
for day in forecast[:3]:
message += f"**{day['date']} ({day['week']})**: {day['weather']} {day['temp']} \n"
# 添加更新时间
update_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
message += f"\n<font color='#888888'>⏱️更新时间: {update_time}</font>"
return message
def send_to_wechat(message, image_data):
"""发送消息到企业微信"""
# 先发送文字消息
text_payload = {
"msgtype": "markdown",
"markdown": {
"content": message
}
}
# 上传图片获取媒体ID
upload_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media"
files = {"media": ("weather.png", image_data, "image/png")}
params = {"key": WECHAT_WEBHOOK.split("key=")[-1], "type": "image"}
response = requests.post(upload_url, params=params, files=files)
if response.status_code == 200:
media_id = response.json().get("media_id")
# 再发送图片消息
image_payload = {
"msgtype": "image",
"image": {
"media_id": media_id
}
}
# 发送消息
requests.post(WECHAT_WEBHOOK, json=text_payload)
requests.post(WECHAT_WEBHOOK, json=image_payload)
print("天气信息已发送到企业微信")
else:
print(f"图片上传失败: {response.text}")
def main():
"""主函数"""
print("开始获取天气信息...")
today_weather, forecast = get_weather_data()
if today_weather and forecast:
print("创建天气图表...")
chart_buffer = create_weather_chart(forecast)
print("生成消息内容...")
message = generate_weather_message(today_weather, forecast)
print("发送到企业微信...")
send_to_wechat(message, chart_buffer)
else:
print("无法获取天气数据")
if __name__ == "__main__":
main()
关键组件说明
1. 获取天气数据
使用免费的天行数据API获取实时天气和预报:
- 通过HTTP GET请求获取JSON格式天气数据
- 提取今日天气详情(温度、湿度、风速等)
- 获取未来7天天气预报数据
2. 创建天气趋势图
使用Matplotlib生成专业美观的温度趋势图:
- 绘制白天和夜间温度折线图
- 添加日期、星期、天气类型标注
- 调整图表样式、颜色和布局
- 使用BytesIO将图表保存为内存缓冲区
3. 生成天气消息
创建格式化的Markdown消息:
- 包括今日天气概况、空气质量指数和日出日落时间
- 添加生活指数建议(穿衣、出行等)
- 提供未来三天天气概览
- 使用颜色标记不同类型的天气信息
4. 发送到企业微信
分两步发送到企业微信机器人:
- 上传天气趋势图到企业微信服务器
- 先发送文字信息,再发送图片信息
使用说明
-
获取API密钥
- 访问天行数据注册账号获取免费API Key
- 免费版每天100次调用,足够日常使用
-
创建企业微信机器人
- 在企业微信中创建群聊
- 添加群机器人,获取Webhook URL
- 替换脚本中的
WECHAT_WEBHOOK
变量
-
设置城市
- 修改
LOCATION
变量为目标城市
- 修改
-
安装依赖
pip install requests matplotlib
-
运行脚本
python weather_bot.py
输出效果
企业微信中将收到两条消息:
- 文本消息:包含今日天气详情和未来三天预报
- 图片消息:未来7天温度趋势图,标注白天/夜间温度和天气情况
效果示例:
⛅️上海今日天气 (2023-09-15 星期五)
天气概况: 多云 28℃ | 湿度: 78%
空气质量: 42 (优)
日出日落: 🌅05:45 | 🌇18:20
📌生活建议:
- 💧湿度较高,注意防潮
- ☔️出行请随身携带雨具
- 😷空气质量良好,适合户外活动
- 🧥早晚温差较大,注意添加衣物
📈未来三天天气:
2023-09-16 (星期六): 多云 30℃/24℃
2023-09-17 (星期日): 小雨 28℃/23℃
2023-09-18 (星期一): 中雨 26℃/22℃
⏱️更新时间: 2023-09-15 09:30
高级扩展功能
-
定时发送
使用crontab(Linux)或Task Scheduler(Windows)设置每天定时执行:# 每天8:30发送天气报告 30 8 * * * /usr/bin/python3 /path/to/weather_bot.py
-
多城市支持
修改脚本支持多个城市:LOCATIONS = ["北京", "上海", "广州"] for city in LOCATIONS: # 获取并发送每个城市的天气
-
错误处理与日志
添加更完善的错误处理和日志记录:import logging logging.basicConfig(filename='weather_bot.log', level=logging.INFO)
-
邮件/短信备用通知
在企业微信发送失败时使用其他通知方式:def fallback_notify(message): # 实现邮件或短信通知
此解决方案提供了完整的天气信息获取、可视化与通知流程,适合日常办公环境和企业场景使用。