基于Python实现定时自动给微信好友发送天气预报


Posted in Python onOctober 25, 2018

效果图

基于Python实现定时自动给微信好友发送天气预报

from wxpyimport *
import requests
from datetimeimport datetime
import time
from apscheduler.schedulers.blockingimport BlockingScheduler#定时框架
bot = Bot(cache_path=True)
tuling = Tuling(api_key=你的api')#机器人api
def send_weather(location):
#准备url地址
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 = ('  早上好!这是今天的天气预报!……机器人:PyChatBot\n')
results = result['results']
# 取出数据字典
data1 = results[0]
# 取出城市
city = data1['currentCity']
str1 ='  你的城市: %s\n' % city
# 取出pm2.5值
pm25 = data1['pm25']
str2 ='  Pm值  : %s\n' % pm25
# 将字符串转换为整数 否则无法比较大小
if pm25 =='':
pm25 =0
pm25 =int(pm25)
# 通过pm2.5的值大小判断污染指数
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[0]
temperature_now = data['date']
str4 ='  当前温度: %s\n' % temperature_now
wind = data['wind']
str5 ='  风向  : %s\n' % wind
weather = data['weather']
str6 ='  天气  : %s\n' % weather
str7 ='  温度  : %s\n' % data['temperature']
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']
str = str0 + str1 + str2 + str3 + str4 + str5 + str6 + str7 + str8 + str9 + str10 + str11
return str
#好友列表
my_friends = []
my_friends = bot.friends()
my_friends.pop(0)
#发送函数
def send_message():
#给全体好友发送
for friendin my_friends:
friend.send(send_weather(friend.city))
#发送成功通知我
bot.file_helper.send(send_weather('濮阳'))
bot.file_helper.send('发送完毕')
#定时器
print('star')
sched = BlockingScheduler()
sched.add_job(send_message,'cron',month='1-12',day='1-31',hour=5,minute =30)
sched.start()

具体操作:

首先导入wxpy、图灵机器人和定时器Apscheduler,定时器用来定时群发。

具体pip操作建议百度。

使用百度的一个天气接口得到json数据。

主要思路:

1.从wxpy获取好友列表

2.创建定时器

3.定时器触发函数

4.函数执行,遍历好友列表

5.好友对象执行带参函数,参数为该好友城市

6.函数中请求百度天气接口,得到该好友对应天气数据,解析处理数据,发送天气信息,完成该对象发送。

7.遍历结束,发送完毕

缺陷:打包为exe文件之后启动失败,原因是定时器找不到trigger,要想解决需要查看Apscheduler相关资料。

解决方法:换一种定时器。

编译器上正常执行。

打包为exe之后,可以很方便发给别人使用。扫码登录后每天早上5:30会自动给所有好友发送效果图中的天气预报。

PS:下面看下Python实现微信定时发送天气预报

schedule实现定时

import requests
from requests import exceptions
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
from wxpy import *
import schedule
import time
bot=Bot(cache_path=True) #登陆网页微信,并保存登陆状态
def sendblogmsg(content):
  #搜索自己的好友,注意中文字符前需要+u
  my_friend = bot.friends().search(u'卿尘')[0]
  my_friend.send(content)
  #my_group = bot.groups().search(u'卿尘')[0]
  #my_group.send(content) #发送天气预报
def job():
  resp=urlopen('http://www.weather.com.cn/weather/101010100.shtml')
  soup=BeautifulSoup(resp,'html.parser')
  tagToday=soup.find('p',class_="tem") #第一个包含class="tem"的p标签即为存放今天天气数据的标签
  try:
    temperatureHigh=tagToday.span.string #有时候这个最高温度是不显示的,此时利用第二天的最高温度代替。
  except AttributeError as e:
    temperatureHigh=tagToday.find_next('p',class_="tem").span.string #获取第二天的最高温度代替
  temperatureLow=tagToday.i.string #获取最低温度
  weather=soup.find('p',class_="wea").string #获取天气
  contents = '北京' + '\n' + '最高温度:' + temperatureHigh + '\n' + '最低温度:' + temperatureLow + '\n' + '天气:' + weather 
    # result3 = '最低温度:' + temperatureLow
  #print('最低温度:' + temperatureLow)
  #print('最高温度:' + temperatureHigh)
  # print('天气:' + weather)
  sendblogmsg(contents)
#定时
schedule.every().day.at("19:20").do(job) #规定每天12:30执行job()函数
while True:
  schedule.run_pending()#确保schedule一直运行
  time.sleep(1)
bot.join() #保证上述代码持续运行

end

总结

以上所述是小编给大家介绍的基于Python实现定时自动给微信好友发送天气预报,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
Python库urllib与urllib2主要区别分析
Jul 13 Python
Python 中pandas.read_excel详细介绍
Jun 23 Python
Python使用min、max函数查找二维数据矩阵中最小、最大值的方法
May 15 Python
Python学习小技巧总结
Jun 10 Python
树莓派采用socket方式文件传输(python)
Jun 22 Python
Python开发之基于模板匹配的信用卡数字识别功能
Jan 13 Python
Anaconda+vscode+pytorch环境搭建过程详解
May 25 Python
Pandas缺失值2种处理方式代码实例
Jun 13 Python
Python将字典转换为XML的方法
Aug 01 Python
Python unittest装饰器实现原理及代码
Sep 08 Python
matplotlib之pyplot模块之标题(title()和suptitle())
Feb 22 Python
对Keras自带Loss Function的深入研究
May 25 Python
python批量修改图片后缀的方法(png到jpg)
Oct 25 #Python
python bmp转换为jpg 并删除原图的方法
Oct 25 #Python
virtualenv 指定 python 解释器的版本方法
Oct 25 #Python
解决python3读取Python2存储的pickle文件问题
Oct 25 #Python
python 解压pkl文件的方法
Oct 25 #Python
纯用NumPy实现神经网络的示例代码
Oct 24 #Python
Django添加KindEditor富文本编辑器的使用
Oct 24 #Python
You might like
php基础教程 php内置函数实例教程
2012/08/21 PHP
php计算2个日期的差值函数分享
2015/02/02 PHP
php校验表单检测字段是否为空的方法
2015/03/20 PHP
Apache服务器下防止图片盗链的办法
2015/07/06 PHP
php连接微软MSSQL(sql server)完全攻略
2016/11/27 PHP
Laravel6.0.4中将添加计划任务事件的方法步骤
2019/10/15 PHP
跟随鼠标旋转的文字
2006/11/30 Javascript
如何在Mozilla Gecko 用Javascript加载XSL
2007/01/09 Javascript
用jQuery模拟页面加载进度条的实现代码
2011/12/19 Javascript
jQuery 获取浏览器所在的IP地址的小例子
2013/11/08 Javascript
JavaScript判断前缀、后缀是否是空格的方法
2015/04/15 Javascript
文字垂直滚动之javascript代码
2015/07/29 Javascript
jquery树形菜单效果的简单实例
2016/06/06 Javascript
图片懒加载插件实例分享(含解析)
2017/01/09 Javascript
JavaScript实现简单图片轮播效果
2017/08/21 Javascript
关于Mac下安装nodejs、npm和cnpm的教程
2018/04/11 NodeJs
详解如何使用webpack打包JS
2018/06/21 Javascript
[01:18]PWL开团时刻DAY10——一拳超人
2020/11/11 DOTA
使用graphics.py实现2048小游戏
2015/03/10 Python
Python中编写ORM框架的入门指引
2015/04/29 Python
Python IDLE 错误:IDLE''s subprocess didn''t make connection 的解决方案
2017/02/13 Python
python 实现数组list 添加、修改、删除的方法
2018/04/04 Python
PyQt5 QTableView设置某一列不可编辑的方法
2019/06/25 Python
使用Pandas对数据进行筛选和排序的实现
2019/07/29 Python
详解python中各种文件打开模式
2020/01/19 Python
python上传时包含boundary时的解决方法
2020/04/08 Python
如何表示python中的相对路径
2020/07/08 Python
使用Python实现NBA球员数据查询小程序功能
2020/11/09 Python
详解python 条件语句和while循环的实例代码
2020/12/28 Python
用canvas实现图片滤镜效果附演示
2013/11/05 HTML / CSS
英文版餐饮运营管理求职信
2013/11/06 职场文书
技校毕业生自荐信范文
2014/03/07 职场文书
红色故事演讲稿
2014/05/22 职场文书
2015年街道除四害工作总结
2015/05/15 职场文书
Ruby处理YAML和json数据
2022/04/18 Ruby
redis protocol通信协议及使用详解
2022/07/15 Redis