kaktus_bot/kaktus_bot.py
2024-07-29 14:49:05 +02:00

73 lines
1.9 KiB
Python

from bs4 import BeautifulSoup
import requests
import time
import sys
api_token = '1437509413:AAHyyA5tnDW4cJm2SAdj1655YAwbuGQVuNU'
channel_name = '@kaktusdobijecka'
devlog_channel_name = -1001399814968
path = 'https://api.telegram.org/bot%s/sendMessage' % api_token
kaktus = 'https://www.mujkaktus.cz/novinky'
def last_text(text):
with open('/home/saitama/kaktus_bot/last.txt', 'r+', encoding='utf-8') as f:
if f.read() == text:
return True
else:
f.seek(0)
f.truncate(0)
f.write(text)
return False
def report_bug(text):
params = {
'chat_id': devlog_channel_name,
'text': text,
}
r = requests.get(path, params=params)
print(r)
def send_to_telegram(text):
params = {
'chat_id': channel_name,
'text': text,
}
r = requests.get(path, params=params)
if r.status_code != 200:
print('Failed to send, response:')
print(r.content)
else:
print('Sent successfully!')
try:
print('Checking for new messages... ', end='')
text = requests.get(kaktus).text
bs = BeautifulSoup(text, 'html.parser')
entries = bs.find_all("div", {"class": "journal-content-article"})
entry = entries[0]
split = entry.text.split('\n')
split = [_ for _ in split if _ and _ != 'Sdílet na Facebooku']
text = '\n\n'.join(split)
if not last_text(text):
print('found!')
send_to_telegram(text)
else:
print('not found.')
except Exception as e:
error_text = repr(e)
print(error_text, 'RESTARTING SERVICE')
while True:
try:
report_bug(error_text)
except Exception as ex:
print(repr(ex))
print('failed to send error report, trying again...')
time.sleep(5)
else:
break