TG 機器人推送網頁XML消息

Linux·Python · 01-23 · 65 人浏览
TG 機器人推送網頁XML消息

原理:通過requests請求網頁xml並解析,運行時獲取文章的時間,不終止循環,所以每次出現新的文章都會發送TG頻道
我的博客是Typecho,理論通用。

本次環境:Ubuntu

首先基本配置為Python3PIP3

sudo apt-get install -y libxml2-dev libxslt-dev ;pip3 install requests bs4 python-telegram-bot lxml 

2024-01-22T16:53:49.png
代碼如下:

# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
import telegram
# 初始化上一次的更新时间
last_pubDate = None

def send_message(content):
    bot = telegram.Bot(token='')  # 機器人Token
    chat_id = '@Xue_Li_Li_Channel'  # 聊天 ID
    bot.send_message(chat_id=chat_id, text=content)

while True:
    response = requests.get('XML_URL')
    # 解析网页
    soup = BeautifulSoup(response.content, 'xml')  # 使用'xml'解析器

    # 获取第一个"item"标签
    item = soup.find('item')
    # 获取"title"标签的内容
    title = item.find('title').text
    link = item.find('link').text
    # 获取"pubDate"标签的内容并解析为datetime对象
    pubDate = item.find('pubDate').text
    pubDate = datetime.strptime(pubDate, '%a, %d %b %Y %H:%M:%S %z')

    # 如果博客有更新
    if last_pubDate is not None and pubDate > last_pubDate:
        # 發送信息
        content = '***' + str(pubDate) + '***' + '\n\n' + title + '\n' + link + '\n'
        send_message(content)

    # 更新上一次的更新时间
    last_pubDate = pubDate
    print('1分鐘后繼續獲取....')
    # 每隔1分钟执行一次
    time.sleep(60)

2024-01-22T16:55:30.png

Bot
本站立足于美利堅合衆國,請讀者自覺遵守當地法律!如有違規,本站不承擔任何法律責任! This site is based in the United States of America, readers are requested to abide by local laws! If there are any violations, this site does not bear any legal responsibility! Theme Jasmine by Kent Liao