openkriemy.py 2.5 KB

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