openkriemy.py 5.2 KB

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