L
L
L1kr1k2021-03-23 17:54:25
Python
L1kr1k, 2021-03-23 17:54:25

How to make the telegram bot display the desired message?

There is a bot on the telebot library that parses news from the site using bs4. My idea is to write the url of the news that the bot parsed into a separate text document, I did this. But if they are present in the document, it should not display them, but only display news that has not yet been. In the case of a complete absence of new posts, the bot should display a message stating that there is no news. I've been scratching my head all day and can't think of anything. This is how the code fragment looks like now (sorry if I posted something wrong, this is my first time on this forum):

elif message.text=='Помощник, есть новости?':
      bot.send_message(message.chat.id, 'Вот последние новости.')
      news_url='(сайт)'
      news_headers={'User-Agent': '(агент пользователя)'}
      news_response=requests.get(news_url, headers=news_headers)
      result_news=BeautifulSoup(news_response.content, 'html.parser')
      items_news=result_news.findAll('div', class_='list-item')
      comps_news=[]
      for item in items_news:
        comps_news.append({'news_title': item.find('a', class_='list-item__title color-font-hover-only').get_text(strip=True), 'news_link': item.find('a', class_='list-item__title color-font-hover-only').get('href')})
        news_link=item.find('a', class_='list-item__title color-font-hover-only').get('href')
        news_file=open('(путь к текстовому файлу)', 'r')
        news_note=set()
        for line in news_file:
          news_note.add(line.strip())
        news_file.close()
        if not str(news_link) in news_note:
          news_file=open('(путь к текстовому файлу)', 'a')
          news_file.write(str(news_link)+'\n')
          news_note.add(news_link)
      for comp in comps_news:
        bot.send_message(message.chat.id, comp['news_title']+'\n'+comp['news_link'])

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question