1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python--实现微信自动回复机器人和定时发送每日一句与天气预报

python--实现微信自动回复机器人和定时发送每日一句与天气预报

时间:2023-08-28 04:02:13

相关推荐

python--实现微信自动回复机器人和定时发送每日一句与天气预报

目录

关于wxpy安装wxpy利用机器人实现微信自动回复获取金山词霸每日一句获取天气预报数据定时发送每日一句与天气预报结束

关于wxpy

wxpy其实是通过微信网页版的api实现对微信的一些相应操作,所支持的功能也局限于微信网页版,有些微信账号可能登录不了网页版,那么也就无法使用了。

关于wxpy,官方文档是这样介绍的

wxpy: 用 Python 玩微信

微信机器人 / 可能是最优雅的微信个人号 API

wxpy 在 itchat 的基础上,通过大量接口优化提升了模块的易用性,并进行丰富的功能扩展

用来干啥

一些常见的场景

控制路由器、智能家居等具有开放接口的玩意儿运行脚本时自动把日志发送到你的微信加群主为好友,自动拉进群中跨号或跨群转发消息自动陪人聊天逗人玩

总而言之,可用来实现各种微信个人号的自动化操作

关于wxpy的更多介绍请看官方文档:https://wxpy.readthedocs.io/zh/latest/index.html

安装wxpy

wxpy 支持 Python 3.4-3.6,以及 2.7 版本

将下方命令中的 “pip” 替换为 “pip3” 或 “pip2”,可确保安装到对应的 Python 版本中

从 PYPI 官方源下载安装 (在国内可能比较慢或不稳定):

pip install -U wxpy

从豆瓣 PYPI 镜像源下载安装 (推荐国内用户选用):

pip install -U wxpy -i "/simple/"

利用机器人实现微信自动回复

wxpy提供了两种自动聊天机器人接口:

图灵机器人小i机器人

图灵机器人接入方法:

首先要到图灵机器人官网注册账号,和创建一个机器人得到key

from wxpy import *#导入wxpy模块bot=Bot(cache_path=True)#设置缓存为True,下次登陆在手机确认就行,不用再次扫码xiaoguo=Tuling(api_key='填你上面获取到的key')my_friend=bot.friends().search('你的笑像一条恶犬')[0]#查找聊天对象(微信好友的微信名,不是微信号和备注)@bot.register(my_friend)def reply_my_friend(msg):#机器人只自动回复选择的好友xiaoguo.do_reply(msg)embed()#阻塞进程

以上就可以利用图灵机器人实现一个微信聊天机器人,但是现在图灵机器人免费的每天只能调用100次,而且要进行实名认证

小i机器人接入方法:

首先到小i机器人官网注册账号获取key和secret

然后跟图灵机器人基本一样的方法

from wxpy import *#导入wxpy模块bot=Bot(cache_path=True)#设置缓存为True,下次登陆在手机确认就行,不用再次扫码xiaoguo=XiaoI('你的key','你的secret')#使用小i机器人my_friend=bot.friends().search('你的笑像一条恶犬')[0]#查找聊天对象(微信好友的微信名,不是微信号和备注)@bot.register(my_friend)def reply_my_friend(msg):#机器人只自动回复选择的好友xiaoguo.do_reply(msg)embed()#阻塞进程

这样就利用小i机器人实现了微信聊天机器人,但是可能是因为小i机器人的api接口更新了,wxpy没有及时更新,导致机器人接口会请求失败,需要对wxpy的源码对小i机器人api接口的url进行修改,如下图

获取金山词霸每日一句

金山词霸每日一句提供了一个api可供调用:/dsapi/

这是官方的api文档介绍:/?c=wiki

import requests#导入requests模块def get_one_word():#获取每日一句r=requests.get('/dsapi?').json()content=r.get('content')note=r.get('note')return content,note

这就是获取到的每日一句

获取天气预报数据

天气预报的api大部分都要付费,免费的可能限制比较多,而且也不是很稳定,这里用的是和风天气的api:/documents/api/s6/weather-all

首先到官网注册账号并登录,然后到控制台新建一个应用

然后为刚才添加的应用添加key

请求url:https://free-/s6/weather?location=要查询的城市或地区&key=上面获取到的key

def get_weather():#获取天气r=requests.get('https://free-/s6/weather?location=要查询的城市或地区&key=上面获取到的key')weather=r.json().get('HeWeather6')[0]now=weather.get('now')daily_forecast=weather.get('daily_forecast')[0]lifestyle=weather.get('lifestyle')date=daily_forecast.get('date')sr=daily_forecast.get('sr')ss=daily_forecast.get('ss')mr=daily_forecast.get('mr')ms=daily_forecast.get('ms')tmp_max=daily_forecast.get('tmp_max')tmp_min=daily_forecast.get('tmp_min')cond_txt_d=daily_forecast.get('cond_txt_d')cond_txt_n=daily_forecast.get('cond_txt_n')wind_dir=daily_forecast.get('wind_dir')wind_sc=daily_forecast.get('wind_sc')wind_spd=daily_forecast.get('wind_spd')hum=daily_forecast.get('hum')pcpn=daily_forecast.get('pcpn')pop=daily_forecast.get('pop')pres=daily_forecast.get('pres')uv_index=daily_forecast.get('uv_index')vis=daily_forecast.get('vis')tmp=now.get('tmp')fl=now.get('fl')comf=lifestyle[0].get('brf')+','+lifestyle[0].get('txt')drsg=lifestyle[1].get('brf')+','+lifestyle[1].get('txt')flu=lifestyle[2].get('brf')+','+lifestyle[2].get('txt')sport=lifestyle[3].get('brf')+','+lifestyle[3].get('txt')uv=lifestyle[5].get('brf')+','+lifestyle[5].get('txt')air=lifestyle[7].get('brf')+','+lifestyle[7].get('txt')weather_msg="""日期:{0}\n温度:{1}℃\n体感温度:{2}℃\n最高温度:{3}℃\n最低温度:{4}℃\n白天:{5}\n晚间:{6}\n风向:{7}\n风力:{8}级\n风速:{9}公里/小时\n相对湿度:{10}\n降水量:{11}\n降水概率:{12}\n大气压强:{13}\n紫外线强度指数:{14}\n能见度:{15}公里\n日出时间:{16}\n日落时间:{17}\n月升时间:{18}\n月落时间:{19}\n舒适度指数:{20}\n穿衣指数:{21}\n感冒指数:{22}\n运动指数:{23}\n紫外线指数:{24}\n空气污染扩散条件指数:{25} """.format(date,tmp,fl,tmp_max,tmp_min,cond_txt_d,cond_txt_n,wind_dir,wind_sc,wind_spd,hum,pcpn,pop,pres,uv_index,vis,sr,ss,mr,ms,comf,drsg,flu,sport,uv,air)return weather_msg

定时发送每日一句与天气预报

利用schedule模块实现定时(每天的某个时间点,例如晚上十一点发送天气预报,早上8点发送每日一句)发送每日一句与天气预报。

schedule模块的简单使用:

import scheduleimport timeimport datetimedef job1():print('Job1:每隔10秒执行一次的任务,每次执行2秒')print('Job1-startTime:%s' %(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))time.sleep(2)print('Job1-endTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))print('------------------------------------------------------------------------')def job2():print('Job2:每隔30秒执行一次,每次执行5秒')print('Job2-startTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))time.sleep(5)print('Job2-endTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))print('------------------------------------------------------------------------')def job3():print('Job3:每隔1分钟执行一次,每次执行10秒')print('Job3-startTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))time.sleep(10)print('Job3-endTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))print('------------------------------------------------------------------------')def job4():print('Job4:每天下午17:49执行一次,每次执行20秒')print('Job4-startTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))time.sleep(20)print('Job4-endTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))print('------------------------------------------------------------------------')def job5():print('Job5:每隔5秒到10秒执行一次,每次执行3秒')print('Job5-startTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))time.sleep(3)print('Job5-endTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))print('------------------------------------------------------------------------')if __name__ == '__main__':schedule.every(10).seconds.do(job1)schedule.every(30).seconds.do(job2)schedule.every(1).minutes.do(job3)schedule.every().day.at('17:49').do(job4)schedule.every(5).to(10).seconds.do(job5)while True:#schedule模块是阻塞式函数需要死循环运行run_pending()schedule.run_pending()

实现每天定时发送每日一句与天气预报:

def send_one_word():try:one_word=get_one_word()my_friend.send(one_word[0])my_friend.send(one_word[1])except:me=bot.friends().search('花蛤与蟹')[0]me.send('今天每日一句发送失败')def send_weather():try:weather=get_weather()my_friend.send(weather)except:me=bot.friends().search('花蛤与蟹')[0]me.send('今天天气预报发送失败')schedule.every().day.at('22:30').do(send_one_word)#定时每天晚上22:30发送每日一句schedule.every().day.at('08:00').do(send_weather)#定时每天早上08:00发送天气预报while True:schedule.run_pending()

结束

完整代码:

from wxpy import *import requestsimport schedulebot=Bot(cache_path=True)#xiaoguo=Tuling(api_key='你的key')#使用图灵机器人xiaoguo=XiaoI('你的key','你的secret')#使用小i机器人#@bot.register(bot.self,except_self=False)#def auto_reply(msg):# xiaoguo.do_reply(msg)my_friend=bot.friends().search('你的笑像一条恶犬')[0]#查找聊天对象(微信好友的微信名,不是微信号和备注)@bot.register(my_friend)def reply_my_friend(msg):#机器人只自动回复选择的好友xiaoguo.do_reply(msg)def get_one_word():#获取每日一句r=requests.get('/dsapi?').json()content=r.get('content')note=r.get('note')return content,notedef get_weather():#获取天气r=requests.get('https://free-/s6/weather?location=要查询的城市或地区&key=你的key')weather=r.json().get('HeWeather6')[0]now=weather.get('now')daily_forecast=weather.get('daily_forecast')[0]lifestyle=weather.get('lifestyle')date=daily_forecast.get('date')sr=daily_forecast.get('sr')ss=daily_forecast.get('ss')mr=daily_forecast.get('mr')ms=daily_forecast.get('ms')tmp_max=daily_forecast.get('tmp_max')tmp_min=daily_forecast.get('tmp_min')cond_txt_d=daily_forecast.get('cond_txt_d')cond_txt_n=daily_forecast.get('cond_txt_n')wind_dir=daily_forecast.get('wind_dir')wind_sc=daily_forecast.get('wind_sc')wind_spd=daily_forecast.get('wind_spd')hum=daily_forecast.get('hum')pcpn=daily_forecast.get('pcpn')pop=daily_forecast.get('pop')pres=daily_forecast.get('pres')uv_index=daily_forecast.get('uv_index')vis=daily_forecast.get('vis')tmp=now.get('tmp')fl=now.get('fl')comf=lifestyle[0].get('brf')+','+lifestyle[0].get('txt')drsg=lifestyle[1].get('brf')+','+lifestyle[1].get('txt')flu=lifestyle[2].get('brf')+','+lifestyle[2].get('txt')sport=lifestyle[3].get('brf')+','+lifestyle[3].get('txt')uv=lifestyle[5].get('brf')+','+lifestyle[5].get('txt')air=lifestyle[7].get('brf')+','+lifestyle[7].get('txt')weather_msg="""日期:{0}\n温度:{1}℃\n体感温度:{2}℃\n最高温度:{3}℃\n最低温度:{4}℃\n白天:{5}\n晚间:{6}\n风向:{7}\n风力:{8}级\n风速:{9}公里/小时\n相对湿度:{10}\n降水量:{11}\n降水概率:{12}\n大气压强:{13}\n紫外线强度指数:{14}\n能见度:{15}公里\n日出时间:{16}\n日落时间:{17}\n月升时间:{18}\n月落时间:{19}\n舒适度指数:{20}\n穿衣指数:{21}\n感冒指数:{22}\n运动指数:{23}\n紫外线指数:{24}\n空气污染扩散条件指数:{25} """.format(date,tmp,fl,tmp_max,tmp_min,cond_txt_d,cond_txt_n,wind_dir,wind_sc,wind_spd,hum,pcpn,pop,pres,uv_index,vis,sr,ss,mr,ms,comf,drsg,flu,sport,uv,air)return weather_msgdef send_one_word():try:one_word=get_one_word()my_friend.send(one_word[0])my_friend.send(one_word[1])except:me=bot.friends().search('花蛤与蟹')[0]me.send('今天每日一句发送失败')def send_weather():try:weather=get_weather()my_friend.send(weather)except:me=bot.friends().search('花蛤与蟹')[0]me.send('今天天气预报发送失败')schedule.every().day.at('22:30').do(send_one_word)#定时每天晚上22:30发送每日一句schedule.every().day.at('08:00').do(send_weather)#定时每天早上08:00发送天气预报while True:schedule.run_pending()#embed()

效果展示:

虽然这个机器人有点蠢蠢的哈哈哈,不过是因为这是个初始的机器人,你可以到官网对你的机器人进行一些训练和设置,让他变得更智能~

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。