基于Python实现定时自动给微信好友发送天气预报
作者:李聪你好 发布时间:2023-09-13 01:24:05
标签: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实现定时自动给微信好友发送天气预报,希望对大家有所帮助
来源:https://www.jianshu.com/p/2c62e684941f


猜你喜欢
- PHP程序员玩转Linux系列文章:1.PHP程序员玩转Linux系列-怎么安装使用CentOS2.PHP程序员玩转Linux系列-lnmp
- yield的功能类似于return,但是不同之处在于它返回的是生成器。生成器生成器是通过一个或多个yield表达式构成的函数,每一个生成器都
- 问题描述:在pyhton脚本中logging.info("hello world")希望输出'hello wor
- 这段时间一直想尝试着在SAE中使用Python,初步选择了Web.py框架做为开发框架,但是可怜SAE上的资料少的可怜,有点问题基本上解决不
- 举个简单的例子:(此仅限于修改change_form页面)原来的时候,change_form_list是包含这些按钮的:因为此页面继承了{%
- 问题简述在 Windows 系统上,我使用 Python 3.11 的 pip 工具安装 lxml 等库时会出现以下报错:error: Mi
- 一、PyTorch 检查模型梯度是否可导当我们构建复杂网络模型或在模型中加入复杂操作时,可能会需要验证该模型或操作是否可导,即模型是否能够优
- 1、异常的传播当在函数中出现异常时,如果在函数中对异常进行了处理,则异常不会再继续传播。如果函数中没有对异常进行处理,则异常会继续向函数调用
- 所谓产品其实最终展现在用户面前的只是界面而已,所谓界面绝大多数时候只包括两个部分:图片、文字。重视界面上的每一个像素和每一个文字是UED的基
- 相信每个前端工程师都有自己喜爱的javascript框架,说情感也好,道信仰也罢,javascript框架带给人的不仅仅是便捷的开发,更有一
- 有时候使用Pytorch训练完模型,在测试数据上面得到的结果令人大跌眼镜。这个时候需要检查一下定义的Model类中有没有 BN 或 Drop
- 1.在HTML5中使用Geolocation.getCurrentPosition()方法来获取地理位置。语法:navigator.geol
- 首先说下Golang中的结构体,结构体是由一系列具有相同类型或不同类型的数据构成的数据集合,Golang中使用关键字struct来创建一个结
- Python 读取WAV文件import waveimport structfrom scipy import *from pylab im
- 一个装饰器已经作用在一个函数上,你想撤销它,直接访问原始的未包装的那个函数。假设装饰器是通过 @wraps 来实现的,那么你可以通过访问 w
- 本文为大家分享了mysql 8.0.15 安装配置图文教程,供大家参考,具体内容如下1.进官网,选择适合自己版本的linux下的MYSQL版
- python 循环while和for in简单实例#!/uer/bin/env python# _*_ coding: utf-8 _*_l
- 简介:MongoEngine 是一个Document-Object Mapper (想一下ORM, 但它是针对文档型数据库),Python通
- 这些CSS Selector在平时写页面的时候用地不多,只在JavaScript库、Firefox插件、iPhone页面里有过接触。推荐大家
- 今天我和中国著名画家"渔人"谈了一个关于"怎样才能设计好"的问题,他给我说了一句话,得益不浅,那句话