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

关于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 版本中

  1. 从 PYPI 官方源下载安装 (在国内可能比较慢或不稳定):
	pip install -U wxpy
  1. 从豆瓣 PYPI 镜像源下载安装 (推荐国内用户选用):
	pip install -U wxpy -i "https://pypi.doubanio.com/simple/"

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

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

  1. 图灵机器人
  2. 小i机器人

图灵机器人接入方法:

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

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可供调用:http://open.iciba.com/dsapi/
这是官方的api文档介绍:http://open.iciba.com/?c=wiki

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

在这里插入图片描述
这就是获取到的每日一句

获取天气预报数据

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

首先到官网注册账号并登录,然后到控制台新建一个应用
在这里插入图片描述
然后为刚才添加的应用添加key在这里插入图片描述
请求url:https://free-api.heweather.net/s6/weather?location=要查询的城市或地区&key=上面获取到的key

def get_weather():#获取天气
    r=requests.get('https://free-api.heweather.net/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 schedule
import time
import datetime

def 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 requests
import schedule

bot=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('http://open.iciba.com/dsapi?').json()
    content=r.get('content')
    note=r.get('note')
    return content,note

def get_weather():#获取天气
    r=requests.get('https://free-api.heweather.net/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

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()

#embed()

效果展示:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
虽然这个机器人有点蠢蠢的哈哈哈,不过是因为这是个初始的机器人,你可以到官网对你的机器人进行一些训练和设置,让他变得更智能~

  • 9
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值