编写Pyhton脚本监控主机补货情况,并发送QQ消息

679次阅读
没有评论

共计 3373 个字符,预计需要花费 9 分钟才能阅读完成。

这里利用了 Py 脚本监控 + go_cqhttp 机器人实现。

准备阶段:

安装 Python
在终端中输入以下命令来安装 Python:

sudo apt update
sudo apt install python3

这将安装 Python 3.x 版本。如果您需要安装 Python 2.x 版本,请将上述命令中的“python3”替换为“python”。

安装所需的库
在终端中输入以下命令来安装所需的 Python 库:

apt install python3-pip
pip3 install requests
pip3 install beautifulsoup4
pip3 install python-telegram-bot

这将安装 requests、beautifulsoup4 和 python-telegram-bot 库。

 

1. 创建 Py 监控脚本 web_monitor.py

!注意如果在 linux 运行头部要加这行代码:#!/usr/bin/env python3

#-*- codeing = utf-8 -*-
#@Time :2023/4/1 15:25
#@Author : zh
#@File : web_monitor.py
#@Software: PyCharm

import datetime
import requests
import asyncio
import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoup

# 发送群号
group_id = '112'

# Telegram Bot 群组 id (需要把 bot 加入群组,并点打开点开始。再把 @get_id_bot 加入群组 /start,即可知道群组 id,完事后可以移除 @get_id_bot)
telegram_user_id = '-xxx'
# 填写 Telegram Bot 的 API token 和您的 Telegram 用户 ID
bot_token = 'xxxxxx'

# 发送文本范式
template_txt = '''
商 品: {name} 补货了
详 情: {url}
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
'''.strip()

headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36",
}


# 发送消息到 QQ 机器人
def send_group_msg(group_id, message):
    # 发送的机器人通信
    send_group_msg_url = 'http://127.0.0.1:5700/send_group_msg'
    params = {
        'group_id': group_id,
        'message': message,
    }
    print(params)
    requests.get(send_group_msg_url, params).json()


# 发送到 tg 机器人消息
async def send_tg_msg(msg):
    bot = telegram.Bot(token=bot_token)
    await bot.send_message(chat_id=telegram_user_id, text=msg)


def check_stock():
    try:
        print("start...")

        urlList = [
            {
            'url':'https://example.xxx.com/order/?shop_id=28',
            'name':'商品名称'
        }
        ]

        for item in urlList:
            print(item.get('url'))

            response = requests.get(item.get('url') , headers=headers, timeout=50)
            print(response.status_code)

            if response.status_code == 200:
                # 这里是自己写的规则
                # 解析网站内容,获取商品库存信息
                soup = BeautifulSoup(response.text, "html.parser")
                # 寻找元素
                change_currency_element = soup.find_all(class_='col-md-3 package-boxes')
                now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 获取当前时间
                # 判断是否能打开页面
                if len(change_currency_element)<=0:
                    print(now_time, '缺货:' + item.get('name'))
                    continue
                # 取第一个下拉列表
                qty_text = change_currency_element[0].text.strip()

                # 判断下拉文本按钮是否为 Select 状态
                if qty_text is not None and 'Select' in qty_text:
                    # 发送邮件通知有货
                    # send_email_notification(url)
                    # 文本赋值
                    msg = template_txt.format(name=item.get('name'), url=item.get('url'))
                    print(now_time, '有货:' + item.get('name'))
                    # 发送消息到 QQ 机器人
                    send_group_msg(group_id, msg)
                    # 异步发送消息到 TG 机器人
                    asyncio.run(send_tg_msg(msg))
                else:
                    print(now_time, '缺货:' + item.get('name'))
                print("end")

    except Exception as e:
        print('错误', e)


if __name__ == '__main__':
    check_stock()

这里的机器人通信服务接口 http://127.0.0.1:5700/send_group_msg 

可以参考我上一篇文章部署。 部署 QQ 消息机器人

2. 开始监控

脚本和机器人都部署到服务器上后,go_cqhttp 机器人可以运行命令

./go-cqhttp -d

在后台运行。

py 脚本 则需使用定时任务
为了让 Python 代码定期运行,您可以使用 Linux 的定时任务工具 cron。在终端中输入以下命令以编辑 cron 表:

crontab -e

然后添加以下行来设置定时任务,例如每隔 10 秒运行一次:

* * * * * sleep 10 && /usr/bin/python3 /root/web_monitor.py > /root/web_monitor.log

要填绝对路径。保存并退出 cron 表后,定时任务将自动启动,并按照您设置的时间间隔运行 Python 代码。运行日志将保存到 /root/web_monitor.log

3. 这里贴一下 qq 邮件的发送方法,自行选择。

def send_email_notification(buy_link):
    # 邮件 SMTP 配置
    smtp_server = 'smtp.qq.com'
    smtp_port = 465  # 或者其他端口号
    sender_email = '发件人 [email protected]'
    sender_password = '服务密码,可以去邮箱查看'
    receiver_email = '收件人 [email protected]'

    # 邮件内容
    message = MIMEText('xx 商品补货了 Buy it at: {}'.format(buy_link), 'plain', 'utf-8')
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = 'commodity is available now!'

    # 发送邮件
    smtp_server = smtplib.SMTP_SSL(smtp_server, smtp_port)
    smtp_server.login(sender_email, sender_password)
    smtp_server.sendmail(sender_email, [receiver_email], message.as_string())
    smtp_server.quit()
    print("邮件发送完成")

 

正文完
 
alecctv
版权声明:本站原创文章,由 alecctv 2023-04-01发表,共计3373字。
转载说明:除特殊说明外本站文章皆由ooly.cc发布,转载请注明出处。
评论(没有评论)
验证码