openkriemy.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. text = event.text
  33. try:
  34. command = parse_command(text)
  35. except ValueError:
  36. if await is_markov_enabled(peer_id):
  37. markov.extend_corpus(text)
  38. for word in config.MARKOV_TRIGGER_WORDS:
  39. if word.lower() in text.lower() and random() > 0.5:
  40. await markov_say(bot, peer_id, reply_to=event)
  41. return
  42. reply_prob = await get_markov_option(peer_id, "opt_reply_prob")
  43. reply = await event.get_reply_message()
  44. if (
  45. reply and get_peer_id(reply.from_id) == await bot.get_peer_id("me") and random() > 0.5
  46. ) or random() > reply_prob:
  47. await markov_say(bot, peer_id, reply_to=event)
  48. return
  49. handler = COMMANDS.get(command.name, None)
  50. if handler and handler.is_public:
  51. await handler.handler(bot, event, command)
  52. return
  53. if not await is_allowed(peer_id):
  54. if not handler or not handler.is_restricted:
  55. return
  56. if handler:
  57. if handler.is_restricted and not await is_admin(bot, event.sender):
  58. await event.reply("К сожалению, данная команда Вам недоступна.")
  59. else:
  60. await handler.handler(bot, event, command)
  61. return
  62. try:
  63. action = await find_action(command.name)
  64. except SyntaxError:
  65. return
  66. if not action:
  67. return
  68. reply_to = None
  69. target = None
  70. if action.kind != Kind.NO_TARGET:
  71. target = await event.get_reply_message()
  72. if not target:
  73. try:
  74. target = await bot.get_entity(command.args[0])
  75. except (ValueError, IndexError):
  76. if action.kind != Kind.NO_TARGET_MAYBE:
  77. await event.reply("Это действие нужно применить на кого-то!")
  78. return
  79. else:
  80. reply_to = target
  81. target = target.sender
  82. if target is None:
  83. target = await bot.get_entity(event.peer_id.channel_id)
  84. if action.kind == Kind.CANNOT_APPLY_TO_SELF and target.id == event.sender.id:
  85. await event.reply("Данное действие нельзя применять к самому себе...")
  86. return
  87. try:
  88. await event.delete()
  89. except:
  90. pass
  91. if event.sender is None:
  92. initiator = await bot.get_entity(event.peer_id.channel_id)
  93. initiator = initiator.title
  94. else:
  95. initiator = get_link_to_user(event.sender)
  96. text = action.template.format(
  97. **{"initiator": initiator, "target": get_link_to_user(target) if target else ""}
  98. )
  99. gif = await get_random_gif(action)
  100. if gif:
  101. gif = resolve_bot_file_id(gif.file_id)
  102. await bot.send_message(event.peer_id, message=text, file=gif, reply_to=reply_to)
  103. async def notify_birthdays():
  104. birthdays = await get_all_birthdays()
  105. for birthday in birthdays:
  106. age = calculate_age(birthday.date)
  107. if age.days_until < 1:
  108. try:
  109. try:
  110. entity = await bot.get_entity(birthday.user_id)
  111. except ValueError:
  112. await bot.get_participants(birthday.peer_id)
  113. entity = await bot.get_entity(birthday.user_id)
  114. await bot.send_message(
  115. birthday.peer_id,
  116. f"{get_link_to_user(entity)}, поздравляю с днём рождения!!~~",
  117. )
  118. except:
  119. pass
  120. async def notify_birthdays_loop():
  121. interval = datetime.combine(date.today(), time(hour=0, minute=0))
  122. while True:
  123. await sleep(((interval - datetime.now()) % timedelta(days=1)).total_seconds())
  124. await notify_birthdays()
  125. async def markov_say_loop():
  126. while True:
  127. await sleep(randint(30, 60 * 5))
  128. for chat in await list_markov_chats():
  129. if random() > chat.opt_message_prob:
  130. await markov_say(bot, chat.peer_id)
  131. with bot:
  132. bot.loop.run_until_complete(init_db())
  133. bot.loop.create_task(notify_birthdays_loop())
  134. bot.loop.create_task(markov_say_loop())
  135. bot.start()
  136. bot.run_until_disconnected()