L
L
laimonsess2022-04-10 16:37:56
Python
laimonsess, 2022-04-10 16:37:56

The parser does not work in the Python telegram bot, what could be the problem?

Parser of the latest posts from Habr.
The bottom line is that the bot will take the latest published posts from Habr on the topic of Python and publish them in the telegram channel. The published post will contain a title, text, and a link to the source of the post.
Perhaps the problem is that I used the wrong code elements from Habr.
(Perhaps I stuck a lot of unnecessary things, because I looked at different sources)

Code:

spoiler

import telebot
import requests
import time

from bs4 import BeautifulSoup

token = ""
id_channel = ""
bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(func=lambda m: True)
def echo_all(message):
    bot.send_message(id_channel, message.text)

@bot.message_handler(func=lambda m: True)
def commands(message):
    bot.send_message(id_channel, message.text)
    if message.text == "Старт":
        bot.send_message(id_channel, "Hello")
        back_post_id = None
        while True:
            post_text = parser(back_post_id)
            back_post_id = post_text[1]

            if post_text[0] != None:
                bot.send_message(id_channel, post_text[0])
                time.sleep(1800)
    else:
        bot.send_message(message.from_user.id, "Я тебя не понимаю. Напиши Старт")

def parser(back_post_id):
    URL = "https://habr.com/ru/search/?q=python&target_type=posts&order=date"

    page = requests.get(URL)
    soup = BeautifulSoup(page.content, "html.parser")

    post = soup.find("article", class_="tm-articles-list__item", id=True)
    post_id = post["id"]
    
    if post_id != back_post_id:
        title = post.find("h2", class_="tm-article-snippet__title-link").text.strip()
        description = post.find("div", class_="article-formatted-body article-formatted-body_version-2").text.strip()
        url = post.find("h2", class_="tm-article-snippet__title-link", href=True)["href"].strip()
        
        return f"{title}\n\n{description}\n\n{url}", post_id
    else:
        return None, post_id

bot.infinity_polling()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2022-04-10
@SoreMix

@bot.message_handler(func=lambda m: True)
Out of two identical decorators, the first one will work. So the commands function is not even executed

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question