openkriemy.py.bak 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from asyncio import run
  2. from telethon import TelegramClient
  3. from telethon.events import NewMessage
  4. from telethon.utils import resolve_bot_file_id
  5. from utils import parse_command, get_link_to_user
  6. from config import config
  7. from db import init_db
  8. from actions import (
  9. find_action,
  10. get_random_gif,
  11. is_admin
  12. )
  13. from commands import COMMANDS
  14. bot = TelegramClient(
  15. 'openkriemy',
  16. config.API_ID,
  17. config.API_HASH
  18. ).start(bot_token=config.API_TOKEN)
  19. @bot.on(NewMessage)
  20. async def on_message(event):
  21. try:
  22. command = parse_command(event.text)
  23. except ValueError:
  24. return
  25. handler = COMMANDS.get(command.name, None)
  26. if handler:
  27. if handler.is_restricted\
  28. and not await is_admin(bot, event.sender):
  29. await event.reply('К сожалению, данная команда Вам недоступна.')
  30. else:
  31. await handler.handler(bot, event, command)
  32. return
  33. try:
  34. action = await find_action(command.name)
  35. except SyntaxError:
  36. return
  37. if not action:
  38. return
  39. reply_to = None
  40. target = await event.get_reply_message()
  41. if not target:
  42. try:
  43. target = await bot.get_entity(command.args[0])
  44. except (ValueError, IndexError):
  45. await event.reply('Это действие нужно применить на кого-то!')
  46. return
  47. else:
  48. reply_to = target
  49. target = target.sender
  50. if target.id == event.sender.id\
  51. and not action.can_apply_to_self:
  52. await event.reply('Данное действие нельзя применять к самому себе...')
  53. return
  54. await event.delete()
  55. text = action.template.format(**{
  56. 'initiator': get_link_to_user(event.sender),
  57. 'target': get_link_to_user(target)
  58. })
  59. gif = await get_random_gif(action)
  60. if gif:
  61. gif = resolve_bot_file_id(gif.file_id)
  62. await bot.send_message(
  63. event.peer_id,
  64. message=text,
  65. file=gif,
  66. reply_to=reply_to
  67. )
  68. with bot:
  69. bot.loop.run_until_complete(init_db())
  70. bot.start()
  71. bot.run_until_disconnected()