Помогите дописать код парсинга для телеграм бота Python
Добрый вечер помогите переписать код для телеграм бота для сайта https://parfumelover.herokuapp.com/ , с уведомлением о новых товарах,заранее благодарен. сам код парсинга
import re
import os.path
import requests
from bs4 import BeautifulSoup as BS
from urllib.parse import urlparse
class StopGame:
host = 'https://stopgame.ru'
url = 'https://stopgame.ru/review/new'
lastkey = ""
lastkey_file = ""
def __init__(self, lastkey_file):
self.lastkey_file = lastkey_file
if(os.path.exists(lastkey_file)):
self.lastkey = open(lastkey_file, 'r').read()
else:
f = open(lastkey_file, 'w')
self.lastkey = self.get_lastkey()
f.write(self.lastkey)
f.close()
def new_games(self):
r = requests.get(self.url)
html = BS(r.content, 'html.parser')
new = []
items = html.select('.tiles > .items > .item > a')
for i in items:
key = self.parse_href(i['href'])
if(self.lastkey < key):
new.append(i['href'])
return new
def game_info(self, uri):
link = self.host + uri
r = requests.get(link)
html = BS(r.content, 'html.parser')
# parse poster image url
poster = re.match(r'background-image:\s*url\((.+?)\)', html.select('.image-game-logo > .image')[0]['style'])
# remove some stuff
remels = html.select('.article.article-show > *')
for remel in remels:
remel.extract()
# form data
info = {
"id": self.parse_href(uri),
"title": html.select('.article-title > a')[0].text,
"link": link,
"image": poster.group(1),
"score": self.identify_score(html.select('.game-stopgame-score > .score')[0]['class'][1]),
"excerpt": html.select('.article.article-show')[0].text[0:200] + '...'
};
return info
def download_image(self, url):
r = requests.get(url, allow_redirects=True)
a = urlparse(url)
filename = os.path.basename(a.path)
open(filename, 'wb').write(r.content)
return filename
def get_lastkey(self):
r = requests.get(self.url)
html = BS(r.content, 'html.parser')
items = html.select('.tiles > .items > .item > a')
return self.parse_href(items[0]['href'])
def parse_href(self, href):
result = re.match(r'\/show\/(\d+)', href)
return result.group(1)
def update_lastkey(self, new_key):
self.lastkey = new_key
with open(self.lastkey_file, "r+") as f:
data = f.read()
f.seek(0)
f.write(str(new_key))
f.truncate()
return new_key
сам код бота
import logging
import asyncio
from datetime import datetime
from aiogram import Bot,Dispatcher,executor,types
from sqliter import SQLiter
from ParfumeLover import StopGame
logging.basicConfig(level=logging.INFO)
bot=Bot(token=config.API_TOKEN)
dp=Dispatcher(bot)
db = SQLiter('db.db')
sg=StopGame('lastkey.txt')
@dp.message_handler(commands=['subscribe'])
async def subscribe(message: types.Message):
if(not db.subscriber_exists(message.from_user.id)):
db.add_subscriber(message.from_user.id)
else:
db.update_subscription(message.from_user.id, True)
await message.answer("Вы успешно подписались на Новинки!")
@dp.message_handler(commands=['unsubscribe'])
async def unsubscribe(message: types.Message):
if(not db.subscriber_exists(message.from_user.id)):
db.add_subscriber(message.from_user.id, False)
await message.answer("Вы и так не подписаны.")
else:
db.update_subscription(message.from_user.id, False)
await message.answer("Вы успешно отписаны от рассылки.")
async def scheduled(wait_for):
while True:
await asyncio.sleep(wait_for)
# проверяем наличие новых игр
new_games = sg.new_games()
if(new_games):
# если игры есть, переворачиваем список и итерируем
new_games.reverse()
for ng in new_games:
# парсим инфу о новой игре
nfo = sg.game_info(ng)
# получаем список подписчиков бота
subscriptions = db.get_subscriptions()
# отправляем всем новость
with open(sg.download_image(nfo['image']), 'rb') as photo:
for s in subscriptions:
await bot.send_photo(
s[1],
photo,
caption = nfo['title'] + "\n" + "Оценка: " + "\n" + nfo['excerpt'] + "\n\n" + nfo['link'],
disable_notification = True
)
# обновляем ключ
sg.update_lastkey(nfo['id'])
# запускаем лонг поллинг
if __name__ == '__main__':
dp.loop.create_task(scheduled(10)) # пока что оставим 10 секунд (в качестве теста)
executor.start_polling(dp, skip_updates=True)