vanitybot.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import re
  2. import logging
  3. from attr import __description__
  4. from logzero import logger
  5. from aiogram.types import message
  6. from aiogram.types.message import Message, ParseMode
  7. from aiogram import Bot, Dispatcher, executor, types
  8. from config import API_TOKEN
  9. from bs4 import BeautifulSoup
  10. from requests import get
  11. from contextlib import suppress
  12. # Configure logging
  13. logging.basicConfig(level=logging.INFO)
  14. # utils funtions
  15. def get_paper_desc(id_paper: str) -> tuple:
  16. request = get(f'https://arxiv.org/abs/{id_paper}')
  17. if request.ok:
  18. soup = BeautifulSoup(request.content)
  19. with suppress(TypeError):
  20. url = soup.find('meta', property='og:url').get('content')
  21. title = soup.find('meta', property='og:title').get('content')
  22. description = soup.find('meta', property='og:description').get('content').replace('\n', ' ')
  23. return url, title, description
  24. return None
  25. # Initialize bot and dispatcher
  26. bot = Bot(token=API_TOKEN)
  27. dp = Dispatcher(bot)
  28. help_message = "Hello!\n\n\
  29. Send me a link paper from arxiv.org and \
  30. I'll send you back snipet of paper and arxiv-vanity.com mobile friendly link!\n\
  31. Or add me to chat and I'll be watching the arxiv link and \
  32. reply to them with fancy axiv-vanity links."
  33. @dp.message_handler(commands=['start'])
  34. async def process_start_command(message: types.Message):
  35. await message.reply(help_message)
  36. @dp.message_handler(commands=['help'])
  37. async def process_help_command(message: types.Message):
  38. await message.reply(help_message)
  39. @dp.message_handler(regexp='arxiv.org\/(?:abs|pdf)\/\d{4}\.\d{5}')
  40. async def vanitify(message: types.Message):
  41. papers_ids = re.findall(r'arxiv.org\/(?:abs|pdf)\/(\d{4}\.\d{5})', message.text)
  42. for id_ in papers_ids:
  43. reply_message = f"[Here you can read the paper in mobile friendly way](https://www.arxiv-vanity.com/papers/{id_})"
  44. if desc := get_paper_desc(id_):
  45. url, title, description = desc
  46. reply_message = f'{url}\n\n***{title}***\n\n{description}\n\n{reply_message}'
  47. await message.reply(reply_message, parse_mode=ParseMode.MARKDOWN)
  48. if __name__ == "__main__":
  49. executor.start_polling(dp, skip_updates=True)