Queer European MD passionate about IT

bot.py 72 KB

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