openkriemy.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. if action.kind != Kind.NO_TARGET_MAYBE:
  52. await event.reply('Это действие нужно применить на кого-то!')
  53. return
  54. else:
  55. reply_to = target
  56. target = target.sender
  57. if target is None:
  58. target = await bot.get_entity(event.peer_id.channel_id)
  59. if action.kind == Kind.CANNOT_APPLY_TO_SELF\
  60. and target.id == event.sender.id:
  61. await event.reply('Данное действие нельзя применять к самому себе...')
  62. return
  63. try:
  64. await event.delete()
  65. except:
  66. pass
  67. if event.sender is None:
  68. initiator = await bot.get_entity(event.peer_id.channel_id)
  69. initiator = initiator.title
  70. else:
  71. initiator = get_link_to_user(event.sender)
  72. text = action.template.format(**{
  73. 'initiator': initiator,
  74. 'target': get_link_to_user(target) if target else ''
  75. })
  76. gif = await get_random_gif(action)
  77. if gif:
  78. gif = resolve_bot_file_id(gif.file_id)
  79. await bot.send_message(
  80. event.peer_id,
  81. message=text,
  82. file=gif,
  83. reply_to=reply_to
  84. )
  85. with bot:
  86. bot.loop.run_until_complete(init_db())
  87. bot.start()
  88. bot.run_until_disconnected()