main.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import logging
  2. from aiogram import Bot, Dispatcher, executor, types
  3. from aiogram.dispatcher import FSMContext
  4. from config import BOT_TOKEN, logfile, ROOT_ID
  5. from parse_vedabase import get_full_verse
  6. from users import Users
  7. from memory import memory
  8. def split_big_text(text: str, num_symbols: int) -> list[str]:
  9. messages = [p for p in text.split('\n')]
  10. message = ''
  11. for p in messages:
  12. if len(message + p) < num_symbols:
  13. print('Yes')
  14. message += f'{p}\n'
  15. else:
  16. messages.append(message)
  17. message = ''
  18. if message != '':
  19. messages.append(message)
  20. return messages
  21. users_db = Users()
  22. logging.basicConfig(filename=logfile,
  23. format='%(asctime)s %(levelname)-2s %(message)s',
  24. filemode='a',
  25. datefmt='%Y-%m-%d %H:%M:%S',
  26. level=logging.INFO)
  27. bot = Bot(token=BOT_TOKEN)
  28. dp = Dispatcher(bot)
  29. @dp.message_handler(commands=['start', 'help'])
  30. async def send_welcome(message: types.Message):
  31. """
  32. Обрабатывает команды `/start` и `/help`
  33. """
  34. # user_info = [
  35. # str(message.from_user.id),
  36. # message.from_user.first_name,
  37. # dict(message.from_user).get(
  38. # 'last_name', 'None'),
  39. # dict(message.from_user).get('username', 'None')
  40. # ]
  41. users_db.add_user(message.from_user.id)
  42. await message.reply("""To find the verse from the scripture, enter:
  43. - start with 'verse '
  44. - then enter the desired language ('en', 'nl', 'ru', 'da', 'et', 'sk', 'es', 'de', 'uk', 'lt', 'sl', 'fi', 'cs', 'hu', 'fr', 'ko', 'pt-br', 'bg', 'ja', 'zu')
  45. BG: 'verse ru bg 10.8'
  46. SB: 'verse uk sb 1.10.8'
  47. CC (adi, madhya, antya): 'verse en cc adi 10.8'""")
  48. @dp.message_handler(lambda message: message.text.lower().startswith("verse "))
  49. async def search_verse(message: types.Message):
  50. message_text = message.text.lower()
  51. if len(message_text.split()) < 4 or len(message_text.split()) > 5:
  52. return await message.reply('Wrong query string. Try /help command')
  53. query_string = message_text.split('verse ')[1]
  54. verse = get_full_verse(query_string)
  55. if 'errors' in verse:
  56. logging.warning(
  57. f"{message_text.split('verse ')[1]} - {' | '.join(verse['errors'])}")
  58. await message.reply('\n'.join(verse['errors']))
  59. else:
  60. if verse['purport_id'] == '':
  61. watch_purport = ''
  62. else:
  63. watch_purport = f"\n===============\nClick to read purport /purport_{verse['purport_id']}"
  64. await message.reply('\n\n'.join(list(verse.values())[:-1]) + watch_purport)
  65. @dp.message_handler(lambda message: message.text.startswith("/message "))
  66. async def sendind_to_users(message: types.Message):
  67. if message.from_user.id == ROOT_ID:
  68. for user in users_db.users:
  69. await bot.send_message(user, message.text.replace('/message ', ''))
  70. @dp.message_handler(lambda message: message.text.startswith("/purport_"))
  71. async def sendind_purport(message: types.Message):
  72. user_id = message.from_user.id
  73. purport_id = message.text.replace('/purport_', '')
  74. try:
  75. purport = memory.get(purport_id).decode("utf-8")
  76. except AttributeError:
  77. await message.reply(f'The link is out of date. You need to re-enter the verse number to getting text and comment.\nEx. verse en sb 1.10.8')
  78. else:
  79. try:
  80. await message.reply(purport)
  81. except aiogram.utils.exceptions.MessageIsTooLong:
  82. messages = split_big_text(purport, 4096)
  83. for m in messages:
  84. await bot.send_message(user_id, m)
  85. @dp.message_handler()
  86. async def echo(message: types.Message):
  87. await message.answer("Do not understand this message. Try /help command", reply_markup=None)
  88. if __name__ == '__main__':
  89. executor.start_polling(dp, skip_updates=True)