python微信聊天机器人改进版(定时或触发抓取天气预报、励志语录等,向好友推送)

yizhihongxing

Python微信聊天机器人改进版攻略

项目概述

本项目是使用Python实现的微信聊天机器人,可以实现根据定时或触发条件抓取天气预报、励志语录等并向好友推送的功能。

技术方案

开发环境

  • Python 3.x
  • itchat:一个开源的微信个人号接口;
  • BeautifulSoup:一个可以从HTML或XML文件中提取数据的Python库;
  • requests:一个用于Python网络请求的第三方库;
  • APScheduler:一个Python定时任务调度库。

实现思路

  • 使用itchat库登录微信个人号;
  • 接收微信消息,根据指令触发不同的功能;
  • 使用requests、BeautifulSoup库抓取网络数据;
  • 使用APScheduler库实现定时任务。

改进版实现流程

  1. 安装itchat、BeautifulSoup、requests、APScheduler库
pip install itchat
pip install BeautifulSoup4
pip install requests
pip install APScheduler
  1. 导入所需库
import itchat
import requests
from bs4 import BeautifulSoup
from apscheduler.schedulers.background import BackgroundScheduler
import time
import datetime
  1. 登录微信个人号
itchat.auto_login(hotReload=True)  # 开启微信网页版登录
  1. 监听微信消息,根据指令触发不同的功能
@itchat.msg_register('Text')  # 监听微信文本消息
def handle_text(msg):
    from_user = msg['FromUserName']  # 发送消息的好友的UserName
    to_user = msg['ToUserName']  # 接收消息的个人号的UserName
    text = msg['Text']  # 收到的文本消息内容
    cmd = text.split(' ')[0]  # 截取第一个空格前的字符作为指令

    if cmd == '天气':
        send_weather(from_user, to_user)
    elif cmd == '励志':
        send_inspire(from_user, to_user)
    else:
        pass
  1. 抓取天气预报
def get_weather():
    city = '南京'  # 城市
    url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city

    response = requests.get(url)  # 发起请求
    response.encoding = response.apparent_encoding  # 设置编码
    soup = BeautifulSoup(response.text, 'html.parser')  # 解析HTML
    today = soup.select_one('.today')  # 获取当天天气信息
    weather = today.select_one('.wea').get_text()  # 天气现象
    temperature = today.select_one('.tem').get_text()  # 温度

    return f'{city}天气:{weather},温度:{temperature}'
  1. 发送天气预报
def send_weather(from_user, to_user):
    weather = get_weather()
    itchat.send_msg(weather, toUserName=from_user)
    itchat.send_msg(weather, toUserName=to_user)
  1. 抓取励志语录
def get_inspire():
    url = 'http://www.lovehhy.net/Joke/Detail/QSBK/'  # 糗事百科
    response = requests.get(url)
    response.encoding = 'utf-8'
    soup = BeautifulSoup(response.text, 'html.parser')
    jokes = soup.select('.content')[1:]
    joke = jokes[0].get_text().strip()  # 获取一则励志语录

    return joke
  1. 发送励志语录
def send_inspire(from_user, to_user):
    inspire = get_inspire()
    itchat.send_msg(inspire, toUserName=from_user)
    itchat.send_msg(inspire, toUserName=to_user)
  1. 实现定时任务
scheduler = BackgroundScheduler()  # 定义定时任务调度器

@scheduler.scheduled_job('cron', hour=7)  # 凌晨7点发送天气预报
def auto_send_weather():
    friends = itchat.get_friends(update=True)[1:]  # 获取好友列表
    for friend in friends:
        to_user = friend['UserName']
        send_weather(to_user, to_user)  # 将天气预报发送给自己和好友

@scheduler.scheduled_job('interval', minutes=30)  # 每30分钟发送一则励志语录
def auto_send_inspire():
    friends = itchat.get_friends(update=True)[1:]
    for friend in friends:
        to_user = friend['UserName']
        send_inspire(to_user, to_user)  # 发送给自己和好友

scheduler.start()  # 启动任务

示例说明

示例1

假设现在我想要获取当前南京的天气预报,可以向微信聊天机器人发送“天气”指令。Python代码中的函数 send_weather(from_user, to_user) 实现了向发送消息的好友和个人号自身发送天气预报的功能。

发送如下文本消息:

天气

聊天机器人会回复您类似于如下的天气预报:

南京天气:多云,温度:11℃~22℃

示例2

聊天机器人还会每天自动向好友推送天气预报和励志语录。例如,假设在早上7点整,聊天机器人会自动向好友推送南京当天的天气预报:

2022-01-01 07:00:00,149 - apscheduler.scheduler - INFO - Running job "auto_send_weather (trigger: cron[hour='7'], next run at: 2022-01-01 07:00:00 CST)" (scheduled at 2022-01-01 07:00:00+08:00)
2022-01-01 07:00:00,195 - apscheduler.executors.default - INFO - Running job "auto_send_weather (trigger: cron[hour='7'], next run at: 2022-01-01 07:00:00 CST)" (scheduled at 2022-01-01 07:00:00+08:00)

又比如,假设每30分钟聊天机器人会向好友们发送一则励志语录。例如:

2022-01-01 08:30:00,189 - apscheduler.scheduler - INFO - Running job "auto_send_inspire (trigger: interval[0:30:00], next run at: 2022-01-01 09:00:00 CST)" (scheduled at 2022-01-01 08:30:00+08:00)
2022-01-01 08:30:00,195 - apscheduler.executors.default - INFO - Running job "auto_send_inspire (trigger: interval[0:30:00], next run at: 2022-01-01 09:00:00 CST)" (scheduled at 2022-01-01 08:30:00+08:00)

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python微信聊天机器人改进版(定时或触发抓取天气预报、励志语录等,向好友推送) - Python技术站

(0)
上一篇 2023年5月23日
下一篇 2023年5月23日

相关文章

  • 在python plt图表中文字大小调节的方法

    在Python中常用的绘图库是Matplotlib,其中plt模块提供了许多常用的绘图函数。当我们需要调节图表中的文字大小时,可以通过设置rcParams参数来实现。 方法一:设置rcParams参数 首先,导入Matplotlib和rcParams: import matplotlib.pyplot as plt from matplotlib impor…

    python 2023年6月6日
    00
  • Python random模块的使用示例

    Python random模块的使用示例 Python中的random模块用于生成随机数,包括整数、浮点数和随机序列。接下来介绍random模块的常见使用示例。 1. 生成随机整数 要生成指定范围内的随机整数,可以使用random.randint()函数。该函数接受两个参数,分别代表随机整数的范围。下面的代码示例生成一个1~100之间的随机整数: impor…

    python 2023年6月3日
    00
  • python列表去重的5种常见方法实例

    以下是“Python列表去重的5种常见方法实例”的完整攻略。 1. 列表去重的概述 在Python中,列表(list)是一种常见的数据类型,它允我们存储多个值。有时候我们需要对列表中的元素进行去重操作,以便更好地处理数据。在本攻略中,我们将介绍5种常见的Python去重方法。 2. 方法一:使用set()函数 Python的set()函数可以将列表转换为集合…

    python 2023年5月13日
    00
  • Python中号称神仙的六个内置函数详解

    下面是Python中号称神仙的六个内置函数的详解攻略。 标题 1. map()函数 map()函数可以将一个函数作用于一个可迭代对象中的每个元素,并返回一个新的可迭代对象。 map(function, iterable) 示例1: l = [1, 2, 3] def f(x): return x**2 list(map(f, l)) 输出:[1, 4, 9]…

    python 2023年5月14日
    00
  • Python aiohttp百万并发极限测试实例分析

    以下是详细讲解“Pythonaiohttp百万并发极限测试实例分析”的完整攻略,包含两个示例说明。 1. Pythonaiohttp简介 Pythonaiohttp是一个基于asyncio实现异步HTTP客户端/服务器框架,它提供了高效的异步HTTP请求和响应处理能力。aiohttp的主要特点包括: 支持HTTP/1.1和HTTP/2协议 支持WebSock…

    python 2023年5月14日
    00
  • Python实现双X轴双Y轴绘图的示例详解

    下面就是“Python实现双X轴双Y轴绘图的示例详解”的完整攻略: 1. 什么是双X轴和双Y轴绘图? 双X轴和双Y轴绘图,是一种可以在一个图中显示两个不同X轴 或两个不同Y轴 的绘图方式。这种绘图方式常用于需要同时显示两组数据时,比较不同组数据之间的关系。 2. 如何实现双X轴和双Y轴绘图? 在 Python 中,我们可以使用 matplotlib 库来实现…

    python 2023年5月19日
    00
  • python 正则表达式 反斜杠(/)的麻烦和陷阱

    当在Python中使用正则表达式时,反斜杠字符(\)可能会导致一些麻烦和陷阱。这是因为反斜杠在Python中有特殊的含义,例如用于转义字符。因此,如果您想在正则表达式中使用反斜杠,您需要小心处理。 以下是两个示例,说明如何在Python中使用正则表达式时避免反斜杠的问题: 示例1:匹配文件路径 假设您想匹配一个文件路径,例如/home/user/file.t…

    python 2023年5月14日
    00
  • python正则表达式对字符串的查找匹配

    Python正则表达式对字符串的查找匹配 正则表达式是一种强大的文本处理工具,可以用于在字符串中查找和匹配特定的模式。Python内置了re模块,提供了对正表达式的支持。本文将为您介绍如何使用Python正则表达式对字符串进行查找和匹配。 正则表达式语法 正则表达式是由一系列字符和特殊字符组成的模式,用于匹配字符串中的文本。下面是一些常用的正则表达式特殊字符…

    python 2023年5月14日
    00
合作推广
合作推广
分享本页
返回顶部