openkriemy.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from random import random, randint
  2. from asyncio import sleep
  3. from datetime import datetime, timedelta, date, time
  4. from telethon import TelegramClient
  5. from telethon.events import NewMessage
  6. from telethon.utils import resolve_bot_file_id, get_peer_id
  7. from actions import get_all_birthdays
  8. from utils import parse_command, get_link_to_user, calculate_age, Kind
  9. from config import config
  10. from db import init_db
  11. from actions import (
  12. find_action,
  13. get_random_gif,
  14. is_admin,
  15. is_allowed,
  16. is_markov_enabled,
  17. get_markov_option,
  18. list_markov_chats,
  19. markov_say,
  20. )
  21. from commands import COMMANDS
  22. from markov import Markov
  23. bot = TelegramClient("openkriemy", config.API_ID, config.API_HASH).start(
  24. bot_token=config.API_TOKEN
  25. )
  26. markov = Markov()
  27. # Wait isn't that illegal??
  28. bot.markov = markov
  29. @bot.on(NewMessage)
  30. async def on_message(event):
  31. peer_id = get_peer_id(event.peer_id)
  32. try:
  33. command = parse_command(event.text)
  34. except ValueError:
  35. if await is_markov_enabled(peer_id):
  36. markov.extend_corpus(event.text)
  37. reply_prob = await get_markov_option(peer_id, "opt_reply_prob")
  38. reply = await event.get_reply_message()
  39. if (
  40. reply and get_peer_id(reply.from_id) == await bot.get_peer_id("me") and random() > 0.5
  41. ) or random() > reply_prob:
  42. await markov_say(bot, peer_id, reply_to=event)
  43. return
  44. handler = COMMANDS.get(command.name, None)
  45. if handler and handler.is_public:
  46. await handler.handler(bot, event, command)
  47. return
  48. if not await is_allowed(peer_id):
  49. if not handler or not handler.is_restricted:
  50. return
  51. if handler:
  52. if handler.is_restricted and not await is_admin(bot, event.sender):
  53. await event.reply("К сожалению, данная команда Вам недоступна.")
  54. else:
  55. await handler.handler(bot, event, command)
  56. return
  57. try:
  58. action = await find_action(command.name)
  59. except SyntaxError:
  60. return
  61. if not action:
  62. return
  63. reply_to = None
  64. target = None
  65. if action.kind != Kind.NO_TARGET:
  66. target = await event.get_reply_message()
  67. if not target:
  68. try:
  69. target = await bot.get_entity(command.args[0])
  70. except (ValueError, IndexError):
  71. if action.kind != Kind.NO_TARGET_MAYBE:
  72. await event.reply("Это действие нужно применить на кого-то!")
  73. return
  74. else:
  75. reply_to = target
  76. target = target.sender
  77. if target is None:
  78. target = await bot.get_entity(event.peer_id.channel_id)
  79. if action.kind == Kind.CANNOT_APPLY_TO_SELF and target.id == event.sender.id:
  80. await event.reply("Данное действие нельзя применять к самому себе...")
  81. return
  82. try:
  83. await event.delete()
  84. except:
  85. pass
  86. if event.sender is None:
  87. initiator = await bot.get_entity(event.peer_id.channel_id)
  88. initiator = initiator.title
  89. else:
  90. initiator = get_link_to_user(event.sender)
  91. text = action.template.format(
  92. **{"initiator": initiator, "target": get_link_to_user(target) if target else ""}
  93. )
  94. gif = await get_random_gif(action)
  95. if gif:
  96. gif = resolve_bot_file_id(gif.file_id)
  97. await bot.send_message(event.peer_id, message=text, file=gif, reply_to=reply_to)
  98. async def notify_birthdays():
  99. birthdays = await get_all_birthdays()
  100. for birthday in birthdays:
  101. age = calculate_age(birthday.date)
  102. if age.days_until < 1:
  103. try:
  104. try:
  105. entity = await bot.get_entity(birthday.user_id)
  106. except ValueError:
  107. await bot.get_participants(birthday.peer_id)
  108. entity = await bot.get_entity(birthday.user_id)
  109. await bot.send_message(
  110. birthday.peer_id,
  111. f"{get_link_to_user(entity)}, поздравляю с днём рождения!!~~",
  112. )
  113. except:
  114. pass
  115. async def notify_birthdays_loop():
  116. interval = datetime.combine(date.today(), time(hour=0, minute=0))
  117. while True:
  118. await sleep(((interval - datetime.now()) % timedelta(days=1)).total_seconds())
  119. await notify_birthdays()
  120. async def markov_say_loop():
  121. while True:
  122. await sleep(randint(30, 60 * 5))
  123. for chat in await list_markov_chats():
  124. if random() > chat.opt_message_prob:
  125. await markov_say(bot, chat.peer_id)
  126. with bot:
  127. bot.loop.run_until_complete(init_db())
  128. bot.loop.create_task(notify_birthdays_loop())
  129. bot.loop.create_task(markov_say_loop())
  130. bot.start()
  131. bot.run_until_disconnected()