Queer European MD passionate about IT

custombot.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. """This module conveniently subclasses third party telepot.aio.Bot, providing the following features.
  2. - It prevents hitting Telegram flood limits by waiting between text and photo messages.
  3. - It provides command, parser, button and other decorators to associate common Telegram actions with custom handlers.
  4. - It supports multiple bots running in the same script and allows communications between them as well as complete independency from each other.
  5. - Each bot is associated with a sqlite database (using dataset third party library).
  6. Please note that you need Python3.5+ to run async code
  7. Check requirements.txt for third party dependencies.
  8. """
  9. # Standard library modules
  10. import asyncio
  11. import datetime
  12. import io
  13. import logging
  14. import os
  15. # Third party modules
  16. import dataset
  17. import telepot
  18. # Project modules
  19. from utilities import Gettable, MyOD
  20. from utilities import escape_html_chars, get_cleaned_text, make_lines_of_buttons, markdown_check, remove_html_tags, sleep_until
  21. def split_text_gracefully(text, limit, parse_mode):
  22. """Split text if it hits telegram limits for text messages.
  23. Split at `\n` if possible.
  24. Add a `[...]` at the end and beginning of split messages, with proper code markdown.
  25. """
  26. text = text.split("\n")[::-1]
  27. result = []
  28. while len(text)>0:
  29. temp=[]
  30. while len(text)>0 and len("\n".join(temp + [text[-1]]))<limit:
  31. temp.append(text.pop())
  32. if len(temp) == 0:
  33. temp.append(text[-1][:limit])
  34. text[-1] = text[-1][limit:]
  35. result.append("\n".join(temp))
  36. if len(result)>1:
  37. for i in range(1,len(result)):
  38. result[i] = "{tag[0]}[...]{tag[1]}\n{text}".format(
  39. tag=('`','`') if parse_mode=='Markdown'
  40. else ('<code>', '</code>') if parse_mode.lower() == 'html'
  41. else ('', ''),
  42. text=result[i]
  43. )
  44. result[i-1] = "{text}\n{tag[0]}[...]{tag[1]}".format(
  45. tag=('`','`') if parse_mode=='Markdown'
  46. else ('<code>', '</code>') if parse_mode.lower() == 'html'
  47. else ('', ''),
  48. text=result[i-1]
  49. )
  50. return result
  51. def make_inline_query_answer(answer):
  52. """Return an article-type answer to inline query.
  53. Takes either a string or a dictionary and returns a list."""
  54. if type(answer) is str:
  55. answer = dict(
  56. type='article',
  57. id=0,
  58. title=remove_html_tags(answer),
  59. input_message_content=dict(
  60. message_text=answer,
  61. parse_mode='HTML'
  62. )
  63. )
  64. if type(answer) is dict:
  65. answer = [answer]
  66. return answer
  67. class Bot(telepot.aio.Bot, Gettable):
  68. """telepot.aio.Bot (async Telegram bot framework) convenient subclass.
  69. === General functioning ===
  70. - While Bot.run() coroutine is executed, HTTP get requests are made to Telegram servers asking for new messages for each Bot instance.
  71. - Each message causes the proper Bot instance method coroutine to be awaited, according to its flavour (see routing_table)
  72. -- For example, chat messages cause `Bot().on_chat_message(message)` to be awaited.
  73. - This even-processing coroutine ensures the proper handling function a future and returns.
  74. -- That means that simpler tasks are completed before slower ones, since handling functions are not awaited but scheduled by `asyncio.ensure_future(handling_function(...))`
  75. -- For example, chat text messages are handled by `handle_text_message`, which looks for the proper function to elaborate the request (in bot's commands and parsers)
  76. - The handling function evaluates an answer, depending on the message content, and eventually provides a reply
  77. -- For example, `handle_text_message` sends its answer via `send_message`
  78. - All Bot.instances run simultaneously and faster requests are completed earlier.
  79. - All uncaught events are ignored.
  80. """
  81. instances = {}
  82. stop = False
  83. # Cooldown time between sent messages, to prevent hitting Telegram flood limits
  84. # Current limits: 30 total messages sent per second, 1 message per second per chat, 20 messages per minute per group
  85. COOLDOWN_TIME_ABSOLUTE = datetime.timedelta(seconds=1/30)
  86. COOLDOWN_TIME_PER_CHAT = datetime.timedelta(seconds=1)
  87. MAX_GROUP_MESSAGES_PER_MINUTE = 20
  88. # Max length of text field for a Telegram message (UTF-8 text)
  89. TELEGRAM_MESSAGES_MAX_LEN = 4096
  90. _path = os.path.dirname(__file__)
  91. _unauthorized_message = None
  92. _unknown_command_message = None
  93. _maintenance_message = None
  94. _default_inline_query_answer = [
  95. dict(
  96. type='article',
  97. id=0,
  98. title="I cannot answer this query, sorry",
  99. input_message_content=dict(
  100. message_text="I'm sorry but I could not find an answer for your query."
  101. )
  102. )
  103. ]
  104. def __init__(self, token, db_name=None):
  105. super().__init__(token)
  106. self.routing_table = {
  107. 'chat' : self.on_chat_message,
  108. 'inline_query' : self.on_inline_query,
  109. 'chosen_inline_result' : self.on_chosen_inline_result,
  110. 'callback_query' : self.on_callback_query
  111. }
  112. self.chat_message_handlers = {
  113. 'text': self.handle_text_message,
  114. 'pinned_message': self.handle_pinned_message,
  115. 'photo': self.handle_photo_message
  116. }
  117. if db_name:
  118. self.db_url = 'sqlite:///{name}{ext}'.format(
  119. name=db_name,
  120. ext='.db' if not db_name.endswith('.db') else ''
  121. )
  122. self._unauthorized_message = None
  123. self.authorization_function = lambda update, authorization_level: True
  124. self.get_chat_id = lambda update: update['message']['chat']['id'] if 'message' in update else update['chat']['id']
  125. self.commands = dict()
  126. self.callback_handlers = dict()
  127. self.inline_query_handlers = MyOD()
  128. self._default_inline_query_answer = None
  129. self.chosen_inline_result_handlers = dict()
  130. self.aliases = MyOD()
  131. self.parsers = MyOD()
  132. self.custom_parsers = dict()
  133. self.custom_photo_parsers = dict()
  134. self.bot_name = None
  135. self.default_reply_keyboard_elements = []
  136. self._default_keyboard = dict()
  137. self.run_before_loop = []
  138. self.run_after_loop = []
  139. self.to_be_obscured = []
  140. self.to_be_destroyed = []
  141. self.last_sending_time = dict(
  142. absolute=datetime.datetime.now() - self.__class__.COOLDOWN_TIME_ABSOLUTE
  143. )
  144. self._maintenance = False
  145. self._maintenance_message = None
  146. self.chat_actions = dict(
  147. pinned=MyOD()
  148. )
  149. @property
  150. def name(self):
  151. """Bot name"""
  152. return self.bot_name
  153. @property
  154. def path(self):
  155. """custombot.py file path"""
  156. return self.__class__._path
  157. @property
  158. def db(self):
  159. """Connection to bot's database
  160. It must be used inside a with statement: `with bot.db as db`
  161. """
  162. if self.db_url:
  163. return dataset.connect(self.db_url)
  164. @property
  165. def default_keyboard(self):
  166. """Default keyboard which is sent when reply_markup is left blank and chat is private.
  167. """
  168. return self._default_keyboard
  169. @property
  170. def default_inline_query_answer(self):
  171. """Answer to be returned if inline query returned None.
  172. """
  173. if self._default_inline_query_answer:
  174. return self._default_inline_query_answer
  175. return self.__class__._default_inline_query_answer
  176. @property
  177. def unauthorized_message(self):
  178. """Return this if user is unauthorized to make a request.
  179. If instance message is not set, class message is returned.
  180. """
  181. if self._unauthorized_message:
  182. return self._unauthorized_message
  183. return self.__class__._unauthorized_message
  184. @property
  185. def unknown_command_message(self):
  186. """Message to be returned if user sends an unknown command in private chat.
  187. If instance message is not set, class message is returned.
  188. """
  189. if self._unknown_command_message:
  190. return self._unknown_command_message
  191. return self.__class__._unknown_command_message
  192. @property
  193. def maintenance(self):
  194. """True if bot is under maintenance, False otherwise.
  195. While under maintenance, bot will reply with `self.maintenance_message` to any request, with few exceptions."""
  196. return self._maintenance
  197. @property
  198. def maintenance_message(self):
  199. """Message to be returned if bot is under maintenance.
  200. If instance message is not set, class message is returned.
  201. """
  202. if self._maintenance_message:
  203. return self._maintenance_message
  204. if self.__class__.maintenance_message:
  205. return self.__class__._maintenance_message
  206. return "Bot is currently under maintenance! Retry later please."
  207. @classmethod
  208. def set_class_unauthorized_message(csl, unauthorized_message):
  209. """Set class unauthorized message, to be returned if user is unauthorized to make a request.
  210. """
  211. csl._unauthorized_message = unauthorized_message
  212. @classmethod
  213. def set_class_unknown_command_message(cls, unknown_command_message):
  214. """Set class unknown command message, to be returned if user sends an unknown command in private chat.
  215. """
  216. cls._unknown_command_message = unknown_command_message
  217. @classmethod
  218. def set_class_maintenance_message(cls, maintenance_message):
  219. """Set class maintenance message, to be returned if bot is under maintenance.
  220. """
  221. cls._maintenance_message = maintenance_message
  222. @classmethod
  223. def set_class_default_inline_query_answer(cls, default_inline_query_answer):
  224. """Set class default inline query answer, to be returned if an inline query returned no answer.
  225. """
  226. cls._default_inline_query_answer = default_inline_query_answer
  227. def set_unauthorized_message(self, unauthorized_message):
  228. """Set instance unauthorized message
  229. If instance message is None, default class message is used.
  230. """
  231. self._unauthorized_message = unauthorized_message
  232. def set_unknown_command_message(self, unknown_command_message):
  233. """Set instance unknown command message, to be returned if user sends an unknown command in private chat.
  234. If instance message is None, default class message is used.
  235. """
  236. self._unknown_command_message = unknown_command_message
  237. def set_maintenance_message(self, maintenance_message):
  238. """Set instance maintenance message, to be returned if bot is under maintenance.
  239. If instance message is None, default class message is used.
  240. """
  241. self._maintenance_message = maintenance_message
  242. def set_default_inline_query_answer(self, default_inline_query_answer):
  243. """Set a custom default_inline_query_answer to be returned when no answer is found for an inline query.
  244. If instance answer is None, default class answer is used.
  245. """
  246. if type(default_inline_query_answer) in (str, dict):
  247. default_inline_query_answer = make_inline_query_answer(default_inline_query_answer)
  248. if type(default_inline_query_answer) is not list:
  249. return 1
  250. self._default_inline_query_answer = default_inline_query_answer
  251. return 0
  252. def set_maintenance(self, maintenance_message):
  253. """Puts the bot under maintenance or ends it.
  254. While in maintenance, bot will reply to users with maintenance_message.
  255. Bot will accept /coma, /stop and /restart commands from admins.
  256. s"""
  257. self._maintenance = not self.maintenance
  258. if maintenance_message:
  259. self.set_maintenance_message(maintenance_message)
  260. if self.maintenance:
  261. return "<i>Bot has just been put under maintenance!</i>\n\nUntil further notice, it will reply to users with the following message:\n\n{}".format(
  262. self.maintenance_message
  263. )
  264. return "<i>Maintenance ended!</i>"
  265. def set_authorization_function(self, authorization_function):
  266. """Set a custom authorization_function, which evaluates True if user is authorized to perform a specific action and False otherwise.
  267. It should take update and role and return a Boolean.
  268. Default authorization_function always evaluates True.
  269. """
  270. self.authorization_function = authorization_function
  271. def set_get_chat_id_function(self, get_chat_id_function):
  272. """Set a custom get_chat_id function which takes and update and returns the chat in which a reply should be sent.
  273. For instance, bots could reply in private to group messages as a default behaviour.
  274. Default chat_id returned is current chat id.
  275. """
  276. self.get_chat_id = get_chat_id_function
  277. async def avoid_flooding(self, chat_id):
  278. """asyncio-sleep until COOLDOWN_TIME (per_chat and absolute) has passed.
  279. To prevent hitting Telegram flood limits, send_message and send_photo await this function.
  280. """
  281. if type(chat_id) is int and chat_id > 0:
  282. while (
  283. datetime.datetime.now() < self.last_sending_time['absolute'] + self.__class__.COOLDOWN_TIME_ABSOLUTE
  284. ) or (
  285. chat_id in self.last_sending_time
  286. and datetime.datetime.now() < self.last_sending_time[chat_id] + self.__class__.COOLDOWN_TIME_PER_CHAT
  287. ):
  288. await asyncio.sleep(self.__class__.COOLDOWN_TIME_ABSOLUTE.seconds)
  289. self.last_sending_time[chat_id] = datetime.datetime.now()
  290. else:
  291. while (
  292. datetime.datetime.now() < self.last_sending_time['absolute'] + self.__class__.COOLDOWN_TIME_ABSOLUTE
  293. ) or (
  294. chat_id in self.last_sending_time
  295. and len(
  296. [
  297. sending_datetime
  298. for sending_datetime in self.last_sending_time[chat_id]
  299. if sending_datetime >= datetime.datetime.now() - datetime.timedelta(minutes=1)
  300. ]
  301. ) >= self.__class__.MAX_GROUP_MESSAGES_PER_MINUTE
  302. ) or (
  303. chat_id in self.last_sending_time
  304. and len(self.last_sending_time[chat_id]) > 0
  305. and datetime.datetime.now() < self.last_sending_time[chat_id][-1] + self.__class__.COOLDOWN_TIME_PER_CHAT
  306. ):
  307. await asyncio.sleep(0.5)
  308. if chat_id not in self.last_sending_time:
  309. self.last_sending_time[chat_id] = []
  310. self.last_sending_time[chat_id].append(datetime.datetime.now())
  311. self.last_sending_time[chat_id] = [
  312. sending_datetime
  313. for sending_datetime in self.last_sending_time[chat_id]
  314. if sending_datetime >= datetime.datetime.now() - datetime.timedelta(minutes=1)
  315. ]
  316. self.last_sending_time['absolute'] = datetime.datetime.now()
  317. return
  318. async def on_inline_query(self, update):
  319. """Schedule handling of received inline queries.
  320. Notice that handling is only scheduled, not awaited.
  321. This means that all Bot instances may now handle other requests before this one is completed.
  322. """
  323. asyncio.ensure_future(self.handle_inline_query(update))
  324. return
  325. async def on_chosen_inline_result(self, update):
  326. """Schedule handling of received chosen inline result events.
  327. Notice that handling is only scheduled, not awaited.
  328. This means that all Bot instances may now handle other requests before this one is completed.
  329. """
  330. asyncio.ensure_future(self.handle_chosen_inline_result(update))
  331. return
  332. async def on_callback_query(self, update):
  333. """Schedule handling of received callback queries.
  334. A callback query is sent when users press inline keyboard buttons.
  335. Bad clients may send malformed or deceiving callback queries: never use secret keys in buttons and always check request validity!
  336. Notice that handling is only scheduled, not awaited.
  337. This means that all Bot instances may now handle other requests before this one is completed.
  338. """
  339. # Reject malformed updates lacking of data field
  340. if 'data' not in update:
  341. return
  342. asyncio.ensure_future(self.handle_callback_query(update))
  343. return
  344. async def on_chat_message(self, update):
  345. """Schedule handling of received chat message.
  346. Notice that handling is only scheduled, not awaited.
  347. According to update type, the corresponding handler is scheduled (see self.chat_message_handlers).
  348. This means that all Bot instances may now handle other requests before this one is completed.
  349. """
  350. answer = None
  351. content_type, chat_type, chat_id = telepot.glance(
  352. update,
  353. flavor='chat',
  354. long=False
  355. )
  356. if content_type in self.chat_message_handlers:
  357. answer = asyncio.ensure_future(
  358. self.chat_message_handlers[content_type](update)
  359. )
  360. else:
  361. answer = None
  362. logging.debug("Unhandled message")
  363. return answer
  364. async def handle_inline_query(self, update):
  365. """Handle inline query and answer it with results, or log errors.
  366. """
  367. query = update['query']
  368. answer = None
  369. switch_pm_text, switch_pm_parameter = None, None
  370. if self.maintenance:
  371. answer = self.maintenance_message
  372. else:
  373. for condition, handler in self.inline_query_handlers.items():
  374. answerer = handler['function']
  375. if condition(update['query']):
  376. if asyncio.iscoroutinefunction(answerer):
  377. answer = await answerer(update)
  378. else:
  379. answer = answerer(update)
  380. break
  381. if not answer:
  382. answer = self.default_inline_query_answer
  383. if type(answer) is dict:
  384. if 'switch_pm_text' in answer:
  385. switch_pm_text = answer['switch_pm_text']
  386. if 'switch_pm_parameter' in answer:
  387. switch_pm_parameter = answer['switch_pm_parameter']
  388. answer = answer['answer']
  389. if type(answer) is str:
  390. answer = make_inline_query_answer(answer)
  391. try:
  392. await self.answerInlineQuery(
  393. update['id'],
  394. answer,
  395. cache_time=10,
  396. is_personal=True,
  397. switch_pm_text=switch_pm_text,
  398. switch_pm_parameter=switch_pm_parameter
  399. )
  400. except Exception as e:
  401. logging.info("Error answering inline query\n{}".format(e))
  402. return
  403. async def handle_chosen_inline_result(self, update):
  404. """If chosen inline result id is in self.chosen_inline_result_handlers, call the related function passing the update as argument."""
  405. user_id = update['from']['id'] if 'from' in update else None
  406. if self.maintenance:
  407. return
  408. if user_id in self.chosen_inline_result_handlers:
  409. result_id = update['result_id']
  410. handlers = self.chosen_inline_result_handlers[user_id]
  411. if result_id in handlers:
  412. func = handlers[result_id]
  413. if asyncio.iscoroutinefunction(func):
  414. await func(update)
  415. else:
  416. func(update)
  417. return
  418. def set_inline_result_handler(self, user_id, result_id, func):
  419. """Associate a func to a result_id: when an inline result is chosen having that id, function will be passed the update as argument."""
  420. if type(user_id) is dict:
  421. user_id = user_id['from']['id']
  422. assert type(user_id) is int, "user_id must be int!"
  423. result_id = str(result_id) # Query result ids are parsed as str by telegram
  424. assert callable(func), "func must be a callable"
  425. if user_id not in self.chosen_inline_result_handlers:
  426. self.chosen_inline_result_handlers[user_id] = {}
  427. self.chosen_inline_result_handlers[user_id][result_id] = func
  428. return
  429. async def handle_callback_query(self, update):
  430. """Get an answer from the callback handler associated to the query prefix.
  431. The answer is used to edit the source message or send new ones if text is longer than single message limit.
  432. Anyway, the query is answered, otherwise the client would hang and the bot would look like idle.
  433. """
  434. answer = None
  435. if self.maintenance:
  436. answer = remove_html_tags(self.maintenance_message[:45])
  437. else:
  438. data = update['data']
  439. for start_text, handler in self.callback_handlers.items():
  440. answerer = handler['function']
  441. if data.startswith(start_text):
  442. if asyncio.iscoroutinefunction(answerer):
  443. answer = await answerer(update)
  444. else:
  445. answer = answerer(update)
  446. break
  447. if answer:
  448. if type(answer) is str:
  449. answer = {'text': answer}
  450. if type(answer) is not dict:
  451. return
  452. if 'edit' in answer:
  453. if 'message' in update:
  454. message_identifier = telepot.message_identifier(update['message'])
  455. else:
  456. message_identifier = telepot.message_identifier(update)
  457. edit = answer['edit']
  458. reply_markup = edit['reply_markup'] if 'reply_markup' in edit else None
  459. text = edit['text'] if 'text' in edit else None
  460. caption = edit['caption'] if 'caption' in edit else None
  461. parse_mode = edit['parse_mode'] if 'parse_mode' in edit else None
  462. disable_web_page_preview = edit['disable_web_page_preview'] if 'disable_web_page_preview' in edit else None
  463. try:
  464. if 'text' in edit:
  465. if len(text) > self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 200:
  466. if 'from' in update:
  467. await self.send_message(
  468. chat_id=update['from']['id'],
  469. text=text,
  470. reply_markup=reply_markup,
  471. parse_mode=parse_mode,
  472. disable_web_page_preview=disable_web_page_preview
  473. )
  474. else:
  475. await self.editMessageText(
  476. msg_identifier=message_identifier,
  477. text=text,
  478. parse_mode=parse_mode,
  479. disable_web_page_preview=disable_web_page_preview,
  480. reply_markup=reply_markup
  481. )
  482. elif 'caption' in edit:
  483. await self.editMessageCaption(
  484. msg_identifier=message_identifier,
  485. caption=caption,
  486. reply_markup=reply_markup
  487. )
  488. elif 'reply_markup' in edit:
  489. await self.editMessageReplyMarkup(
  490. msg_identifier=message_identifier,
  491. reply_markup=reply_markup
  492. )
  493. except Exception as e:
  494. logging.info("Message was not modified:\n{}".format(e))
  495. text = answer['text'][:180] if 'text' in answer else None
  496. show_alert = answer['show_alert'] if 'show_alert' in answer else None
  497. cache_time = answer['cache_time'] if 'cache_time' in answer else None
  498. try:
  499. await self.answerCallbackQuery(
  500. callback_query_id=update['id'],
  501. text=text,
  502. show_alert=show_alert,
  503. cache_time=cache_time
  504. )
  505. except telepot.exception.TelegramError as e:
  506. logging.error(e)
  507. else:
  508. try:
  509. await self.answerCallbackQuery(callback_query_id=update['id'])
  510. except telepot.exception.TelegramError as e:
  511. logging.error(e)
  512. return
  513. async def handle_text_message(self, update):
  514. """Answer to chat text messages.
  515. 1) Ignore bot name (case-insensitive) and search bot custom parsers, commands, aliases and parsers for an answerer.
  516. 2) Get an answer from answerer(update).
  517. 3) Send it to the user.
  518. """
  519. answerer, answer = None, None
  520. # Lower text and replace only bot's tag, meaning that `/command@OtherBot` will be ignored.
  521. text = update['text'].lower().replace('@{}'.format(self.name.lower()),'')
  522. user_id = update['from']['id'] if 'from' in update else None
  523. if self.maintenance and not any(
  524. text.startswith(x)
  525. for x in ('/coma', '/restart')
  526. ):
  527. if update['chat']['id']>0:
  528. answer = self.maintenance_message
  529. elif user_id in self.custom_parsers:
  530. answerer = self.custom_parsers[user_id]
  531. del self.custom_parsers[user_id]
  532. elif text.startswith('/'):
  533. command = text.split()[0].strip(' /@')
  534. if command in self.commands:
  535. answerer = self.commands[command]['function']
  536. elif update['chat']['id']>0:
  537. answer = self.unknown_command_message
  538. else:
  539. # If text starts with an alias (case insensitive: text and alias are both .lower()):
  540. for alias, parser in self.aliases.items():
  541. if text.startswith(alias.lower()):
  542. answerer = parser
  543. break
  544. # If update matches any parser
  545. for check_function, parser in self.parsers.items():
  546. if (
  547. parser['argument'] == 'text'
  548. and check_function(text)
  549. ) or (
  550. parser['argument'] == 'update'
  551. and check_function(update)
  552. ):
  553. answerer = parser['function']
  554. break
  555. if answerer:
  556. if asyncio.iscoroutinefunction(answerer):
  557. answer = await answerer(update)
  558. else:
  559. answer = answerer(update)
  560. if answer:
  561. try:
  562. return await self.send_message(answer=answer, chat_id=update)
  563. except Exception as e:
  564. logging.error("Failed to process answer:\n{}".format(e), exc_info=True)
  565. async def handle_pinned_message(self, update):
  566. """Handle pinned message chat action."""
  567. if self.maintenance:
  568. return
  569. answerer = None
  570. for criteria, handler in self.chat_actions['pinned'].items():
  571. if criteria(update):
  572. answerer = handler['function']
  573. break
  574. if answerer is None:
  575. return
  576. elif asyncio.iscoroutinefunction(answerer):
  577. answer = await answerer(update)
  578. else:
  579. answer = answerer(update)
  580. if answer:
  581. try:
  582. return await self.send_message(answer=answer, chat_id=update['chat']['id'])
  583. except Exception as e:
  584. logging.error("Failed to process answer:\n{}".format(e), exc_info=True)
  585. return
  586. async def handle_photo_message(self, update):
  587. """Handle photo chat message"""
  588. user_id = update['from']['id'] if 'from' in update else None
  589. answerer, answer = None, None
  590. if self.maintenance:
  591. if update['chat']['id']>0:
  592. answer = self.maintenance_message
  593. elif user_id in self.custom_photo_parsers:
  594. answerer = self.custom_photo_parsers[user_id]
  595. del self.custom_photo_parsers[user_id]
  596. if answerer:
  597. if asyncio.iscoroutinefunction(answerer):
  598. answer = await answerer(update)
  599. else:
  600. answer = answerer(update)
  601. if answer:
  602. try:
  603. return await self.send_message(answer=answer, chat_id=update)
  604. except Exception as e:
  605. logging.error("Failed to process answer:\n{}".format(e), exc_info=True)
  606. return
  607. def set_custom_parser(self, parser, update=None, user=None):
  608. """Set a custom parser for the user.
  609. Any chat message update coming from the user will be handled by this custom parser instead of default parsers (commands, aliases and text parsers).
  610. Custom parsers last one single use, but their handler can call this function to provide multiple tries.
  611. """
  612. if user and type(user) is int:
  613. pass
  614. elif type(update) is int:
  615. user = update
  616. elif type(user) is dict:
  617. user = user['from']['id'] if 'from' in user and 'id' in user['from'] else None
  618. elif not user and type(update) is dict:
  619. user = update['from']['id'] if 'from' in update and 'id' in update['from'] else None
  620. else:
  621. raise TypeError('Invalid user.\nuser: {}\nupdate: {}'.format(user, update))
  622. if not type(user) is int:
  623. raise TypeError('User {} is not an int id'.format(user))
  624. if not callable(parser):
  625. raise TypeError('Parser {} is not a callable'.format(parser.__name__))
  626. self.custom_parsers[user] = parser
  627. return
  628. def set_custom_photo_parser(self, parser, update=None, user=None):
  629. """Set a custom photo parser for the user.
  630. Any photo chat update coming from the user will be handled by this custom parser instead of default parsers.
  631. Custom photo parsers last one single use, but their handler can call this function to provide multiple tries.
  632. """
  633. if user and type(user) is int:
  634. pass
  635. elif type(update) is int:
  636. user = update
  637. elif type(user) is dict:
  638. user = user['from']['id'] if 'from' in user and 'id' in user['from'] else None
  639. elif not user and type(update) is dict:
  640. user = update['from']['id'] if 'from' in update and 'id' in update['from'] else None
  641. else:
  642. raise TypeError('Invalid user.\nuser: {}\nupdate: {}'.format(user, update))
  643. if not type(user) is int:
  644. raise TypeError('User {} is not an int id'.format(user))
  645. if not callable(parser):
  646. raise TypeError('Parser {} is not a callable'.format(parser.__name__))
  647. self.custom_photo_parsers[user] = parser
  648. return
  649. def command(self, command, aliases=None, show_in_keyboard=False, descr="", auth='admin'):
  650. """
  651. Decorator: `@bot.command(*args)`
  652. When a message text starts with `/command[@bot_name]`, or with an alias, it gets passed to the decorated function.
  653. `command` is the command name (with or without /)
  654. `aliases` is a list of aliases
  655. `show_in_keyboard`, if True, makes first alias appear in default_keyboard
  656. `descr` is a description
  657. `auth` is the lowest authorization level needed to run the command
  658. """
  659. command = command.replace('/','').lower()
  660. if not isinstance(command, str):
  661. raise TypeError('Command {} is not a string'.format(command))
  662. if aliases:
  663. if not isinstance(aliases, list):
  664. raise TypeError('Aliases is not a list: {}'.format(aliases))
  665. for alias in aliases:
  666. if not isinstance(alias, str):
  667. raise TypeError('Alias {} is not a string'.format(alias))
  668. def decorator(func):
  669. if asyncio.iscoroutinefunction(func):
  670. async def decorated(message):
  671. logging.info("COMMAND({}) @{} FROM({})".format(command, self.name, message['from'] if 'from' in message else message['chat']))
  672. if self.authorization_function(message, auth):
  673. return await func(message)
  674. return self.unauthorized_message
  675. else:
  676. def decorated(message):
  677. logging.info("COMMAND({}) @{} FROM({})".format(command, self.name, message['from'] if 'from' in message else message['chat']))
  678. if self.authorization_function(message, auth):
  679. return func(message)
  680. return self.unauthorized_message
  681. self.commands[command] = dict(
  682. function=decorated,
  683. descr=descr,
  684. auth=auth
  685. )
  686. if aliases:
  687. for alias in aliases:
  688. self.aliases[alias] = decorated
  689. if show_in_keyboard:
  690. self.default_reply_keyboard_elements.append(aliases[0])
  691. return decorator
  692. def parser(self, condition, descr='', auth='admin', argument='text'):
  693. """
  694. Decorator: `@bot.parser(condition)`
  695. If condition evaluates True when run on a message text (not starting with '/'), such decorated function gets called on update.
  696. Conditions of parsers are evaluated in order; when one is True, others will be skipped.
  697. `descr` is a description
  698. `auth` is the lowest authorization level needed to run the command
  699. """
  700. if not callable(condition):
  701. raise TypeError('Condition {} is not a callable'.format(condition.__name__))
  702. def decorator(func):
  703. if asyncio.iscoroutinefunction(func):
  704. async def decorated(message):
  705. logging.info("TEXT MATCHING CONDITION({}) @{} FROM({})".format(condition.__name__, self.name, message['from']))
  706. if self.authorization_function(message, auth):
  707. return await func(message)
  708. return self.unauthorized_message
  709. else:
  710. def decorated(message):
  711. logging.info("TEXT MATCHING CONDITION({}) @{} FROM({})".format(condition.__name__, self.name, message['from']))
  712. if self.authorization_function(message, auth):
  713. return func(message)
  714. return self.unauthorized_message
  715. self.parsers[condition] = dict(
  716. function=decorated,
  717. descr=descr,
  718. auth=auth,
  719. argument=argument
  720. )
  721. return decorator
  722. def pinned(self, condition, descr='', auth='admin'):
  723. """
  724. Decorator: `@bot.pinned(condition)`
  725. If condition evaluates True when run on a pinned_message update, such decorated function gets called on update.
  726. Conditions are evaluated in order; when one is True, others will be skipped.
  727. `descr` is a description
  728. `auth` is the lowest authorization level needed to run the command
  729. """
  730. if not callable(condition):
  731. raise TypeError('Condition {} is not a callable'.format(condition.__name__))
  732. def decorator(func):
  733. if asyncio.iscoroutinefunction(func):
  734. async def decorated(message):
  735. logging.info("CHAT ACTION MATCHING CONDITION({}) @{} FROM({})".format(condition.__name__, self.name, message['from']))
  736. if self.authorization_function(message, auth):
  737. return await func(message)
  738. return# self.unauthorized_message
  739. else:
  740. def decorated(message):
  741. logging.info("CHAT ACTION MATCHING CONDITION({}) @{} FROM({})".format(condition.__name__, self.name, message['from']))
  742. if self.authorization_function(message, auth):
  743. return func(message)
  744. return# self.unauthorized_message
  745. self.chat_actions['pinned'][condition] = dict(
  746. function=decorated,
  747. descr=descr,
  748. auth=auth
  749. )
  750. return decorator
  751. def button(self, data, descr='', auth='admin'):
  752. """
  753. Decorator: `@bot.button('example:///')`
  754. When a callback data text starts with <data>, it gets passed to the decorated function
  755. `descr` is a description
  756. `auth` is the lowest authorization level needed to run the command
  757. """
  758. if not isinstance(data, str):
  759. raise TypeError('Inline button callback_data {} is not a string'.format(data))
  760. def decorator(func):
  761. if asyncio.iscoroutinefunction(func):
  762. async def decorated(message):
  763. logging.info("INLINE BUTTON({}) @{} FROM({})".format(message['data'], self.name, message['from']))
  764. if self.authorization_function(message, auth):
  765. return await func(message)
  766. return self.unauthorized_message
  767. else:
  768. def decorated(message):
  769. logging.info("INLINE BUTTON({}) @{} FROM({})".format(message['data'], self.name, message['from']))
  770. if self.authorization_function(message, auth):
  771. return func(message)
  772. return self.unauthorized_message
  773. self.callback_handlers[data] = dict(
  774. function=decorated,
  775. descr=descr,
  776. auth=auth
  777. )
  778. return decorator
  779. def query(self, condition, descr='', auth='admin'):
  780. """
  781. Decorator: `@bot.query(example)`
  782. When an inline query matches the `condition` function, decorated function is called and passed the query update object as argument.
  783. `descr` is a description
  784. `auth` is the lowest authorization level needed to run the command
  785. """
  786. if not callable(condition):
  787. raise TypeError('Condition {} is not a callable'.format(condition.__name__))
  788. def decorator(func):
  789. if asyncio.iscoroutinefunction(func):
  790. async def decorated(message):
  791. logging.info("QUERY MATCHING CONDITION({}) @{} FROM({})".format(condition.__name__, self.name, message['from']))
  792. if self.authorization_function(message, auth):
  793. return await func(message)
  794. return self.unauthorized_message
  795. else:
  796. def decorated(message):
  797. logging.info("QUERY MATCHING CONDITION({}) @{} FROM({})".format(condition.__name__, self.name, message['from']))
  798. if self.authorization_function(message, auth):
  799. return func(message)
  800. return self.unauthorized_message
  801. self.inline_query_handlers[condition] = dict(
  802. function=decorated,
  803. descr=descr,
  804. auth=auth
  805. )
  806. return decorator
  807. def additional_task(self, when='BEFORE'):
  808. """Decorator: such decorated async functions get awaited BEFORE or AFTER messageloop"""
  809. when = when[0].lower()
  810. def decorator(func):
  811. if when == 'b':
  812. self.run_before_loop.append(func())
  813. elif when == 'a':
  814. self.run_after_loop.append(func())
  815. return decorator
  816. def set_default_keyboard(self, keyboard='set_default'):
  817. """Set a default keyboard for the bot.
  818. If a keyboard is not passed as argument, a default one is generated, based on aliases of commands.
  819. """
  820. if keyboard=='set_default':
  821. btns = [
  822. dict(
  823. text=x
  824. )
  825. for x in self.default_reply_keyboard_elements
  826. ]
  827. row_len = 2 if len(btns) < 4 else 3
  828. self._default_keyboard = dict(
  829. keyboard=make_lines_of_buttons(
  830. btns,
  831. row_len
  832. ),
  833. resize_keyboard=True
  834. )
  835. else:
  836. self._default_keyboard = keyboard
  837. return
  838. async def edit_message(self, update, *args, **kwargs):
  839. """Edit given update with given *args and **kwargs.
  840. Please note, that it is currently only possible to edit messages without reply_markup or with inline keyboards.
  841. """
  842. try:
  843. return await self.editMessageText(
  844. telepot.message_identifier(update),
  845. *args,
  846. **kwargs
  847. )
  848. except Exception as e:
  849. logging.error("{}".format(e))
  850. async def delete_message(self, update, *args, **kwargs):
  851. """Delete given update with given *args and **kwargs.
  852. Please note, that a bot can delete only messages sent by itself or sent in a group which it is administrator of.
  853. """
  854. try:
  855. return await self.deleteMessage(
  856. telepot.message_identifier(update),
  857. *args,
  858. **kwargs
  859. )
  860. except Exception as e:
  861. logging.error("{}".format(e))
  862. async def send_message(self, answer=dict(), chat_id=None, text='', parse_mode="HTML", disable_web_page_preview=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
  863. """Convenient method to call telepot.Bot(token).sendMessage
  864. All sendMessage **kwargs can be either **kwargs of send_message or key:val of answer argument.
  865. Messages longer than telegram limit will be split properly.
  866. Telegram flood limits won't be reached thanks to `await avoid_flooding(chat_id)`
  867. parse_mode will be checked and edited if necessary.
  868. Arguments will be checked and adapted.
  869. """
  870. if type(answer) is dict and 'chat_id' in answer:
  871. chat_id = answer['chat_id']
  872. # chat_id may simply be the update to which the bot should repy: get_chat_id is called
  873. if type(chat_id) is dict:
  874. chat_id = self.get_chat_id(chat_id)
  875. if type(answer) is str:
  876. text = answer
  877. if not reply_markup and chat_id > 0 and text!=self.unauthorized_message:
  878. reply_markup = self.default_keyboard
  879. elif type(answer) is dict:
  880. if 'text' in answer:
  881. text = answer['text']
  882. if 'parse_mode' in answer:
  883. parse_mode = answer['parse_mode']
  884. if 'disable_web_page_preview' in answer:
  885. disable_web_page_preview = answer['disable_web_page_preview']
  886. if 'disable_notification' in answer:
  887. disable_notification = answer['disable_notification']
  888. if 'reply_to_message_id' in answer:
  889. reply_to_message_id = answer['reply_to_message_id']
  890. if 'reply_markup' in answer:
  891. reply_markup = answer['reply_markup']
  892. elif not reply_markup and type(chat_id) is int and chat_id > 0 and text!=self.unauthorized_message:
  893. reply_markup = self.default_keyboard
  894. assert type(text) is str, "Text is not a string!"
  895. assert (
  896. type(chat_id) is int
  897. or (type(chat_id) is str and chat_id.startswith('@'))
  898. ), "Invalid chat_id:\n\t\t{}".format(chat_id)
  899. if not text:
  900. return
  901. parse_mode = str(parse_mode)
  902. text_chunks = split_text_gracefully(
  903. text=text,
  904. limit=self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 100,
  905. parse_mode=parse_mode
  906. )
  907. n = len(text_chunks)
  908. for text_chunk in text_chunks:
  909. n-=1
  910. if parse_mode.lower() == "html":
  911. this_parse_mode = "HTML"
  912. # Check that all tags are well-formed
  913. if not markdown_check(
  914. text_chunk,
  915. [
  916. "<", ">",
  917. "code>", "bold>", "italic>",
  918. "b>", "i>", "a>", "pre>"
  919. ]
  920. ):
  921. this_parse_mode = "None"
  922. text_chunk = "!!![invalid markdown syntax]!!!\n\n" + text_chunk
  923. elif parse_mode != "None":
  924. this_parse_mode = "Markdown"
  925. # Check that all markdowns are well-formed
  926. if not markdown_check(
  927. text_chunk,
  928. [
  929. "*", "_", "`"
  930. ]
  931. ):
  932. this_parse_mode = "None"
  933. text_chunk = "!!![invalid markdown syntax]!!!\n\n" + text_chunk
  934. else:
  935. this_parse_mode = parse_mode
  936. this_reply_markup = reply_markup if n==0 else None
  937. try:
  938. await self.avoid_flooding(chat_id)
  939. result = await self.sendMessage(
  940. chat_id=chat_id,
  941. text=text_chunk,
  942. parse_mode=this_parse_mode,
  943. disable_web_page_preview=disable_web_page_preview,
  944. disable_notification=disable_notification,
  945. reply_to_message_id=reply_to_message_id,
  946. reply_markup=this_reply_markup
  947. )
  948. except Exception as e:
  949. logging.debug(e, exc_info=False) # Set exc_info=True for more information
  950. result = e
  951. return result
  952. async def send_photo(self, chat_id=None, answer={}, photo=None, caption='', parse_mode='HTML', disable_notification=None, reply_to_message_id=None,reply_markup=None, use_stored=True, second_chance=False):
  953. """Convenient method to call telepot.Bot(token).sendPhoto
  954. All sendPhoto **kwargs can be either **kwargs of send_message or key:val of answer argument.
  955. Captions longer than telegram limit will be shortened gently.
  956. Telegram flood limits won't be reached thanks to `await avoid_flooding(chat_id)`
  957. Most arguments will be checked and adapted.
  958. If use_stored is set to True, the bot will store sent photo telegram_id and use it for faster sending next times (unless future errors).
  959. Sending photos by their file_id already stored on telegram servers is way faster: that's why bot stores and uses this info, if required.
  960. A second_chance is given to send photo on error.
  961. """
  962. if 'chat_id' in answer:
  963. chat_id = answer['chat_id']
  964. # chat_id may simply be the update to which the bot should repy: get_chat_id is called
  965. if type(chat_id) is dict:
  966. chat_id = self.get_chat_id(chat_id)
  967. assert (
  968. type(chat_id) is int
  969. or (type(chat_id) is str and chat_id.startswith('@'))
  970. ), "Invalid chat_id:\n\t\t{}".format(chat_id)
  971. if 'photo' in answer:
  972. photo = answer['photo']
  973. assert photo is not None, "Null photo!"
  974. if 'caption' in answer:
  975. caption = answer['caption']
  976. if 'parse_mode' in answer:
  977. parse_mode = answer['parse_mode']
  978. if 'disable_notification' in answer:
  979. disable_notification = answer['disable_notification']
  980. if 'reply_to_message_id' in answer:
  981. reply_to_message_id = answer['reply_to_message_id']
  982. if 'reply_markup' in answer:
  983. reply_markup = answer['reply_markup']
  984. already_sent = False
  985. if type(photo) is str:
  986. photo_url = photo
  987. with self.db as db:
  988. already_sent = db['sent_pictures'].find_one(url=photo_url, errors=False)
  989. if already_sent and use_stored:
  990. photo = already_sent['file_id']
  991. already_sent = True
  992. else:
  993. already_sent = False
  994. if not any(photo_url.startswith(x) for x in ['http', 'www']):
  995. with io.BytesIO() as buffered_picture:
  996. with open("{}/{}".format(self.path, photo_url), 'rb') as photo_file:
  997. buffered_picture.write(photo_file.read())
  998. photo = buffered_picture.getvalue()
  999. caption = escape_html_chars(caption)
  1000. if len(caption) > 199:
  1001. new_caption = ''
  1002. tag = False
  1003. tag_body = False
  1004. count = 0
  1005. temp = ''
  1006. for char in caption:
  1007. if tag and char == '>':
  1008. tag = False
  1009. elif char == '<':
  1010. tag = True
  1011. tag_body = not tag_body
  1012. elif not tag:
  1013. count += 1
  1014. if count == 199:
  1015. break
  1016. temp += char
  1017. if not tag_body:
  1018. new_caption += temp
  1019. temp = ''
  1020. caption = new_caption
  1021. sent = None
  1022. try:
  1023. await self.avoid_flooding(chat_id)
  1024. sent = await self.sendPhoto(
  1025. chat_id=chat_id,
  1026. photo=photo,
  1027. caption=caption,
  1028. parse_mode=parse_mode,
  1029. disable_notification=disable_notification,
  1030. reply_to_message_id=reply_to_message_id,
  1031. reply_markup=reply_markup
  1032. )
  1033. if isinstance(sent, Exception):
  1034. raise Exception("SendingFailed")
  1035. except Exception as e:
  1036. logging.error("Error sending photo\n{}".format(e), exc_info=False) # Set exc_info=True for more information
  1037. if already_sent:
  1038. with self.db as db:
  1039. db['sent_pictures'].update(
  1040. dict(
  1041. url=photo_url,
  1042. errors=True
  1043. ),
  1044. ['url']
  1045. )
  1046. if not second_chance:
  1047. logging.info("Trying again (only once)...")
  1048. sent = await self.send_photo(
  1049. chat_id=chat_id,
  1050. answer=answer,
  1051. photo=photo,
  1052. caption=caption,
  1053. parse_mode=parse_mode,
  1054. disable_notification=disable_notification,
  1055. reply_to_message_id=reply_to_message_id,
  1056. reply_markup=reply_markup,
  1057. second_chance=True
  1058. )
  1059. if (
  1060. sent is not None
  1061. and hasattr(sent, '__getitem__')
  1062. and 'photo' in sent
  1063. and len(sent['photo'])>0
  1064. and 'file_id' in sent['photo'][0]
  1065. and (not already_sent)
  1066. and use_stored
  1067. ):
  1068. with self.db as db:
  1069. db['sent_pictures'].insert(
  1070. dict(
  1071. url=photo_url,
  1072. file_id=sent['photo'][0]['file_id'],
  1073. errors=False
  1074. )
  1075. )
  1076. return sent
  1077. async def send_and_destroy(self, chat_id, answer, timer=60, mode='text', **kwargs):
  1078. """Send a message or photo and delete it after `timer` seconds"""
  1079. if mode == 'text':
  1080. sent_message = await self.send_message(
  1081. chat_id=chat_id,
  1082. answer=answer,
  1083. **kwargs
  1084. )
  1085. elif mode == 'pic':
  1086. sent_message = await self.send_photo(
  1087. chat_id=chat_id,
  1088. answer=answer,
  1089. **kwargs
  1090. )
  1091. if sent_message is None:
  1092. return
  1093. self.to_be_destroyed.append(sent_message)
  1094. await asyncio.sleep(timer)
  1095. if await self.delete_message(sent_message):
  1096. self.to_be_destroyed.remove(sent_message)
  1097. return
  1098. async def wait_and_obscure(self, update, when, inline_message_id):
  1099. """Obscure an inline_message `timer` seconds after sending it, by editing its text or caption.
  1100. At the moment Telegram won't let bots delete sent inline query results."""
  1101. if type(when) is int:
  1102. when = datetime.datetime.now() + datetime.timedelta(seconds=when)
  1103. assert type(when) is datetime.datetime, "when must be a datetime instance or a number of seconds (int) to be awaited"
  1104. if 'inline_message_id' not in update:
  1105. logging.info("This inline query result owns no inline_keyboard, so it can't be modified")
  1106. return
  1107. inline_message_id = update['inline_message_id']
  1108. self.to_be_obscured.append(inline_message_id)
  1109. while datetime.datetime.now() < when:
  1110. await sleep_until(when)
  1111. try:
  1112. await self.editMessageCaption(inline_message_id, text="Time over")
  1113. except:
  1114. try:
  1115. await self.editMessageText(inline_message_id, text="Time over")
  1116. except Exception as e:
  1117. logging.error("Couldn't obscure message\n{}\n\n{}".format(inline_message_id,e))
  1118. self.to_be_obscured.remove(inline_message_id)
  1119. return
  1120. async def continue_running(self):
  1121. """If bot can be got, sets name and telegram_id, awaits preliminary tasks and starts getting updates from telegram.
  1122. If bot can't be got, restarts all bots in 5 minutes."""
  1123. try:
  1124. me = await self.getMe()
  1125. self.bot_name = me["username"]
  1126. self.telegram_id = me['id']
  1127. except:
  1128. logging.error("Could not get bot")
  1129. await asyncio.sleep(5*60)
  1130. self.restart_bots()
  1131. return
  1132. for task in self.run_before_loop:
  1133. await task
  1134. self.set_default_keyboard()
  1135. asyncio.ensure_future(
  1136. self.message_loop(handler=self.routing_table)
  1137. )
  1138. return
  1139. def stop_bots(self):
  1140. """Causes the script to exit"""
  1141. Bot.stop = True
  1142. def restart_bots(self):
  1143. """Causes the script to restart.
  1144. Actually, you need to catch Bot.stop state when Bot.run() returns and handle the situation yourself."""
  1145. Bot.stop = "Restart"
  1146. @classmethod
  1147. async def check_task(cls):
  1148. """Await until cls.stop, then end session and return"""
  1149. for bot in cls.instances.values():
  1150. asyncio.ensure_future(bot.continue_running())
  1151. while not cls.stop:
  1152. await asyncio.sleep(10)
  1153. return await cls.end_session()
  1154. @classmethod
  1155. async def end_session(cls):
  1156. """Run after stop, before the script exits.
  1157. Await final tasks, obscure and delete pending messages, log current operation (stop/restart)."""
  1158. for bot in cls.instances.values():
  1159. for task in bot.run_after_loop:
  1160. await task
  1161. for message in bot.to_be_destroyed:
  1162. try:
  1163. await bot.delete_message(message)
  1164. except Exception as e:
  1165. logging.error("Couldn't delete message\n{}\n\n{}".format(message,e))
  1166. for inline_message_id in bot.to_be_obscured:
  1167. try:
  1168. await bot.editMessageCaption(inline_message_id, text="Time over")
  1169. except:
  1170. try:
  1171. await bot.editMessageText(inline_message_id, text="Time over")
  1172. except Exception as e:
  1173. logging.error("Couldn't obscure message\n{}\n\n{}".format(inline_message_id,e))
  1174. if cls.stop=="Restart":
  1175. logging.info("\n\t\t---Restart!---")
  1176. elif cls.stop=="KeyboardInterrupt":
  1177. logging.info("Stopped by KeyboardInterrupt.")
  1178. else:
  1179. logging.info("Stopped gracefully by user.")
  1180. return
  1181. @classmethod
  1182. def run(cls, loop=None):
  1183. """
  1184. Call this method to run the async bots.
  1185. """
  1186. if not loop:
  1187. loop = asyncio.get_event_loop()
  1188. logging.info(
  1189. "{sep}{subjvb} STARTED{sep}".format(
  1190. sep='-'*10,
  1191. subjvb='BOT HAS' if len(cls.instances)==1 else 'BOTS HAVE'
  1192. )
  1193. )
  1194. try:
  1195. loop.run_until_complete(cls.check_task())
  1196. except KeyboardInterrupt:
  1197. logging.info('\n\t\tYour script received a KeyboardInterrupt signal, your bot{} being stopped.'.format(
  1198. 's are' if len(cls.instances)>1 else ' is'
  1199. ))
  1200. cls.stop = "KeyboardInterrupt"
  1201. loop.run_until_complete(cls.end_session())
  1202. except Exception as e:
  1203. logging.error('\nYour bot has been stopped. with error \'{}\''.format(e), exc_info=True)
  1204. logging.info(
  1205. "{sep}{subjvb} STOPPED{sep}".format(
  1206. sep='-'*10,
  1207. subjvb='BOT HAS' if len(cls.instances)==1 else 'BOTS HAVE'
  1208. )
  1209. )
  1210. return