Queer European MD passionate about IT

bot.py 77 KB

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