VPS优惠推送程序参考

监控脚本运行在Debian11系统

安装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库。

创建Telegram Bot并获取API令牌

可以在/root目录下(一般默认进入系统就是在此目录下)编写Python代码 monitor.py,执行:
nano monitor.py
#(使用vi monitor.py也可以,看你喜欢)

将以下代码复制并粘贴到您的文本编辑器中,并将【API token令牌替换】【用户 ID替换】替换为您自己的API令牌和Chat ID。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
##复制下面 从这里开始
import requests
from bs4 import BeautifulSoup
import telegram
import asyncio

\# 填写 Telegram Bot 的 API token 和您的 Telegram 用户 ID,保留单引号,只修改这两个
bot_token = 'API token令牌替换'
telegram_user_id = '用户 ID替换'

\# 从网页获取数据并解析
url = 'https://idc.hytron.io/index.php?rp=/store/hkbgp-standard'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
qty_element = soup.find(id='product1').find(class_='qty')

\# 获取当前的数量值
qty_text = qty_element.text.strip()
qty = int(qty_text.split(' ')[0])

\# 如果数量不为零,向 Telegram 用户发送消息
async def check_availability():
bot = telegram.Bot(token=bot_token)
await bot.send_message(chat_id=telegram_user_id, text=f"hytron1刀有货,当前数量为{qty}")

if qty > 0:
asyncio.run(check_availability())

并使用以下命令在终端中运行Python代码

python3 monitor.py
Python代码将开始运行,并在可用余量大于0时向您的Telegram Bot发送一条消息。如果出现任何错误,Python代码将在终端中打印错误信息。
如果没有任何提示,表示当前没有可用的库存,你也可以将上面的python脚本中id=’product1’,修改为id=’product2’ 临时验证电报是否可用。

一切没问题后,使用定时任务

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

crontab -e

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

* * * * sleep 10 && /usr/bin/python3 /root/monitor.py

请将“/root/monitor.py”替换为您保存Python代码的实际路径。保存并退出cron表后,定时任务将自动启动,并按照您设置的时间间隔运行Python代码。

完成开始测试


参见

参见1