当前位置:网站首页>超简单!只需简单几步即可为TA定制天气小助理!!
超简单!只需简单几步即可为TA定制天气小助理!!
2022-07-26 15:07:00 【执行上下文】
前提
虽然我们每天都会查看天气,但是如果你能够用限制微信每天早上七点定时为TA推送天气预报,生活指数。直接为TA提供过滤好的天气信息,让TA一目了然。而且操作简单上手,任何人都可以零基础搭建,为你的TA带来一丝小惊喜。
效果如图
准备
- 运行环境 win10 Linux
- python 3.4 版本
- 一个微信小号
- 和风天气api
- 一个编辑器,就是文本编辑器也可以
主要代码
1. 安装 python 3.7 版本
小伙伴如果是 window 电脑可以直接在 Python官网 (https://www.python.org/downloads/)选择 *download *直接下载
直接点击下载好的exe文件进行安装,记得将环境变量配置选项勾选上。如下图:
安装完成之后,我们可以新建文件夹,从git 上将代码clone 下来。我们直接在文件夹中摁住 shift + 鼠标右键 唤出 powerShell 查看 Python 版本。
如果大家还有不明白的可以参考 Python安装教程(https://www.runoob.com/python/python-tutorial.html)
2. 为项目安装相关模块
可通过 pip install 直接安装相关模块,如运行时还有因模块报错,也可以直接pip install 模块名直接安装即可。本项目以及后续相关都依赖于以下模块。
#coding=utf8
import requests
from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.parse import urlencode
from threading import Timer
import re
from wxpy import *
import schedule
import time
import http
import json
import datetime
import random重要: 其中 wxpy 模块是本项目以及后续项目中很重要的模块,就是因为这个开源项目,我们才能使其与微信产生交互。
wxpy
控制路由器、智能家居等具有开放接口的玩意儿
运行脚本时自动把日志发送到你的微信
加群主为好友,自动拉进群中
跨号或跨群转发消息
自动陪人聊天
逗人玩
...项目介绍以及安装方法,大家可以去主页想看wxpy(https://wxpy.readthedocs.io/zh/latest/index.html)
3. 初始化机器人
参考 登录文档
bot = Bot(cache_path=True,console_qr = 1)
// 初始化机器人,扫码登录 console_qr 是用于登录的二维码展示默认为1
bot.enable_puid('wxpy_puid.pkl')
// 机器人启用 puid 属性,并指定 puid 所需的映射数据保存/载入路径4. 设置模拟请求接口相关
def api(url):
header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.8',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
}
timeout = random.choice(range(80, 180))
data = requests.get(url, headers=header, timeout=timeout)
return data.json()header 中用来设置模拟请求接口的浏览器相关参数防止api 以为我们是爬虫抓取。并设定随机请求时间。
5. 设置相关请求,以及需要的信息字段拼接
def sendweather(city, xx):
url = 'https://free-api.heweather.com/s6/weather/forecast?location='+city+'&key=和风key'
PMurl = 'https://free-api.heweather.com/s6/air/now?parameters&location='+city+'&key=和风key'
lifeurl = 'https://free-api.heweather.com/s6/weather/lifestyle?location='+city+'&key=和风key'
temp = api(url)
temp = temp['HeWeather6'][0]
update = temp['update']
now = temp['daily_forecast'][0]
nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
pm = api(PMurl)
pm = pm['HeWeather6'][0]
airnow = pm['air_now_city']
life = api(lifeurl)
life = life['HeWeather6'][0]
life = life['lifestyle']
result = xx + city +' ---' + '\n'+ '\n'\
+ ' 今天天气:'+ now['cond_txt_d'] + ' 转 ' + now['cond_txt_n'] + '\n'\
+ ' 今天温度:'+ now['tmp_min'] + '°C ~ ' + now['tmp_max'] + '°C' + '\n'\
+ ' 风向:'+ now['wind_dir'] + ' ' + now['wind_sc'] + '级 '+ now['wind_spd'] + '公里/小时'+ '\n'\
+ ' 相对湿度:'+ now['hum'] + '%' + '\n'\
+ ' 降水量:'+ now['pcpn'] + 'ml' + ',降水概率:'+ now['pop'] + '%' + '\n'\
+ ' 能见度:'+ now['vis'] + '公里' + '\n'\
+ '------------------------------------------' + '\n'\
+ '今天空气质量:'+'\n'\
+ ' 空气质量指数:'+ airnow['aqi']+'\n'\
+ ' 主要污染物:'+ airnow['main']+'\n'\
+ ' 空气质量:'+ airnow['qlty']+'\n'\
+ ' 二氧化氮指数:'+ airnow['no2']+'\n'\
+ ' 二氧化硫指数:'+ airnow['so2']+'\n'\
+ ' 一氧化碳指数:'+ airnow['co']+'\n'\
+ ' pm10指数:'+ airnow['pm10']+'\n'\
+ ' pm25指数:'+ airnow['pm25']+'\n'\
+ ' 臭氧指数:'+ airnow['o3'] +'\n'\
+ '------------------------------------------' + '\n'\
+ '1、'+ life[0]['txt']+'\n\n'\
+ '2、'+ life[1]['txt']+'\n\n'\
+ '3、'+ life[2]['txt']+'\n\n'\
+ ''+'\n\n'\
result = result + '发送时间:' + nowTime + '\n'
return result小伙伴可以在和风官网(https://www.heweather.com/)注册账户,其中有免费的天气、生活指数api可以使用。免费的已经可以满足我们的需求。
6. 获取发送对象
def auto_send(msg):
weather = sendweather('苏州', msg)
// 用来请求刚刚封装的请求天气
Lie = bot.friends().search(u'Lie')[0]
// 查找你要发送的对象,必须在你的好友列表里也可以为群
后面是好友的昵称,记得不是备注名哦!
WxpyChat = bot.groups().search(' (๑• . •๑) ')
// 获取要发送的群
Lie.send(weather)
// 发送
WxpyChat.send(weather)
// 可以设置多个发送对象7. 设置定时发送事件
schedule.every().day.at("13:56").do(auto_send, '早上好,')
schedule.every().day.at("13:57").do(auto_send, '晚上好,')8. 为程序设置持续运行保证项目一直在线
while True:
schedule.run_pending()
time.sleep(1)9. 至此,一个简单的天气小助理就完成了,可以按照以上步骤来实验一下。
10. 扩展
我们还可以为其添加主动询问操作,比如发送城市,直接获得当前城市的天气,只需要在第6步添加如下代码即可。
Lie = bot.friends().search(u'Lie')
@bot.register(Lie)
// 注册对哪个好友的回复生效
def auto_reply_all(msg):
if '苏州' in msg.text:
nowWeather = sendweather(msg.text, msg)
msg.sender.send(nowWeather)git
本项目的代码以上传我的github,如有需要大家可以clone下载你也可以在后台回复 天气助理 获取源码链接。
wepython(https://github.com/jiaopianjun/wepython)
注意事项
- 在window 下 可以用 powerShell 来运行python 程序。
- 微信号要用2017年之前注册的微信号,新注册的微信号不能在web网页登录无法使用。
- 大家如果没有小号,需要购买的请注意对方诚信度。不要为了这个上当受骗。
下期预告
用python + wxpy 为TA定制贴心喝水小助理。
关于我
小夭同学,页面切图仔。
边栏推荐
- [leave some code] Apply transformer to target detection, and understand the model operation process of the model through debug
- QCF for deep packet inspection paper summary
- Vs add settings for author information and time information
- NAT/NAPT地址转换(内外网通信)技术详解【华为eNSP】
- 如何查询外文文献?
- R language Visual scatter diagram, geom using ggrep package_ text_ The rep function avoids overlapping labels between data points (set the min.segment.length parameter to 0 to add line segments to the
- driver开发环境
- R language wilcox The test function compares whether there is a significant difference in the central position of the population of two nonparametric samples (if the two sample data are paired data, s
- R语言使用lm函数构建带交互项的多元回归模型、使用step函数构建逐步回归模型筛选预测变量的最佳子集(step regression)
- Operation method of abbkine elikine human alpha fetoprotein (AFP) ELISA quantitative Kit
猜你喜欢

Deep Packet Inspection Using Cuckoo Filter论文总结

Digital commerce cloud: lead the digital upgrading of chemical industry and see how Mobei can quickly open up the whole scene of mutual integration and interoperability

写综述,想用一个靠谱的整理文献的软件,有推荐的吗?

Prometheus adds email alarm and enterprise wechat robot alarm

If food manufacturing enterprises want to realize intelligent and collaborative supplier management, it is enough to choose SRM supplier system

How much help does solid state disk have for game operation

driver开发环境

FOC学习笔记-坐标变换以及仿真验证
Database expansion can also be so smooth, MySQL 100 billion level data production environment expansion practice

带你熟悉云网络的“电话簿”:DNS
随机推荐
R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses fitted function to calculate y value (response value) vector
兆骑科创高端人才项目引进落地,双创大赛承办,线上直播路演
OpenGL学习日记2——着色器
C # set different text watermarks for each page of word
【LeetCode每日一题】——268.丢失的数字
anaconda No module named ‘cv2‘
FOC learning notes - coordinate transformation and simulation verification
R language ggplot2 visualization: use ggplot2 to visualize the scatter diagram, and use the theme of ggpubr package_ The pubclean function sets the theme without axis lines in the visual image
谷歌尝试为ChromeOS引入密码强度指示器以提升线上安全性
固态硬盘对游戏运行的帮助有多少
【静态代码质量分析工具】上海道宁为您带来SonarSource/SonarQube下载、试用、教程
Sqldeveloper tools quick start
李宏毅《机器学习》丨3. Gradient Descent(梯度下降)
How to find undergraduate dissertations of domestic universities?
Qt最基本的布局,创建window界面
Environment regulation system based on Internet of things (esp32-c3+onenet+ wechat applet)
Double the efficiency of dual screen collaboration lingyao x dual screen Pro leads the new trend of dual screen technology
Continuous integration (II) introduction to the basic use of Jenkins
R语言使用lm函数构建带交互项的多元回归模型、使用step函数构建逐步回归模型筛选预测变量的最佳子集(step regression)
What are the skills and methods of searching foreign literature