主要思路
- 从wxpy获取好友列表,也可发给指定好友
- 创建定时器,也可以随时发送
- 定时器触发函数
- 函数执行,遍历好友列表
- 好友对象执行带参函数,参数为该好友城市
- 函数中请求百度天气接口,得到该好友对应天气数据,解析处理数据,发送天气信息,完成该对象发送。
- 遍历结束,发送完毕
前期准备
- 注意requests这个函数是在python安装路径的Scripts中安装,我们可以cmd命令进入这个路径去安装
完整代码实现
from wxpy import *
import requests
from datetime import datetime
import time
from apscheduler.schedulers.blocking import BlockingScheduler
bot = Bot(cache_path=True)
tuling = Tuling(api_key='4a0488cdce684468b95591a641f0971d')
location = '深圳'
def send_weather(location):
path ='http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'
url = path % location
response = requests.get(url)
result = response.json()
if result['error'] !=0:
location ='深圳'
url = path % location
response = requests.get(url)
result = response.json()
str0 = (' 宝宝!这是明天的天气预报!\n 来自您贴心的小棉袄 : 李老师\n')
results = result['results']
data1 = results[0]
city = '深圳'
str1 =' 你的城市: %s\n' % city
pm25 = data1['pm25']
str2 =' Pm值 : %s\n' % pm25
pm25 = int(pm25)
if pm25 =='':
pm25 =0
if 0 <= pm25 <35:
pollution ='优'
elif 35 <= pm25 <75:
pollution ='良'
elif 75 <= pm25 <115:
pollution ='轻度污染'
elif 115 <= pm25 <150:
pollution ='中度污染'
elif 150 <= pm25 <250:
pollution ='重度污染'
elif pm25 >=250:
pollution ='严重污染'
str3 =' 污染指数: %s\n' % pollution
result1 = results[0]
weather_data = result1['weather_data']
data = weather_data[1]
datetime = data['date']
temperature = data['temperature']
str4 =' 明天温度: %s%s\n' % (datetime,temperature)
wind = data['wind']
str5 =' 风向 : %s\n' % wind
weather = data['weather']
str6 =' 天气 : %s\n' % weather
message = data1['index']
str8 =' 穿衣 : %s\n' % message[0]['des']
str9 =' 我很贴心: %s\n' % message[2]['des']
str10 =' 运动 : %s\n' % message[3]['des']
str11 =' 紫外线 : %s\n' % message[4]['des']
str12="\n爱你爱你爱你muamua~\n"
str = str0 + str1 + str2 + str3 + str4 + str5 + str6 + str8 + str9 + str10 + str11+ str12
return str
friend = bot.friends().search('ZzZero丶')[0]
print(friend)
def send_message():
location = '深圳'
friend.send(send_weather(location))
bot.file_helper.send(send_weather(location))
bot.file_helper.send('发送完毕')
print('start')
send_message()
效果展示