Queer European MD passionate about IT

bot.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  1. """Provide a simple Bot object, mirroring Telegram API methods.
  2. camelCase methods mirror API directly, while snake_case ones act as middlewares
  3. someway.
  4. Usage
  5. ```
  6. import sys
  7. from davtelepot.bot import Bot
  8. from data.passwords import my_token, my_other_token
  9. long_polling_bot = Bot(token=my_token, database_url='my_db')
  10. webhook_bot = Bot(token=my_other_token, hostname='example.com',
  11. certificate='path/to/certificate.pem',
  12. database_url='my_other_db')
  13. @long_polling_bot.command('/foo')
  14. async def foo_command(bot, update, user_record):
  15. return "Bar!"
  16. @webhook_bot.command('/bar')
  17. async def bar_command(bot, update, user_record):
  18. return "Foo!"
  19. exit_state = Bot.run()
  20. sys.exit(exit_state)
  21. ```
  22. """
  23. # Standard library modules
  24. import asyncio
  25. from collections import OrderedDict
  26. import io
  27. import logging
  28. import os
  29. import re
  30. # Third party modules
  31. from aiohttp import web
  32. # Project modules
  33. from davtelepot.api import TelegramBot, TelegramError
  34. from davtelepot.database import ObjectWithDatabase
  35. from davtelepot.utilities import (
  36. escape_html_chars, extract, get_secure_key, make_inline_query_answer,
  37. make_lines_of_buttons, remove_html_tags
  38. )
  39. # Do not log aiohttp `INFO` and `DEBUG` levels
  40. logging.getLogger('aiohttp').setLevel(logging.WARNING)
  41. class Bot(TelegramBot, ObjectWithDatabase):
  42. """Simple Bot object, providing methods corresponding to Telegram bot API.
  43. Multiple Bot() instances may be run together, along with a aiohttp web app.
  44. """
  45. bots = []
  46. _path = '.'
  47. runner = None
  48. local_host = 'localhost'
  49. port = 3000
  50. final_state = 0
  51. _maintenance_message = ("I am currently under maintenance!\n"
  52. "Please retry later...")
  53. _authorization_denied_message = None
  54. _unknown_command_message = None
  55. TELEGRAM_MESSAGES_MAX_LEN = 4096
  56. _default_inline_query_answer = [
  57. dict(
  58. type='article',
  59. id=0,
  60. title="I cannot answer this query, sorry",
  61. input_message_content=dict(
  62. message_text="I'm sorry "
  63. "but I could not find an answer for your query."
  64. )
  65. )
  66. ]
  67. def __init__(
  68. self, token, hostname='', certificate=None, max_connections=40,
  69. allowed_updates=[], database_url='bot.db'
  70. ):
  71. """Init a bot instance.
  72. token : str
  73. Telegram bot API token.
  74. hostname : str
  75. Domain (or public IP address) for webhooks.
  76. certificate : str
  77. Path to domain certificate.
  78. max_connections : int (1 - 100)
  79. Maximum number of HTTPS connections allowed.
  80. allowed_updates : List(str)
  81. Allowed update types (empty list to allow all).
  82. """
  83. # Append `self` to class list of instances
  84. self.__class__.bots.append(self)
  85. # Call superclasses constructors with proper arguments
  86. TelegramBot.__init__(self, token)
  87. ObjectWithDatabase.__init__(self, database_url=database_url)
  88. self._path = None
  89. self.preliminary_tasks = []
  90. self.final_tasks = []
  91. self._offset = 0
  92. self._hostname = hostname
  93. self._certificate = certificate
  94. self._max_connections = max_connections
  95. self._allowed_updates = allowed_updates
  96. self._session_token = get_secure_key(length=10)
  97. self._name = None
  98. self._telegram_id = None
  99. # The following routing table associates each type of Telegram `update`
  100. # with a Bot method to be invoked on it.
  101. self.routing_table = {
  102. 'message': self.message_router,
  103. 'edited_message': self.edited_message_handler,
  104. 'channel_post': self.channel_post_handler,
  105. 'edited_channel_post': self.edited_channel_post_handler,
  106. 'inline_query': self.inline_query_handler,
  107. 'chosen_inline_result': self.chosen_inline_result_handler,
  108. 'callback_query': self.callback_query_handler,
  109. 'shipping_query': self.shipping_query_handler,
  110. 'pre_checkout_query': self.pre_checkout_query_handler,
  111. 'poll': self.poll_handler,
  112. }
  113. # Different message update types need different handlers
  114. self.message_handlers = {
  115. 'text': self.text_message_handler,
  116. 'audio': self.audio_message_handler,
  117. 'document': self.document_message_handler,
  118. 'animation': self.animation_message_handler,
  119. 'game': self.game_message_handler,
  120. 'photo': self.photo_message_handler,
  121. 'sticker': self.sticker_message_handler,
  122. 'video': self.video_message_handler,
  123. 'voice': self.voice_message_handler,
  124. 'video_note': self.video_note_message_handler,
  125. 'contact': self.contact_message_handler,
  126. 'location': self.location_message_handler,
  127. 'venue': self.venue_message_handler,
  128. 'poll': self.poll_message_handler,
  129. 'new_chat_members': self.new_chat_members_message_handler,
  130. 'left_chat_member': self.left_chat_member_message_handler,
  131. 'new_chat_title': self.new_chat_title_message_handler,
  132. 'new_chat_photo': self.new_chat_photo_message_handler,
  133. 'delete_chat_photo': self.delete_chat_photo_message_handler,
  134. 'group_chat_created': self.group_chat_created_message_handler,
  135. 'supergroup_chat_created': (
  136. self.supergroup_chat_created_message_handler
  137. ),
  138. 'channel_chat_created': self.channel_chat_created_message_handler,
  139. 'migrate_to_chat_id': self.migrate_to_chat_id_message_handler,
  140. 'migrate_from_chat_id': self.migrate_from_chat_id_message_handler,
  141. 'pinned_message': self.pinned_message_message_handler,
  142. 'invoice': self.invoice_message_handler,
  143. 'successful_payment': self.successful_payment_message_handler,
  144. 'connected_website': self.connected_website_message_handler,
  145. 'passport_data': self.passport_data_message_handler
  146. }
  147. # Special text message handlers: individual, commands, aliases, parsers
  148. self.individual_text_message_handlers = dict()
  149. self.commands = OrderedDict()
  150. self.command_aliases = OrderedDict()
  151. self._unknown_command_message = None
  152. self.text_message_parsers = OrderedDict()
  153. # Callback query-related properties
  154. self.callback_handlers = OrderedDict()
  155. self._callback_data_separator = None
  156. # Inline query-related properties
  157. self.inline_query_handlers = OrderedDict()
  158. self._default_inline_query_answer = None
  159. self.chosen_inline_result_handlers = dict()
  160. # Maintenance properties
  161. self._under_maintenance = False
  162. self._allowed_during_maintenance = []
  163. self._maintenance_message = None
  164. # Default chat_id getter: same chat as update
  165. self.get_chat_id = lambda update: (
  166. update['message']['chat']['id']
  167. if 'message' in update and 'chat' in update['message']
  168. else update['chat']['id']
  169. if 'chat' in update
  170. else None
  171. )
  172. # Message to be returned if user is not allowed to call method
  173. self._authorization_denied_message = None
  174. # Default authorization function (always return True)
  175. self.authorization_function = (
  176. lambda update, user_record=None, authorization_level='user': True
  177. )
  178. self.default_reply_keyboard_elements = []
  179. self._default_keyboard = dict()
  180. return
  181. @property
  182. def path(self):
  183. """Path where files should be looked for.
  184. If no instance path is set, return class path.
  185. """
  186. return self._path or self.__class__._path
  187. @classmethod
  188. def set_class_path(csl, path):
  189. """Set class path attribute."""
  190. csl._path = path
  191. def set_path(self, path):
  192. """Set instance path attribute."""
  193. self._path = path
  194. @property
  195. def hostname(self):
  196. """Hostname for the webhook URL.
  197. It must be a public domain or IP address. Port may be specified.
  198. A custom webhook url, including bot token and a random token, will be
  199. generated for Telegram to post new updates.
  200. """
  201. return self._hostname
  202. @property
  203. def webhook_url(self):
  204. """URL where Telegram servers should post new updates.
  205. It must be a public domain name or IP address. Port may be specified.
  206. """
  207. if not self.hostname:
  208. return ''
  209. return (
  210. f"{self.hostname}/webhook/{self.token}_{self.session_token}/"
  211. )
  212. @property
  213. def webhook_local_address(self):
  214. """Local address where Telegram updates are routed by revers proxy."""
  215. return (
  216. f"/webhook/{self.token}_{self.session_token}/"
  217. )
  218. @property
  219. def certificate(self):
  220. """Public certificate for `webhook_url`.
  221. May be self-signed
  222. """
  223. return self._certificate
  224. @property
  225. def max_connections(self):
  226. """Maximum number of simultaneous HTTPS connections allowed.
  227. Telegram will open as many connections as possible to boost bot’s
  228. throughput, lower values limit the load on bot‘s server.
  229. """
  230. return self._max_connections
  231. @property
  232. def allowed_updates(self):
  233. """List of update types to be retrieved.
  234. Empty list to allow all updates.
  235. """
  236. return self._allowed_updates
  237. @property
  238. def name(self):
  239. """Bot name."""
  240. return self._name
  241. @property
  242. def telegram_id(self):
  243. """Telegram id of this bot."""
  244. return self._telegram_id
  245. @property
  246. def session_token(self):
  247. """Return a token generated with the current instantiation."""
  248. return self._session_token
  249. @property
  250. def offset(self):
  251. """Return last update id.
  252. Useful to ignore repeated updates and restore original update order.
  253. """
  254. return self._offset
  255. @property
  256. def under_maintenance(self):
  257. """Return True if bot is under maintenance.
  258. While under maintenance, bot will reply `self.maintenance_message` to
  259. any update, except those which `self.is_allowed_during_maintenance`
  260. returns True for.
  261. """
  262. return self._under_maintenance
  263. @property
  264. def allowed_during_maintenance(self):
  265. """Return the list of criteria to allow an update during maintenance.
  266. If any of this criteria returns True on an update, that update will be
  267. handled even during maintenance.
  268. """
  269. return self._allowed_during_maintenance
  270. @property
  271. def maintenance_message(self):
  272. """Message to be returned if bot is under maintenance.
  273. If instance message is not set, class message is returned.
  274. """
  275. if self._maintenance_message:
  276. return self._maintenance_message
  277. if self.__class__.maintenance_message:
  278. return self.__class__._maintenance_message
  279. return ("I am currently under maintenance!\n"
  280. "Please retry later...")
  281. @property
  282. def authorization_denied_message(self):
  283. """Return this text if user is unauthorized to make a request.
  284. If instance message is not set, class message is returned.
  285. """
  286. if self._authorization_denied_message:
  287. return self._authorization_denied_message
  288. return self.__class__._authorization_denied_message
  289. @property
  290. def default_keyboard(self):
  291. """Get the default keyboard.
  292. It is sent when reply_markup is left blank and chat is private.
  293. """
  294. return self._default_keyboard
  295. @property
  296. def unknown_command_message(self):
  297. """Message to be returned if user sends an unknown command.
  298. If instance message is not set, class message is returned.
  299. """
  300. if self._unknown_command_message:
  301. return self._unknown_command_message
  302. return self.__class__._unknown_command_message
  303. @property
  304. def callback_data_separator(self):
  305. """Separator between callback data elements.
  306. Example of callback_data: 'my_button_prefix:///1|4|test'
  307. Prefix: `my_button_prefix:///`
  308. Separator: `|` <--- this is returned
  309. Data: `['1', '4', 'test']`
  310. """
  311. return self._callback_data_separator
  312. def set_callback_data_separator(self, separator):
  313. """Set a callback_data separator.
  314. See property `callback_data_separator` for details.
  315. """
  316. assert type(separator) is str, "Separator must be a string!"
  317. self._callback_data_separator = separator
  318. @property
  319. def default_inline_query_answer(self):
  320. """Answer to be returned if inline query returned None.
  321. If instance default answer is not set, class one is returned.
  322. """
  323. if self._default_inline_query_answer:
  324. return self._default_inline_query_answer
  325. return self.__class__._default_inline_query_answer
  326. @classmethod
  327. def set_class_default_inline_query_answer(cls,
  328. default_inline_query_answer):
  329. """Set class default inline query answer.
  330. It will be returned if an inline query returned no answer.
  331. """
  332. cls._default_inline_query_answer = make_inline_query_answer(
  333. default_inline_query_answer
  334. )
  335. def set_default_inline_query_answer(self, default_inline_query_answer):
  336. """Set a custom default_inline_query_answer.
  337. It will be returned when no answer is found for an inline query.
  338. If instance answer is None, default class answer is used.
  339. """
  340. self._default_inline_query_answer = make_inline_query_answer(
  341. default_inline_query_answer
  342. )
  343. async def message_router(self, update, user_record):
  344. """Route Telegram `message` update to appropriate message handler."""
  345. for key, value in update.items():
  346. if key in self.message_handlers:
  347. return await self.message_handlers[key](update, user_record)
  348. logging.error(
  349. f"The following message update was received: {update}\n"
  350. "However, this message type is unknown."
  351. )
  352. async def edited_message_handler(self, update, user_record):
  353. """Handle Telegram `edited_message` update."""
  354. logging.info(
  355. f"The following update was received: {update}\n"
  356. "However, this edited_message handler does nothing yet."
  357. )
  358. return
  359. async def channel_post_handler(self, update, user_record):
  360. """Handle Telegram `channel_post` update."""
  361. logging.info(
  362. f"The following update was received: {update}\n"
  363. "However, this channel_post handler does nothing yet."
  364. )
  365. return
  366. async def edited_channel_post_handler(self, update, user_record):
  367. """Handle Telegram `edited_channel_post` update."""
  368. logging.info(
  369. f"The following update was received: {update}\n"
  370. "However, this edited_channel_post handler does nothing yet."
  371. )
  372. return
  373. async def inline_query_handler(self, update, user_record):
  374. """Handle Telegram `inline_query` update.
  375. Answer it with results or log errors.
  376. """
  377. query = update['query']
  378. results, switch_pm_text, switch_pm_parameter = None, None, None
  379. for condition, handler in self.inline_query_handlers.items():
  380. if condition(query):
  381. _handler = handler['handler']
  382. results = await _handler(bot=self, update=update,
  383. user_record=user_record)
  384. break
  385. if not results:
  386. results = self.default_inline_query_answer
  387. if type(results) is dict:
  388. if 'switch_pm_text' in results:
  389. switch_pm_text = results['switch_pm_text']
  390. if 'switch_pm_parameter' in results:
  391. switch_pm_parameter = results['switch_pm_parameter']
  392. results = results['answer']
  393. try:
  394. await self.answerInlineQuery(
  395. update['id'],
  396. results=results,
  397. cache_time=10,
  398. is_personal=True,
  399. switch_pm_text=switch_pm_text,
  400. switch_pm_parameter=switch_pm_parameter
  401. )
  402. except Exception as e:
  403. logging.info("Error answering inline query\n{}".format(e))
  404. return
  405. async def chosen_inline_result_handler(self, update, user_record):
  406. """Handle Telegram `chosen_inline_result` update."""
  407. user_id = update['from']['id']
  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.
  420. When an inline result is chosen having that id, function will
  421. be passed the update as argument.
  422. """
  423. if type(user_id) is dict:
  424. user_id = user_id['from']['id']
  425. assert type(user_id) is int, "user_id must be int!"
  426. # Query result ids are parsed as str by telegram
  427. result_id = str(result_id)
  428. assert callable(func), "func must be a callable"
  429. if user_id not in self.chosen_inline_result_handlers:
  430. self.chosen_inline_result_handlers[user_id] = {}
  431. self.chosen_inline_result_handlers[user_id][result_id] = func
  432. return
  433. async def callback_query_handler(self, update, user_record):
  434. """Handle Telegram `callback_query` update.
  435. A callback query is sent when users press inline keyboard buttons.
  436. Bad clients may send malformed or deceiving callback queries:
  437. never put secrets in buttons and always check request validity!
  438. Get an `answer` from the callback handler associated to the query
  439. prefix and use it to edit the source message (or send new ones
  440. if text is longer than single message limit).
  441. Anyway, the query is answered, otherwise the client would hang and
  442. the bot would look like idle.
  443. """
  444. assert 'data' in update, "Malformed callback query lacking data field."
  445. answer = dict()
  446. data = update['data']
  447. for start_text, handler in self.callback_handlers.items():
  448. if data.startswith(start_text):
  449. _function = handler['handler']
  450. answer = await _function(
  451. bot=self,
  452. update=update,
  453. user_record=user_record
  454. )
  455. break
  456. if type(answer) is str:
  457. answer = dict(text=answer)
  458. assert type(answer) is dict, "Invalid callback query answer."
  459. if 'edit' in answer:
  460. message_identifier = self.get_message_identifier(update)
  461. edit = answer['edit']
  462. method = (
  463. self.edit_message_text if 'text' in edit
  464. else self.editMessageCaption if 'caption' in edit
  465. else self.editMessageReplyMarkup if 'reply_markup' in edit
  466. else (lambda *args, **kwargs: None)
  467. )
  468. try:
  469. await method(**message_identifier, **edit)
  470. except TelegramError as e:
  471. logging.info("Message was not modified:\n{}".format(e))
  472. try:
  473. return await self.answerCallbackQuery(
  474. callback_query_id=update['id'],
  475. **{
  476. key: (val[:180] if key == 'text' else val)
  477. for key, val in answer.items()
  478. if key in ('text', 'show_alert', 'cache_time')
  479. }
  480. )
  481. except TelegramError as e:
  482. logging.error(e)
  483. return
  484. async def shipping_query_handler(self, update, user_record):
  485. """Handle Telegram `shipping_query` update."""
  486. logging.info(
  487. f"The following update was received: {update}\n"
  488. "However, this shipping_query handler does nothing yet."
  489. )
  490. return
  491. async def pre_checkout_query_handler(self, update, user_record):
  492. """Handle Telegram `pre_checkout_query` update."""
  493. logging.info(
  494. f"The following update was received: {update}\n"
  495. "However, this pre_checkout_query handler does nothing yet."
  496. )
  497. return
  498. async def poll_handler(self, update, user_record):
  499. """Handle Telegram `poll` update."""
  500. logging.info(
  501. f"The following update was received: {update}\n"
  502. "However, this poll handler does nothing yet."
  503. )
  504. return
  505. async def text_message_handler(self, update, user_record):
  506. """Handle `text` message update."""
  507. replier, reply = None, None
  508. text = update['text'].lower()
  509. user_id = update['from']['id'] if 'from' in update else None
  510. if user_id in self.individual_text_message_handlers:
  511. replier = self.individual_text_message_handlers[user_id]
  512. del self.individual_text_message_handlers[user_id]
  513. elif text.startswith('/'): # Handle commands
  514. # A command must always start with the ‘/’ symbol and may not be
  515. # longer than 32 characters.
  516. # Commands can use latin letters, numbers and underscores.
  517. command = re.search(
  518. r"([A-z_1-9]){1,32}", # Command pattern (without leading `/`)
  519. text
  520. ).group(0) # Get the first group of characters matching pattern
  521. if command in self.commands:
  522. replier = self.commands[command]['handler']
  523. elif 'chat' in update and update['chat']['id'] > 0:
  524. reply = self.unknown_command_message
  525. else: # Handle command aliases and text parsers
  526. # Aliases are case insensitive: text and alias are both .lower()
  527. for alias, function in self.command_aliases.items():
  528. if text.startswith(alias.lower()):
  529. replier = function
  530. break
  531. # Text message update parsers
  532. for check_function, parser in self.text_message_parsers.items():
  533. if (
  534. parser['argument'] == 'text'
  535. and check_function(text)
  536. ) or (
  537. parser['argument'] == 'update'
  538. and check_function(update)
  539. ):
  540. replier = parser['function']
  541. break
  542. if replier:
  543. reply = await replier(
  544. bot=self,
  545. update=update,
  546. user_record=user_record
  547. )
  548. if reply:
  549. if type(reply) is str:
  550. reply = dict(text=reply)
  551. try:
  552. if 'text' in reply:
  553. return await self.send_message(update=update, **reply)
  554. if 'photo' in reply:
  555. return await self.send_photo(update=update, **reply)
  556. except Exception as e:
  557. logging.error(
  558. f"Failed to handle text message:\n{e}",
  559. exc_info=True
  560. )
  561. return
  562. async def audio_message_handler(self, update, user_record):
  563. """Handle `audio` message update."""
  564. logging.info(
  565. "A audio message update was received, "
  566. "but this handler does nothing yet."
  567. )
  568. async def document_message_handler(self, update, user_record):
  569. """Handle `document` message update."""
  570. logging.info(
  571. "A document message update was received, "
  572. "but this handler does nothing yet."
  573. )
  574. async def animation_message_handler(self, update, user_record):
  575. """Handle `animation` message update."""
  576. logging.info(
  577. "A animation message update was received, "
  578. "but this handler does nothing yet."
  579. )
  580. async def game_message_handler(self, update, user_record):
  581. """Handle `game` message update."""
  582. logging.info(
  583. "A game message update was received, "
  584. "but this handler does nothing yet."
  585. )
  586. async def photo_message_handler(self, update, user_record):
  587. """Handle `photo` message update."""
  588. logging.info(
  589. "A photo message update was received, "
  590. "but this handler does nothing yet."
  591. )
  592. async def sticker_message_handler(self, update, user_record):
  593. """Handle `sticker` message update."""
  594. logging.info(
  595. "A sticker message update was received, "
  596. "but this handler does nothing yet."
  597. )
  598. async def video_message_handler(self, update, user_record):
  599. """Handle `video` message update."""
  600. logging.info(
  601. "A video message update was received, "
  602. "but this handler does nothing yet."
  603. )
  604. async def voice_message_handler(self, update, user_record):
  605. """Handle `voice` message update."""
  606. logging.info(
  607. "A voice message update was received, "
  608. "but this handler does nothing yet."
  609. )
  610. async def video_note_message_handler(self, update, user_record):
  611. """Handle `video_note` message update."""
  612. logging.info(
  613. "A video_note message update was received, "
  614. "but this handler does nothing yet."
  615. )
  616. async def contact_message_handler(self, update, user_record):
  617. """Handle `contact` message update."""
  618. logging.info(
  619. "A contact message update was received, "
  620. "but this handler does nothing yet."
  621. )
  622. async def location_message_handler(self, update, user_record):
  623. """Handle `location` message update."""
  624. logging.info(
  625. "A location message update was received, "
  626. "but this handler does nothing yet."
  627. )
  628. async def venue_message_handler(self, update, user_record):
  629. """Handle `venue` message update."""
  630. logging.info(
  631. "A venue message update was received, "
  632. "but this handler does nothing yet."
  633. )
  634. async def poll_message_handler(self, update, user_record):
  635. """Handle `poll` message update."""
  636. logging.info(
  637. "A poll message update was received, "
  638. "but this handler does nothing yet."
  639. )
  640. async def new_chat_members_message_handler(self, update, user_record):
  641. """Handle `new_chat_members` message update."""
  642. logging.info(
  643. "A new_chat_members message update was received, "
  644. "but this handler does nothing yet."
  645. )
  646. async def left_chat_member_message_handler(self, update, user_record):
  647. """Handle `left_chat_member` message update."""
  648. logging.info(
  649. "A left_chat_member message update was received, "
  650. "but this handler does nothing yet."
  651. )
  652. async def new_chat_title_message_handler(self, update, user_record):
  653. """Handle `new_chat_title` message update."""
  654. logging.info(
  655. "A new_chat_title message update was received, "
  656. "but this handler does nothing yet."
  657. )
  658. async def new_chat_photo_message_handler(self, update, user_record):
  659. """Handle `new_chat_photo` message update."""
  660. logging.info(
  661. "A new_chat_photo message update was received, "
  662. "but this handler does nothing yet."
  663. )
  664. async def delete_chat_photo_message_handler(self, update, user_record):
  665. """Handle `delete_chat_photo` message update."""
  666. logging.info(
  667. "A delete_chat_photo message update was received, "
  668. "but this handler does nothing yet."
  669. )
  670. async def group_chat_created_message_handler(self, update, user_record):
  671. """Handle `group_chat_created` message update."""
  672. logging.info(
  673. "A group_chat_created message update was received, "
  674. "but this handler does nothing yet."
  675. )
  676. async def supergroup_chat_created_message_handler(self, update,
  677. user_record):
  678. """Handle `supergroup_chat_created` message update."""
  679. logging.info(
  680. "A supergroup_chat_created message update was received, "
  681. "but this handler does nothing yet."
  682. )
  683. async def channel_chat_created_message_handler(self, update, user_record):
  684. """Handle `channel_chat_created` message update."""
  685. logging.info(
  686. "A channel_chat_created message update was received, "
  687. "but this handler does nothing yet."
  688. )
  689. async def migrate_to_chat_id_message_handler(self, update, user_record):
  690. """Handle `migrate_to_chat_id` message update."""
  691. logging.info(
  692. "A migrate_to_chat_id message update was received, "
  693. "but this handler does nothing yet."
  694. )
  695. async def migrate_from_chat_id_message_handler(self, update, user_record):
  696. """Handle `migrate_from_chat_id` message update."""
  697. logging.info(
  698. "A migrate_from_chat_id message update was received, "
  699. "but this handler does nothing yet."
  700. )
  701. async def pinned_message_message_handler(self, update, user_record):
  702. """Handle `pinned_message` message update."""
  703. logging.info(
  704. "A pinned_message message update was received, "
  705. "but this handler does nothing yet."
  706. )
  707. async def invoice_message_handler(self, update, user_record):
  708. """Handle `invoice` message update."""
  709. logging.info(
  710. "A invoice message update was received, "
  711. "but this handler does nothing yet."
  712. )
  713. async def successful_payment_message_handler(self, update, user_record):
  714. """Handle `successful_payment` message update."""
  715. logging.info(
  716. "A successful_payment message update was received, "
  717. "but this handler does nothing yet."
  718. )
  719. async def connected_website_message_handler(self, update, user_record):
  720. """Handle `connected_website` message update."""
  721. logging.info(
  722. "A connected_website message update was received, "
  723. "but this handler does nothing yet."
  724. )
  725. async def passport_data_message_handler(self, update, user_record):
  726. """Handle `passport_data` message update."""
  727. logging.info(
  728. "A passport_data message update was received, "
  729. "but this handler does nothing yet."
  730. )
  731. @staticmethod
  732. def split_message_text(text, limit=None, parse_mode='HTML'):
  733. r"""Split text if it hits telegram limits for text messages.
  734. Split at `\n` if possible.
  735. Add a `[...]` at the end and beginning of split messages,
  736. with proper code markdown.
  737. """
  738. if parse_mode == 'HTML':
  739. text = escape_html_chars(text)
  740. tags = (
  741. ('`', '`')
  742. if parse_mode == 'Markdown'
  743. else ('<code>', '</code>')
  744. if parse_mode.lower() == 'html'
  745. else ('', '')
  746. )
  747. if limit is None:
  748. limit = Bot.TELEGRAM_MESSAGES_MAX_LEN - 100
  749. # Example text: "lines\nin\nreversed\order"
  750. text = text.split("\n")[::-1] # ['order', 'reversed', 'in', 'lines']
  751. text_part_number = 0
  752. while len(text) > 0:
  753. temp = []
  754. text_part_number += 1
  755. while (
  756. len(text) > 0
  757. and len(
  758. "\n".join(temp + [text[-1]])
  759. ) < limit
  760. ):
  761. # Append lines of `text` in order (`.pop` returns the last
  762. # line in text) until the addition of the next line would hit
  763. # the `limit`.
  764. temp.append(text.pop())
  765. # If graceful split failed (last line was longer than limit)
  766. if len(temp) == 0:
  767. # Force split last line
  768. temp.append(text[-1][:limit])
  769. text[-1] = text[-1][limit:]
  770. text_chunk = "\n".join(temp) # Re-join this group of lines
  771. prefix, suffix = '', ''
  772. is_last = len(text) == 0
  773. if text_part_number > 1:
  774. prefix = f"{tags[0]}[...]{tags[1]}\n"
  775. if not is_last:
  776. suffix = f"\n{tags[0]}[...]{tags[1]}"
  777. yield (prefix + text_chunk + suffix), is_last
  778. return
  779. async def send_message(self, chat_id=None, text=None,
  780. parse_mode='HTML',
  781. disable_web_page_preview=None,
  782. disable_notification=None,
  783. reply_to_message_id=None,
  784. reply_markup=None,
  785. update=dict(),
  786. reply_to_update=False,
  787. send_default_keyboard=True):
  788. """Send text via message(s).
  789. This method wraps lower-level `TelegramBot.sendMessage` method.
  790. Pass an `update` to extract `chat_id` and `message_id` from it.
  791. Set `reply_to_update` = True to reply to `update['message_id']`.
  792. Set `send_default_keyboard` = False to avoid sending default keyboard
  793. as reply_markup (only those messages can be edited, which were
  794. sent with no reply markup or with an inline keyboard).
  795. """
  796. if 'message' in update:
  797. update = update['message']
  798. if chat_id is None and 'chat' in update:
  799. chat_id = self.get_chat_id(update)
  800. if reply_to_update and 'message_id' in update:
  801. reply_to_message_id = update['message_id']
  802. if (
  803. send_default_keyboard
  804. and reply_markup is None
  805. and type(chat_id) is int
  806. and chat_id > 0
  807. and text != self.authorization_denied_message
  808. ):
  809. reply_markup = self.default_keyboard
  810. if not text:
  811. return
  812. parse_mode = str(parse_mode)
  813. text_chunks = self.split_message_text(
  814. text=text,
  815. limit=self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 100,
  816. parse_mode=parse_mode
  817. )
  818. for text_chunk, is_last in text_chunks:
  819. _reply_markup = (reply_markup if is_last else None)
  820. sent_message_update = await self.sendMessage(
  821. chat_id=chat_id,
  822. text=text_chunk,
  823. parse_mode=parse_mode,
  824. disable_web_page_preview=disable_web_page_preview,
  825. disable_notification=disable_notification,
  826. reply_to_message_id=reply_to_message_id,
  827. reply_markup=_reply_markup
  828. )
  829. return sent_message_update
  830. async def edit_message_text(self, text,
  831. chat_id=None, message_id=None,
  832. inline_message_id=None,
  833. parse_mode='HTML',
  834. disable_web_page_preview=None,
  835. reply_markup=None,
  836. update=None):
  837. """Edit message text, sending new messages if necessary.
  838. This method wraps lower-level `TelegramBot.editMessageText` method.
  839. Pass an `update` to extract a message identifier from it.
  840. """
  841. if update is not None:
  842. message_identifier = self.get_message_identifier(update)
  843. if 'chat_id' in message_identifier:
  844. chat_id = message_identifier['chat_id']
  845. message_id = message_identifier['message_id']
  846. if 'inline_message_id' in message_identifier:
  847. inline_message_id = message_identifier['inline_message_id']
  848. for i, text_chunk in enumerate(
  849. self.split_message_text(
  850. text=text,
  851. limit=self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 200,
  852. parse_mode=parse_mode
  853. )
  854. ):
  855. if i == 0:
  856. edited_message = await self.editMessageText(
  857. text=text_chunk,
  858. chat_id=chat_id,
  859. message_id=message_id,
  860. inline_message_id=inline_message_id,
  861. parse_mode=parse_mode,
  862. disable_web_page_preview=disable_web_page_preview,
  863. reply_markup=reply_markup
  864. )
  865. if chat_id is None:
  866. # Cannot send messages without a chat_id
  867. # Inline keyboards attached to inline query results may be
  868. # in chats the bot cannot reach.
  869. break
  870. else:
  871. await self.send_message(
  872. text=text,
  873. chat_id=chat_id,
  874. parse_mode=parse_mode,
  875. disable_web_page_preview=disable_web_page_preview,
  876. reply_markup=reply_markup,
  877. update=update,
  878. reply_to_update=True,
  879. send_default_keyboard=False
  880. )
  881. return edited_message
  882. async def send_photo(self, chat_id=None, photo=None,
  883. caption=None,
  884. parse_mode=None,
  885. disable_notification=None,
  886. reply_to_message_id=None,
  887. reply_markup=None,
  888. update=dict(),
  889. reply_to_update=False,
  890. send_default_keyboard=True,
  891. use_stored_file_id=True):
  892. """Send photos.
  893. This method wraps lower-level `TelegramBot.sendPhoto` method.
  894. Pass an `update` to extract `chat_id` and `message_id` from it.
  895. Set `reply_to_update` = True to reply to `update['message_id']`.
  896. Set `send_default_keyboard` = False to avoid sending default keyboard
  897. as reply_markup (only those messages can be edited, which were
  898. sent with no reply markup or with an inline keyboard).
  899. If photo was already sent by this bot and `use_stored_file_id` is set
  900. to True, use file_id (it is faster and recommended).
  901. """
  902. already_sent = False
  903. if 'message' in update:
  904. update = update['message']
  905. if chat_id is None and 'chat' in update:
  906. chat_id = self.get_chat_id(update)
  907. if reply_to_update and 'message_id' in update:
  908. reply_to_message_id = update['message_id']
  909. if (
  910. send_default_keyboard
  911. and reply_markup is None
  912. and type(chat_id) is int
  913. and chat_id > 0
  914. and caption != self.authorization_denied_message
  915. ):
  916. reply_markup = self.default_keyboard
  917. if type(photo) is str:
  918. photo_path = photo
  919. with self.db as db:
  920. already_sent = db['sent_pictures'].find_one(
  921. path=photo_path,
  922. errors=False
  923. )
  924. if already_sent and use_stored_file_id:
  925. photo = already_sent['file_id']
  926. already_sent = True
  927. else:
  928. already_sent = False
  929. if not any(
  930. [
  931. photo.startswith(url_starter)
  932. for url_starter in ('http', 'www',)
  933. ]
  934. ): # If `photo` is not a url but a local file path
  935. try:
  936. with io.BytesIO() as buffered_picture:
  937. with open(
  938. os.path.join(self.path, photo_path),
  939. 'rb' # Read bytes
  940. ) as photo_file:
  941. buffered_picture.write(photo_file.read())
  942. photo = buffered_picture.getvalue()
  943. except FileNotFoundError:
  944. photo = None
  945. else:
  946. use_stored_file_id = False
  947. if photo is None:
  948. logging.error("Photo is None, `send_photo` returning...")
  949. return
  950. sent_update = None
  951. try:
  952. sent_update = await self.sendPhoto(
  953. chat_id=chat_id,
  954. photo=photo,
  955. caption=caption,
  956. parse_mode=parse_mode,
  957. disable_notification=disable_notification,
  958. reply_to_message_id=reply_to_message_id,
  959. reply_markup=reply_markup
  960. )
  961. if isinstance(sent_update, Exception):
  962. raise Exception("sendPhoto API call failed!")
  963. except Exception as e:
  964. logging.error(f"Error sending photo\n{e}")
  965. if already_sent:
  966. with self.db as db:
  967. db['sent_pictures'].update(
  968. dict(
  969. path=photo_path,
  970. errors=True
  971. ),
  972. ['path']
  973. )
  974. if (
  975. type(sent_update) is dict
  976. and 'photo' in sent_update
  977. and len(sent_update['photo']) > 0
  978. and 'file_id' in sent_update['photo'][0]
  979. and (not already_sent)
  980. and use_stored_file_id
  981. ):
  982. with self.db as db:
  983. db['sent_pictures'].insert(
  984. dict(
  985. path=photo_path,
  986. file_id=sent_update['photo'][0]['file_id'],
  987. errors=False
  988. )
  989. )
  990. return sent_update
  991. async def answer_inline_query(self,
  992. inline_query_id=None,
  993. results=[],
  994. cache_time=None,
  995. is_personal=None,
  996. next_offset=None,
  997. switch_pm_text=None,
  998. switch_pm_parameter=None,
  999. update=None):
  1000. """Answer inline queries.
  1001. This method wraps lower-level `answerInlineQuery` method.
  1002. If `results` is a string, cast it to proper type (list of dicts having
  1003. certain keys). See utilities.make_inline_query_answer for details.
  1004. """
  1005. if inline_query_id is None and isinstance(update, dict):
  1006. inline_query_id = self.get_message_identifier(update)
  1007. results = make_inline_query_answer(results)
  1008. return await self.answerInlineQuery(
  1009. inline_query_id=inline_query_id,
  1010. results=results,
  1011. cache_time=cache_time,
  1012. is_personal=is_personal,
  1013. next_offset=next_offset,
  1014. switch_pm_text=switch_pm_text,
  1015. switch_pm_parameter=switch_pm_parameter,
  1016. )
  1017. @classmethod
  1018. def set_class_maintenance_message(cls, maintenance_message):
  1019. """Set class maintenance message.
  1020. It will be returned if bot is under maintenance, unless and instance
  1021. `_maintenance_message` is set.
  1022. """
  1023. cls._maintenance_message = maintenance_message
  1024. def set_maintenance_message(self, maintenance_message):
  1025. """Set instance maintenance message.
  1026. It will be returned if bot is under maintenance.
  1027. If instance message is None, default class message is used.
  1028. """
  1029. self._maintenance_message = maintenance_message
  1030. def change_maintenance_status(self, maintenance_message=None, status=None):
  1031. """Put the bot under maintenance or end it.
  1032. While in maintenance, bot will reply to users with maintenance_message
  1033. with a few exceptions.
  1034. If status is not set, it is by default the opposite of the current one.
  1035. Optionally, `maintenance_message` may be set.
  1036. """
  1037. if status is None:
  1038. status = not self.under_maintenance
  1039. assert type(status) is bool, "status must be a boolean value!"
  1040. self._under_maintenance = status
  1041. if maintenance_message:
  1042. self.set_maintenance_message(maintenance_message)
  1043. return self._under_maintenance # Return new status
  1044. def is_allowed_during_maintenance(self, update):
  1045. """Return True if update is allowed during maintenance.
  1046. An update is allowed if any of the criteria in
  1047. `self.allowed_during_maintenance` returns True called on it.
  1048. """
  1049. for criterion in self.allowed_during_maintenance:
  1050. if criterion(update):
  1051. return True
  1052. return False
  1053. def allow_during_maintenance(self, criterion):
  1054. """Add a criterion to allow certain updates during maintenance.
  1055. `criterion` must be a function taking a Telegram `update` dictionary
  1056. and returning a boolean.
  1057. ```# Example of criterion
  1058. def allow_text_messages(update):
  1059. if 'message' in update and 'text' in update['message']:
  1060. return True
  1061. return False
  1062. ```
  1063. """
  1064. self._allowed_during_maintenance.append(criterion)
  1065. async def handle_update_during_maintenance(self, update):
  1066. """Handle an update while bot is under maintenance.
  1067. Handle all types of updates.
  1068. """
  1069. if (
  1070. 'message' in update
  1071. and 'chat' in update['message']
  1072. and update['message']['chat']['id'] > 0
  1073. ):
  1074. return await self.send_message(
  1075. text=self.maintenance_message,
  1076. update=update['message'],
  1077. reply_to_update=True
  1078. )
  1079. elif 'callback_query' in update:
  1080. await self.answerCallbackQuery(
  1081. callback_query_id=update['id'],
  1082. text=remove_html_tags(self.maintenance_message[:45])
  1083. )
  1084. elif 'inline_query' in update:
  1085. await self.answer_inline_query(
  1086. update['inline_query']['id'],
  1087. self.maintenance_message,
  1088. cache_time=30,
  1089. is_personal=False,
  1090. )
  1091. return
  1092. @classmethod
  1093. def set_class_authorization_denied_message(csl, message):
  1094. """Set class authorization denied message.
  1095. It will be returned if user is unauthorized to make a request.
  1096. """
  1097. csl._authorization_denied_message = message
  1098. def set_authorization_denied_message(self, message):
  1099. """Set instance authorization denied message.
  1100. If instance message is None, default class message is used.
  1101. """
  1102. self._authorization_denied_message = message
  1103. def set_authorization_function(self, authorization_function):
  1104. """Set a custom authorization_function.
  1105. It should evaluate True if user is authorized to perform a specific
  1106. action and False otherwise.
  1107. It should take update and role and return a Boolean.
  1108. Default authorization_function always evaluates True.
  1109. """
  1110. self.authorization_function = authorization_function
  1111. @classmethod
  1112. def set_class_unknown_command_message(cls, unknown_command_message):
  1113. """Set class unknown command message.
  1114. It will be returned if user sends an unknown command in private chat.
  1115. """
  1116. cls._unknown_command_message = unknown_command_message
  1117. def set_unknown_command_message(self, unknown_command_message):
  1118. """Set instance unknown command message.
  1119. It will be returned if user sends an unknown command in private chat.
  1120. If instance message is None, default class message is used.
  1121. """
  1122. self._unknown_command_message = unknown_command_message
  1123. def command(self, command, aliases=None, show_in_keyboard=False,
  1124. description="", authorization_level='admin'):
  1125. """Associate a bot command with a custom handler function.
  1126. Decorate command handlers like this:
  1127. ```
  1128. @bot.command('/mycommand', ['Button'], True, "My command", 'user')
  1129. async def command_handler(bot, update, user_record):
  1130. return "Result"
  1131. ```
  1132. When a message text starts with `/command[@bot_name]`, or with an
  1133. alias, it gets passed to the decorated function.
  1134. `command` is the command name (with or without /).
  1135. `aliases` is a list of aliases; each will call the command handler
  1136. function; the first alias will appear as button in
  1137. default_keyboard.
  1138. `show_in_keyboard`, if True, makes first alias appear in
  1139. default_keyboard.
  1140. `description` can be used to help users understand what `/command`
  1141. does.
  1142. `authorization_level` is the lowest authorization level needed to run
  1143. the command.
  1144. """
  1145. if not isinstance(command, str):
  1146. raise TypeError(f'Command `{command}` is not a string')
  1147. if aliases:
  1148. if not isinstance(aliases, list):
  1149. raise TypeError(f'Aliases is not a list: `{aliases}`')
  1150. if not all(
  1151. [
  1152. isinstance(alias, str)
  1153. for alias in aliases
  1154. ]
  1155. ):
  1156. raise TypeError(
  1157. f'Aliases {aliases} is not a list of strings string'
  1158. )
  1159. command = command.strip('/ ').lower()
  1160. def command_decorator(command_handler):
  1161. async def decorated_command_handler(bot, update, user_record):
  1162. logging.info(
  1163. f"Command `{command}@{bot.name}` called by "
  1164. "`{from_}`".format(
  1165. from_=(
  1166. update['from']
  1167. if 'from' in update
  1168. else update['chat']
  1169. )
  1170. )
  1171. )
  1172. if bot.authorization_function(
  1173. update=update,
  1174. user_record=user_record,
  1175. authorization_level=authorization_level
  1176. ):
  1177. return await command_handler(bot=bot, update=update,
  1178. user_record=user_record)
  1179. return self.unauthorized_message
  1180. self.commands[command] = dict(
  1181. handler=decorated_command_handler,
  1182. description=description,
  1183. authorization_level=authorization_level
  1184. )
  1185. if aliases:
  1186. for alias in aliases:
  1187. self.command_aliases[alias] = decorated_command_handler
  1188. if show_in_keyboard:
  1189. self.default_reply_keyboard_elements.append(aliases[0])
  1190. return command_decorator
  1191. def parser(self, condition, description='', authorization_level='admin',
  1192. argument='text'):
  1193. """Define a text message parser.
  1194. Decorate command handlers like this:
  1195. ```
  1196. def custom_criteria(update):
  1197. return 'from' in update
  1198. @bot.parser(custom_criteria, authorization_level='user')
  1199. async def text_parser(bot, update, user_record):
  1200. return "Result"
  1201. ```
  1202. If condition evaluates True when run on a message text
  1203. (not starting with '/'), such decorated function gets
  1204. called on update.
  1205. Conditions of parsers are evaluated in order; when one is True,
  1206. others will be skipped.
  1207. `description` provides information about the parser.
  1208. `authorization_level` is the lowest authorization level needed to call
  1209. the parser.
  1210. """
  1211. if not callable(condition):
  1212. raise TypeError(
  1213. f'Condition {condition.__name__} is not a callable'
  1214. )
  1215. def parser_decorator(parser):
  1216. async def decorated_parser(bot, message, user_record):
  1217. logging.info(
  1218. f"Text message update matching condition "
  1219. f"`{condition.__name__}@{bot.name}` from "
  1220. "`{user}`".format(
  1221. user=(
  1222. message['from']
  1223. if 'from' in message
  1224. else message['chat']
  1225. )
  1226. )
  1227. )
  1228. if bot.authorization_function(
  1229. update=message,
  1230. user_record=user_record,
  1231. authorization_level=authorization_level
  1232. ):
  1233. return await parser(bot, message, user_record)
  1234. return bot.unauthorized_message
  1235. self.text_message_parsers[condition] = dict(
  1236. handler=decorated_parser,
  1237. description=description,
  1238. authorization_level=authorization_level,
  1239. argument=argument
  1240. )
  1241. return parser_decorator
  1242. def set_command(self, command, handler, aliases=None,
  1243. show_in_keyboard=False, description="",
  1244. authorization_level='admin'):
  1245. """Associate a `command` with a `handler`.
  1246. When a message text starts with `/command[@bot_name]`, or with an
  1247. alias, it gets passed to the decorated function.
  1248. `command` is the command name (with or without /)
  1249. `handler` is the function to be called on update objects.
  1250. `aliases` is a list of aliases; each will call the command handler
  1251. function; the first alias will appear as button in
  1252. default_keyboard.
  1253. `show_in_keyboard`, if True, makes first alias appear in
  1254. default_keyboard.
  1255. `description` is a description and can be used to help users understand
  1256. what `/command` does.
  1257. `authorization_level` is the lowest authorization level needed to run
  1258. the command.
  1259. """
  1260. if not callable(handler):
  1261. raise TypeError(f'Handler `{handler}` is not callable.')
  1262. return self.command(
  1263. command=command, aliases=aliases,
  1264. show_in_keyboard=show_in_keyboard, description=description,
  1265. authorization_level=authorization_level
  1266. )(handler)
  1267. def button(self, prefix, separator=None, description='',
  1268. authorization_level='admin'):
  1269. """Associate a bot button `prefix` with a handler.
  1270. When a callback data text starts with `prefix`, the associated handler
  1271. is called upon the update.
  1272. Decorate button handlers like this:
  1273. ```
  1274. @bot.button('a_prefix:///', description="A button",
  1275. authorization_level='user')
  1276. async def button_handler(bot, update, user_record, data):
  1277. return "Result"
  1278. ```
  1279. `separator` will be used to parse callback data received when a button
  1280. starting with `prefix` will be pressed.
  1281. `description` contains information about the button.
  1282. `authorization_level` is the lowest authorization level needed to
  1283. be allowed to push the button.
  1284. """
  1285. if not isinstance(prefix, str):
  1286. raise TypeError(
  1287. f'Inline button callback_data {prefix} is not a string'
  1288. )
  1289. def button_decorator(handler):
  1290. async def decorated_button_handler(bot, update, user_record):
  1291. logging.info(
  1292. f"Button `{update['data']}`@{bot.name} pressed by "
  1293. f"`{update['from']}`"
  1294. )
  1295. if bot.authorization_function(
  1296. update=update,
  1297. user_record=user_record,
  1298. authorization_level=authorization_level
  1299. ):
  1300. return await handler(bot, update, user_record)
  1301. # Remove `prefix` from `ðata`
  1302. data = extract(update['data'], prefix)
  1303. # If a specific separator or default separator is set,
  1304. # use it to split `data` string in a list.
  1305. # Cast numeric `data` elements to `int`.
  1306. _separator = separator or self.callback_data_separator
  1307. if _separator:
  1308. data = [
  1309. int(element) if element.isnumeric()
  1310. else element
  1311. for element in data.split(_separator)
  1312. ]
  1313. return bot.unauthorized_message
  1314. self.callback_handlers[prefix] = dict(
  1315. handler=decorated_button_handler,
  1316. description=description,
  1317. authorization_level=authorization_level
  1318. )
  1319. return button_decorator
  1320. def query(self, condition, description='', authorization_level='admin'):
  1321. """Define an inline query.
  1322. Decorator: `@bot.query(example)`
  1323. When an inline query matches the `condition` function,
  1324. decorated function is called and passed the query update object
  1325. as argument.
  1326. `description` is a description
  1327. `authorization_level` is the lowest authorization level needed to run
  1328. the command
  1329. """
  1330. if not callable(condition):
  1331. raise TypeError(
  1332. 'Condition {c} is not a callable'.format(
  1333. c=condition.__name__
  1334. )
  1335. )
  1336. def query_decorator(handler):
  1337. async def decorated_query_handler(bot, update, user_record):
  1338. logging.info(
  1339. f"Inline query matching condition "
  1340. f"`{condition.__name__}@{bot.name}` from "
  1341. f"`{update['from']}`"
  1342. )
  1343. if self.authorization_function(
  1344. update=update,
  1345. user_record=user_record,
  1346. authorization_level=authorization_level
  1347. ):
  1348. return await handler(bot=self, update=update,
  1349. user_record=user_record)
  1350. return self.unauthorized_message
  1351. self.inline_query_handlers[condition] = dict(
  1352. handler=decorated_query_handler,
  1353. description=description,
  1354. authorization_level=authorization_level
  1355. )
  1356. return query_decorator
  1357. def set_chat_id_getter(self, getter):
  1358. """Set chat_id getter.
  1359. It must be a function that takes an update and returns the proper
  1360. chat_id.
  1361. """
  1362. assert callable(getter), "Chat id getter must be a function!"
  1363. self.get_chat_id = getter
  1364. @staticmethod
  1365. def get_user_identifier(user_id=None, update=None):
  1366. """Get telegram id of user given an update.
  1367. Result itself may be passed as either parameter (for backward
  1368. compatibility).
  1369. """
  1370. identifier = user_id or update
  1371. assert identifier is not None, (
  1372. "Provide a user_id or update object to get a user identifier."
  1373. )
  1374. if (
  1375. isinstance(identifier, dict)
  1376. and 'message' in identifier
  1377. and 'from' not in identifier
  1378. ):
  1379. identifier = identifier['message']
  1380. if isinstance(identifier, dict) and 'from' in identifier:
  1381. identifier = identifier['from']['id']
  1382. assert type(identifier) is int, (
  1383. "Unable to find a user identifier."
  1384. )
  1385. return identifier
  1386. @staticmethod
  1387. def get_message_identifier(update=dict()):
  1388. """Get a message identifier dictionary to edit `update`.
  1389. Pass the result as keyword arguments to `edit...` API methods.
  1390. """
  1391. if 'message' in update:
  1392. update = update['message']
  1393. if 'chat' in update and 'message_id' in update:
  1394. return dict(
  1395. chat_id=update['chat']['id'],
  1396. message_id=update['message_id']
  1397. )
  1398. elif 'inline_message_id' in update:
  1399. return dict(
  1400. inline_message_id=update['inline_message_id']
  1401. )
  1402. def set_individual_text_message_handler(self, handler,
  1403. update=None, user_id=None):
  1404. """Set a custom text message handler for the user.
  1405. Any text message update from the user will be handled by this custom
  1406. handler instead of default handlers for commands, aliases and text.
  1407. Custom handlers last one single use, but they can call this method and
  1408. set themselves as next custom text message handler.
  1409. """
  1410. identifier = self.get_user_identifier(
  1411. user_id=user_id,
  1412. update=update
  1413. )
  1414. assert callable(handler), (f"Handler `{handler.name}` is not "
  1415. "callable. Custom text message handler "
  1416. "could not be set.")
  1417. self.individual_text_message_handlers[identifier] = handler
  1418. return
  1419. def remove_individual_text_message_handler(self,
  1420. update=None, user_id=None):
  1421. """Remove a custom text message handler for the user.
  1422. Any text message update from the user will be handled by default
  1423. handlers for commands, aliases and text.
  1424. """
  1425. identifier = self.get_user_identifier(
  1426. user_id=user_id,
  1427. update=update
  1428. )
  1429. if identifier in self.individual_text_message_handlers:
  1430. del self.individual_text_message_handlers[identifier]
  1431. return
  1432. def set_default_keyboard(self, keyboard='set_default'):
  1433. """Set a default keyboard for the bot.
  1434. If a keyboard is not passed as argument, a default one is generated,
  1435. based on aliases of commands.
  1436. """
  1437. if keyboard == 'set_default':
  1438. buttons = [
  1439. dict(
  1440. text=x
  1441. )
  1442. for x in self.default_reply_keyboard_elements
  1443. ]
  1444. if len(buttons) == 0:
  1445. self._default_keyboard = None
  1446. else:
  1447. self._default_keyboard = dict(
  1448. keyboard=make_lines_of_buttons(
  1449. buttons,
  1450. (2 if len(buttons) < 4 else 3) # Row length
  1451. ),
  1452. resize_keyboard=True
  1453. )
  1454. else:
  1455. self._default_keyboard = keyboard
  1456. return
  1457. async def webhook_feeder(self, request):
  1458. """Handle incoming HTTP `request`s.
  1459. Get data, feed webhook and return and OK message.
  1460. """
  1461. update = await request.json()
  1462. asyncio.ensure_future(
  1463. self.route_update(update)
  1464. )
  1465. return web.Response(
  1466. body='OK'.encode('utf-8')
  1467. )
  1468. async def get_me(self):
  1469. """Get bot information.
  1470. Restart bots if bot can't be got.
  1471. """
  1472. try:
  1473. me = await self.getMe()
  1474. if isinstance(me, Exception):
  1475. raise me
  1476. elif me is None:
  1477. raise Exception('getMe returned None')
  1478. self._name = me["username"]
  1479. self._telegram_id = me['id']
  1480. except Exception as e:
  1481. logging.error(
  1482. f"API getMe method failed, information about this bot could "
  1483. f"not be retrieved. Restarting in 5 minutes...\n\n"
  1484. f"Error information:\n{e}"
  1485. )
  1486. await asyncio.sleep(5*60)
  1487. self.__class__.stop(
  1488. 65,
  1489. f"Information aformation about this bot could "
  1490. f"not be retrieved. Restarting..."
  1491. )
  1492. def setup(self):
  1493. """Make bot ask for updates and handle responses."""
  1494. self.set_default_keyboard()
  1495. if not self.webhook_url:
  1496. asyncio.ensure_future(self.get_updates())
  1497. else:
  1498. asyncio.ensure_future(self.set_webhook())
  1499. self.__class__.app.router.add_route(
  1500. 'POST', self.webhook_local_address, self.webhook_feeder
  1501. )
  1502. async def close_sessions(self):
  1503. """Close open sessions."""
  1504. for session_name, session in self.sessions.items():
  1505. if not session.closed:
  1506. await session.close()
  1507. async def set_webhook(self, url=None, certificate=None,
  1508. max_connections=None, allowed_updates=None):
  1509. """Set a webhook if token is valid."""
  1510. # Return if token is invalid
  1511. await self.get_me()
  1512. if self.name is None:
  1513. return
  1514. webhook_was_set = await self.setWebhook(
  1515. url=url, certificate=certificate, max_connections=max_connections,
  1516. allowed_updates=allowed_updates
  1517. ) # `setWebhook` API method returns `True` on success
  1518. webhook_information = await self.getWebhookInfo()
  1519. webhook_information['url'] = webhook_information['url'].replace(
  1520. self.token, "<BOT_TOKEN>"
  1521. ).replace(
  1522. self.session_token, "<SESSION_TOKEN>"
  1523. )
  1524. if webhook_was_set:
  1525. logging.info(
  1526. f"Webhook was set correctly.\n"
  1527. f"Webhook information: {webhook_information}"
  1528. )
  1529. else:
  1530. logging.error(
  1531. f"Failed to set webhook!\n"
  1532. f"Webhook information: {webhook_information}"
  1533. )
  1534. async def get_updates(self, timeout=30, limit=100, allowed_updates=None,
  1535. error_cooldown=10):
  1536. """Get updates using long polling.
  1537. timeout : int
  1538. Timeout set for Telegram servers. Make sure that connection timeout
  1539. is greater than `timeout`.
  1540. limit : int (1 - 100)
  1541. Max number of updates to be retrieved.
  1542. allowed_updates : List(str)
  1543. List of update types to be retrieved.
  1544. Empty list to allow all updates.
  1545. None to fallback to class default.
  1546. """
  1547. # Return if token is invalid
  1548. await self.get_me()
  1549. if self.name is None:
  1550. return
  1551. # Set custom list of allowed updates or fallback to class default list
  1552. if allowed_updates is None:
  1553. allowed_updates = self.allowed_updates
  1554. await self.deleteWebhook() # Remove eventually active webhook
  1555. update = None # Do not update offset if no update is received
  1556. while True:
  1557. updates = await self.getUpdates(
  1558. offset=self._offset,
  1559. timeout=timeout,
  1560. limit=limit,
  1561. allowed_updates=allowed_updates
  1562. )
  1563. if updates is None:
  1564. continue
  1565. elif isinstance(updates, TelegramError):
  1566. logging.error(
  1567. f"Waiting {error_cooldown} seconds before trying again..."
  1568. )
  1569. await asyncio.sleep(error_cooldown)
  1570. continue
  1571. for update in updates:
  1572. asyncio.ensure_future(self.route_update(update))
  1573. if update is not None:
  1574. self._offset = update['update_id'] + 1
  1575. def set_router(self, event, handler):
  1576. """Set `handler` as router for `event`."""
  1577. self.routing_table[event] = handler
  1578. async def route_update(self, update):
  1579. """Pass `update` to proper method.
  1580. Update objects have two keys:
  1581. - `update_id` (which is used as offset while retrieving new updates)
  1582. - One and only one of the following
  1583. `message`
  1584. `edited_message`
  1585. `channel_post`
  1586. `edited_channel_post`
  1587. `inline_query`
  1588. `chosen_inline_result`
  1589. `callback_query`
  1590. `shipping_query`
  1591. `pre_checkout_query`
  1592. `poll`
  1593. """
  1594. if (
  1595. self.under_maintenance
  1596. and not self.is_allowed_during_maintenance(update)
  1597. ):
  1598. return await self.handle_update_during_maintenance(update)
  1599. for key, value in update.items():
  1600. if key in self.routing_table:
  1601. with self.db as db:
  1602. user_record = db['users'].find_one(
  1603. telegram_id=self.get_user_identifier(
  1604. update=value
  1605. )
  1606. )
  1607. return await self.routing_table[key](value, user_record)
  1608. logging.error(f"Unknown type of update.\n{update}")
  1609. def additional_task(self, when='BEFORE', *args, **kwargs):
  1610. """Add a task before at app start or cleanup.
  1611. Decorate an async function to have it awaited `BEFORE` or `AFTER` main
  1612. loop.
  1613. """
  1614. when = when[0].lower()
  1615. def additional_task_decorator(task):
  1616. if when == 'b':
  1617. self.preliminary_tasks.append(task(*args, **kwargs))
  1618. elif when == 'a':
  1619. self.final_tasks.append(task(*args, **kwargs))
  1620. return additional_task_decorator
  1621. @classmethod
  1622. async def start_app(cls):
  1623. """Start running `aiohttp.web.Application`.
  1624. It will route webhook-received updates and other custom paths.
  1625. """
  1626. assert cls.local_host is not None, "Invalid local host"
  1627. assert cls.port is not None, "Invalid port"
  1628. cls.runner = web.AppRunner(cls.app)
  1629. await cls.runner.setup()
  1630. cls.server = web.TCPSite(cls.runner, cls.local_host, cls.port)
  1631. await cls.server.start()
  1632. logging.info(f"App running at http://{cls.local_host}:{cls.port}")
  1633. @classmethod
  1634. async def stop_app(cls):
  1635. """Close bot sessions and cleanup."""
  1636. for bot in cls.bots:
  1637. await asyncio.gather(
  1638. *bot.final_tasks
  1639. )
  1640. await bot.close_sessions()
  1641. await cls.runner.cleanup()
  1642. @classmethod
  1643. def stop(cls, message, final_state=0):
  1644. """Log a final `message`, stop loop and set exiting `code`.
  1645. All bots and the web app will be terminated gracefully.
  1646. The final state may be retrieved to get information about what stopped
  1647. the bots.
  1648. """
  1649. logging.info(message)
  1650. cls.final_state = final_state
  1651. cls.loop.stop()
  1652. return
  1653. @classmethod
  1654. def run(cls, local_host=None, port=None):
  1655. """Run aiohttp web app and all Bot instances.
  1656. Each bot will receive updates via long polling or webhook according to
  1657. its initialization parameters.
  1658. A single aiohttp.web.Application instance will be run (cls.app) on
  1659. local_host:port and it may serve custom-defined routes as well.
  1660. """
  1661. if local_host is not None:
  1662. cls.local_host = local_host
  1663. if port is not None:
  1664. cls.port = port
  1665. try:
  1666. cls.loop.run_until_complete(
  1667. asyncio.gather(
  1668. *[
  1669. preliminary_task
  1670. for bot in cls.bots
  1671. for preliminary_task in bot.preliminary_tasks
  1672. ]
  1673. )
  1674. )
  1675. except Exception as e:
  1676. logging.error(f"{e}", exc_info=True)
  1677. for bot in cls.bots:
  1678. bot.setup()
  1679. asyncio.ensure_future(cls.start_app())
  1680. try:
  1681. cls.loop.run_forever()
  1682. except KeyboardInterrupt:
  1683. logging.info("Stopped by KeyboardInterrupt")
  1684. except Exception as e:
  1685. logging.error(f"{e}", exc_info=True)
  1686. finally:
  1687. cls.loop.run_until_complete(cls.stop_app())
  1688. return cls.final_state