1. 更新系统软件包列表:

在终端中运行以下命令以确保系统软件包列表是最新的:

sudo apt update

2. 安装 Python:

通常情况下,Ubuntu 自带了 Python。你可以通过以下方式安装 Python 3(默认情况下,Python 2 已经被弃用):

sudo apt install python3

这将安装 Python 3 和其相关的包。

3. 验证安装:

安装完成后,你可以在终端中输入以下命令来验证 Python 是否成功安装:

python3 --version

这将显示已安装的 Python 版本号。

4.安装 BeautifulSoup 库

pip install beautifulsoup4

如果系统是Centos安装的Python版本低,可以用以下命令安装需要的库。

sudo yum install python3-pip
pip3 install beautifulsoup4
pip3 install requests

5.新建脚本monitor_bbs.py

import requests
from bs4 import BeautifulSoup
import time
import os
import sys
from urllib.parse import urljoin
import re

# Telegram Bot相关信息
telegram_bot_token = 'YOUR_TELEGRAM_BOT_TOKEN'
telegram_channel_id = 'YOUR_TELEGRAM_CHANNEL_ID'

# 论坛页面 URL
forum_url = 'https://google.com/bbs'  # 修改为你的论坛页面地址
base_forum_url = 'https://google.com/'  # 论坛的基础链接

# 关键词列表
keywords = ['出售', '出', '补货', '交易']  # 修改为你想要监控的关键词

# 排除链接关键词
exclude_keywords = ['search.php', 'forumdisplay']

# 已发送的帖子链接列表
sent_post_links = []

# 向Telegram发送消息函数
def send_to_telegram(content):
    try:
        message = f"交易相关帖子:\n{content}"
        telegram_api_url = f'https://api.telegram.org/bot{telegram_bot_token}/sendMessage'
        payload = {
            'chat_id': telegram_channel_id,
            'text': message,
            'parse_mode': 'HTML'
        }
        response = requests.post(telegram_api_url, data=payload)
        if response.status_code == 200:
            print("Message sent to Telegram")
        else:
            print("Failed to send message to Telegram")
    except requests.exceptions.RequestException as e:
        print("Exception occurred:", e)

# 重新启动脚本
def restart_script():
    python = sys.executable
    os.execl(python, python, *sys.argv)

# 主逻辑
def main():
    global sent_post_links
    while True:
        try:
            # 获取论坛页面内容并解析
            response = requests.get(forum_url)
            if response.status_code == 200:
                html_content = response.text
                soup = BeautifulSoup(html_content, 'html.parser')

                # 查找所有链接,并检查文本内容是否包含关键词
                all_links = soup.find_all('a')
                found_posts = [link for link in all_links if any(keyword in link.get_text() for keyword in keywords)]

                if found_posts:
                    # 向Telegram发送找到的帖子内容及链接
                    for post in found_posts:
                        post_content = post.get_text()
                        post_link = urljoin(base_forum_url, post['href'])  # 构建绝对链接
                        if post_link not in sent_post_links:  # 如果帖子链接不在已发送列表中则发送
                            if not re.search(r'(出事|出大事了)', post_content):
                                if any(keyword in post_link for keyword in exclude_keywords):
                                    continue  # 跳过这些链接
                                message_with_link = f"{post_content}\nLink: {post_link}"
                                send_to_telegram(message_with_link)
                                sent_post_links.append(post_link)  # 将已发送的帖子链接添加到列表中
                else:
                    print("No posts found with specified keywords.")
            else:
                print("Failed to fetch forum page.")

            # 休眠2分钟后重新启动脚本
            print("Sleeping for 2 minutes...")
            time.sleep(120)  # 2分钟,单位是秒
        except Exception as e:
            print("Exception occurred:", e)
            # 在发生异常时休眠一段时间后重新启动脚本
            time.sleep(120)  # 2分钟,单位是秒
            restart_script()

if __name__ == "__main__":
    main()

6.给脚本设定权限monitor_bbs.py

chmod +x monitor_bbs.py

7.执行脚本

python3 monitor_bbs.py
Last modification:December 22nd, 2023 at 02:27 pm