Queer European MD passionate about IT

bot.py 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478
  1. """Provide a simple Bot object, mirroring Telegram API methods.
  2. camelCase methods mirror API directly, while snake_case ones act as middleware
  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, language):
  15. return "Bar!"
  16. @webhook_bot.command('/bar')
  17. async def bar_command(bot, update, user_record, language):
  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. import datetime
  29. import io
  30. import inspect
  31. import logging
  32. import os
  33. import re
  34. import sys
  35. from collections import OrderedDict
  36. from typing import Callable, List, Union, Dict
  37. # Third party modules
  38. import aiohttp.web
  39. # Project modules
  40. from davtelepot.api import TelegramBot, TelegramError
  41. from davtelepot.database import ObjectWithDatabase
  42. from davtelepot.languages import MultiLanguageObject
  43. from davtelepot.messages import davtelepot_messages
  44. from davtelepot.utilities import (
  45. async_get, escape_html_chars, extract, get_secure_key,
  46. make_inline_query_answer, make_lines_of_buttons, remove_html_tags
  47. )
  48. # Do not log aiohttp `INFO` and `DEBUG` levels
  49. logging.getLogger('aiohttp').setLevel(logging.WARNING)
  50. # Same with chardet
  51. logging.getLogger('chardet').setLevel(logging.WARNING)
  52. # Some methods are not implemented yet: that's the reason behind the following statement
  53. # noinspection PyUnusedLocal,PyMethodMayBeStatic,PyMethodMayBeStatic
  54. class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject):
  55. """Simple Bot object, providing methods corresponding to Telegram bot API.
  56. Multiple Bot() instances may be run together, along with a aiohttp web app.
  57. """
  58. bots = []
  59. _path = '.'
  60. runner = None
  61. # TODO: find a way to choose port automatically by default
  62. # Setting port to 0 does not work unfortunately
  63. local_host = 'localhost'
  64. port = 3000
  65. final_state = 0
  66. _maintenance_message = ("I am currently under maintenance!\n"
  67. "Please retry later...")
  68. _authorization_denied_message = None
  69. _unknown_command_message = None
  70. TELEGRAM_MESSAGES_MAX_LEN = 4096
  71. _max_message_length = 3 * (TELEGRAM_MESSAGES_MAX_LEN - 100)
  72. _default_inline_query_answer = [
  73. dict(
  74. type='article',
  75. id=0,
  76. title="I cannot answer this query, sorry",
  77. input_message_content=dict(
  78. message_text="I'm sorry "
  79. "but I could not find an answer for your query."
  80. )
  81. )
  82. ]
  83. _log_file_name = None
  84. _errors_file_name = None
  85. _documents_max_dimension = 50 * 1000 * 1000 # 50 MB
  86. def __init__(
  87. self, token, hostname='', certificate=None, max_connections=40,
  88. allowed_updates=None, database_url='bot.db'
  89. ):
  90. """Init a bot instance.
  91. token : str
  92. Telegram bot API token.
  93. hostname : str
  94. Domain (or public IP address) for webhooks.
  95. certificate : str
  96. Path to domain certificate.
  97. max_connections : int (1 - 100)
  98. Maximum number of HTTPS connections allowed.
  99. allowed_updates : List(str)
  100. Allowed update types (empty list to allow all).
  101. @type allowed_updates: list(str)
  102. """
  103. # Append `self` to class list of instances
  104. self.__class__.bots.append(self)
  105. # Call superclasses constructors with proper arguments
  106. TelegramBot.__init__(self, token)
  107. ObjectWithDatabase.__init__(self, database_url=database_url)
  108. MultiLanguageObject.__init__(self)
  109. self.messages['davtelepot'] = davtelepot_messages
  110. self._path = None
  111. self.preliminary_tasks = []
  112. self.final_tasks = []
  113. self._offset = 0
  114. self._hostname = hostname
  115. self._certificate = certificate
  116. self._max_connections = max_connections
  117. self._allowed_updates = allowed_updates
  118. self._max_message_length = None
  119. self._session_token = get_secure_key(length=10)
  120. self._name = None
  121. self._telegram_id = None
  122. # The following routing table associates each type of Telegram `update`
  123. # with a Bot method to be invoked on it.
  124. self.routing_table = {
  125. 'message': self.message_router,
  126. 'edited_message': self.edited_message_handler,
  127. 'channel_post': self.channel_post_handler,
  128. 'edited_channel_post': self.edited_channel_post_handler,
  129. 'inline_query': self.inline_query_handler,
  130. 'chosen_inline_result': self.chosen_inline_result_handler,
  131. 'callback_query': self.callback_query_handler,
  132. 'shipping_query': self.shipping_query_handler,
  133. 'pre_checkout_query': self.pre_checkout_query_handler,
  134. 'poll': self.poll_handler,
  135. }
  136. # Different message update types need different handlers
  137. self.message_handlers = {
  138. 'text': self.text_message_handler,
  139. 'audio': self.audio_file_handler,
  140. 'document': self.document_message_handler,
  141. 'animation': self.animation_message_handler,
  142. 'game': self.game_message_handler,
  143. 'photo': self.photo_message_handler,
  144. 'sticker': self.sticker_message_handler,
  145. 'video': self.video_message_handler,
  146. 'voice': self.voice_message_handler,
  147. 'video_note': self.video_note_message_handler,
  148. 'contact': self.contact_message_handler,
  149. 'location': self.location_message_handler,
  150. 'venue': self.venue_message_handler,
  151. 'poll': self.poll_message_handler,
  152. 'new_chat_members': self.new_chat_members_message_handler,
  153. 'left_chat_member': self.left_chat_member_message_handler,
  154. 'new_chat_title': self.new_chat_title_message_handler,
  155. 'new_chat_photo': self.new_chat_photo_message_handler,
  156. 'delete_chat_photo': self.delete_chat_photo_message_handler,
  157. 'group_chat_created': self.group_chat_created_message_handler,
  158. 'supergroup_chat_created': (
  159. self.supergroup_chat_created_message_handler
  160. ),
  161. 'channel_chat_created': self.channel_chat_created_message_handler,
  162. 'migrate_to_chat_id': self.migrate_to_chat_id_message_handler,
  163. 'migrate_from_chat_id': self.migrate_from_chat_id_message_handler,
  164. 'pinned_message': self.pinned_message_message_handler,
  165. 'invoice': self.invoice_message_handler,
  166. 'successful_payment': self.successful_payment_message_handler,
  167. 'connected_website': self.connected_website_message_handler,
  168. 'passport_data': self.passport_data_message_handler,
  169. 'dice': self.dice_handler,
  170. }
  171. # Special text message handlers: individual, commands, aliases, parsers
  172. self.individual_text_message_handlers = dict()
  173. self.commands = OrderedDict()
  174. self.command_aliases = OrderedDict()
  175. self.messages['commands'] = dict()
  176. self.messages['reply_keyboard_buttons'] = dict()
  177. self._unknown_command_message = None
  178. self.text_message_parsers = OrderedDict()
  179. self.document_handlers = OrderedDict()
  180. self.individual_document_message_handlers = dict()
  181. # General handlers
  182. self.individual_handlers = dict()
  183. self.handlers = OrderedDict()
  184. # Support for /help command
  185. self.messages['help_sections'] = OrderedDict()
  186. # Handle location messages
  187. self.individual_location_handlers = dict()
  188. # Handle voice messages
  189. self.individual_voice_handlers = dict()
  190. # Callback query-related properties
  191. self.callback_handlers = OrderedDict()
  192. self._callback_data_separator = None
  193. # Inline query-related properties
  194. self.inline_query_handlers = OrderedDict()
  195. self._default_inline_query_answer = None
  196. self.chosen_inline_result_handlers = dict()
  197. # Maintenance properties
  198. self._under_maintenance = False
  199. self._allowed_during_maintenance = []
  200. self._maintenance_message = None
  201. # Default chat_id getter: same chat as update
  202. self.get_chat_id = lambda update: (
  203. update['message']['chat']['id']
  204. if 'message' in update and 'chat' in update['message']
  205. else update['chat']['id']
  206. if 'chat' in update
  207. else None
  208. )
  209. # Function to get updated list of bot administrators
  210. self._get_administrators = lambda bot: []
  211. # Message to be returned if user is not allowed to call method
  212. self._authorization_denied_message = None
  213. # Default authorization function (always return True)
  214. self.authorization_function = (
  215. lambda update, user_record=None, authorization_level='user': True
  216. )
  217. self.default_reply_keyboard_elements = []
  218. self.recent_users = OrderedDict()
  219. self._log_file_name = None
  220. self._errors_file_name = None
  221. self.placeholder_requests = dict()
  222. self.shared_data = dict()
  223. self.Role = None
  224. self.packages = [sys.modules['davtelepot']]
  225. self._documents_max_dimension = None
  226. # Add `users` table with its fields if missing
  227. if 'users' not in self.db.tables:
  228. table = self.db.create_table(
  229. table_name='users'
  230. )
  231. table.create_column(
  232. 'telegram_id',
  233. self.db.types.integer
  234. )
  235. table.create_column(
  236. 'privileges',
  237. self.db.types.integer
  238. )
  239. table.create_column(
  240. 'username',
  241. self.db.types.string(64)
  242. )
  243. table.create_column(
  244. 'first_name',
  245. self.db.types.string(64)
  246. )
  247. table.create_column(
  248. 'last_name',
  249. self.db.types.string(64)
  250. )
  251. table.create_column(
  252. 'language_code',
  253. self.db.types.string(8)
  254. )
  255. table.create_column(
  256. 'selected_language_code',
  257. self.db.types.string(8)
  258. )
  259. if 'user_profile_photos' not in self.db.tables:
  260. table = self.db.create_table(
  261. table_name='user_profile_photos'
  262. )
  263. table.create_column(
  264. 'user_id',
  265. self.db.types.integer
  266. )
  267. table.create_column(
  268. 'telegram_file_id',
  269. self.db.types.string(128)
  270. )
  271. table.create_column(
  272. 'update_datetime',
  273. self.db.types.datetime
  274. )
  275. return
  276. @property
  277. def path(self):
  278. """Path where files should be looked for.
  279. If no instance path is set, return class path.
  280. """
  281. return self._path or self.__class__._path
  282. @classmethod
  283. def set_class_path(cls, path):
  284. """Set class path attribute."""
  285. cls._path = path
  286. def set_path(self, path):
  287. """Set instance path attribute."""
  288. self._path = path
  289. @property
  290. def log_file_name(self):
  291. """Return log file name.
  292. Fallback to class file name if set, otherwise return None.
  293. """
  294. return self._log_file_name or self.__class__._log_file_name
  295. @property
  296. def log_file_path(self):
  297. """Return log file path basing on self.path and `_log_file_name`.
  298. Fallback to class file if set, otherwise return None.
  299. """
  300. if self.log_file_name:
  301. return f"{self.path}/data/{self.log_file_name}"
  302. def set_log_file_name(self, file_name):
  303. """Set log file name."""
  304. self._log_file_name = file_name
  305. @classmethod
  306. def set_class_log_file_name(cls, file_name):
  307. """Set class log file name."""
  308. cls._log_file_name = file_name
  309. @property
  310. def errors_file_name(self):
  311. """Return errors file name.
  312. Fallback to class file name if set, otherwise return None.
  313. """
  314. return self._errors_file_name or self.__class__._errors_file_name
  315. @property
  316. def errors_file_path(self):
  317. """Return errors file path basing on self.path and `_errors_file_name`.
  318. Fallback to class file if set, otherwise return None.
  319. """
  320. if self.errors_file_name:
  321. return f"{self.path}/data/{self.errors_file_name}"
  322. def set_errors_file_name(self, file_name):
  323. """Set errors file name."""
  324. self._errors_file_name = file_name
  325. @classmethod
  326. def set_class_errors_file_name(cls, file_name):
  327. """Set class errors file name."""
  328. cls._errors_file_name = file_name
  329. @classmethod
  330. def get(cls, token, *args, **kwargs):
  331. """Given a `token`, return class instance with that token.
  332. If no instance is found, instantiate it.
  333. Positional and keyword arguments may be passed as well.
  334. """
  335. for bot in cls.bots:
  336. if bot.token == token:
  337. return bot
  338. return cls(token, *args, **kwargs)
  339. @property
  340. def hostname(self):
  341. """Hostname for the webhook URL.
  342. It must be a public domain or IP address. Port may be specified.
  343. A custom webhook url, including bot token and a random token, will be
  344. generated for Telegram to post new updates.
  345. """
  346. return self._hostname
  347. @property
  348. def webhook_url(self):
  349. """URL where Telegram servers should post new updates.
  350. It must be a public domain name or IP address. Port may be specified.
  351. """
  352. if not self.hostname:
  353. return ''
  354. return (
  355. f"{self.hostname}/webhook/{self.token}_{self.session_token}/"
  356. )
  357. @property
  358. def webhook_local_address(self):
  359. """Local address where Telegram updates are routed by revers proxy."""
  360. return (
  361. f"/webhook/{self.token}_{self.session_token}/"
  362. )
  363. @property
  364. def certificate(self):
  365. """Public certificate for `webhook_url`.
  366. May be self-signed
  367. """
  368. return self._certificate
  369. @property
  370. def max_connections(self):
  371. """Maximum number of simultaneous HTTPS connections allowed.
  372. Telegram will open as many connections as possible to boost bot’s
  373. throughput, lower values limit the load on bot‘s server.
  374. """
  375. return self._max_connections
  376. @property
  377. def allowed_updates(self):
  378. """List of update types to be retrieved.
  379. Empty list to allow all updates.
  380. """
  381. return self._allowed_updates or []
  382. @property
  383. def max_message_length(self) -> int:
  384. return self._max_message_length or self.__class__._max_message_length
  385. @classmethod
  386. def set_class_max_message_length(cls, max_message_length: int):
  387. cls._max_message_length = max_message_length
  388. def set_max_message_length(self, max_message_length: int):
  389. self._max_message_length = max_message_length
  390. @property
  391. def name(self):
  392. """Bot name."""
  393. return self._name
  394. @property
  395. def telegram_id(self):
  396. """Telegram id of this bot."""
  397. return self._telegram_id
  398. @property
  399. def session_token(self):
  400. """Return a token generated with the current instantiation."""
  401. return self._session_token
  402. @property
  403. def offset(self):
  404. """Return last update id.
  405. Useful to ignore repeated updates and restore original update order.
  406. """
  407. return self._offset
  408. @property
  409. def under_maintenance(self):
  410. """Return True if bot is under maintenance.
  411. While under maintenance, bot will reply `self.maintenance_message` to
  412. any update, except those which `self.is_allowed_during_maintenance`
  413. returns True for.
  414. """
  415. return self._under_maintenance
  416. @property
  417. def allowed_during_maintenance(self):
  418. """Return the list of criteria to allow an update during maintenance.
  419. If any of this criteria returns True on an update, that update will be
  420. handled even during maintenance.
  421. """
  422. return self._allowed_during_maintenance
  423. @property
  424. def maintenance_message(self):
  425. """Message to be returned if bot is under maintenance.
  426. If instance message is not set, class message is returned.
  427. """
  428. if self._maintenance_message:
  429. return self._maintenance_message
  430. if self.__class__.maintenance_message:
  431. return self.__class__._maintenance_message
  432. return ("I am currently under maintenance!\n"
  433. "Please retry later...")
  434. @property
  435. def authorization_denied_message(self):
  436. """Return this text if user is unauthorized to make a request.
  437. If instance message is not set, class message is returned.
  438. """
  439. if self._authorization_denied_message:
  440. return self._authorization_denied_message
  441. return self.__class__._authorization_denied_message
  442. def get_keyboard(self, user_record=None, update=None,
  443. telegram_id=None):
  444. """Return a reply keyboard translated into user language."""
  445. if user_record is None:
  446. user_record = dict()
  447. if update is None:
  448. update = dict()
  449. if (not user_record) and telegram_id:
  450. with self.db as db:
  451. user_record = db['users'].find_one(telegram_id=telegram_id)
  452. buttons = [
  453. dict(
  454. text=self.get_message(
  455. 'reply_keyboard_buttons', command,
  456. user_record=user_record, update=update,
  457. default_message=element['reply_keyboard_button']
  458. )
  459. )
  460. for command, element in self.commands.items()
  461. if 'reply_keyboard_button' in element
  462. and self.authorization_function(
  463. update=update,
  464. user_record=user_record,
  465. authorization_level=element['authorization_level']
  466. )
  467. ]
  468. if len(buttons) == 0:
  469. return
  470. return dict(
  471. keyboard=make_lines_of_buttons(
  472. buttons,
  473. (2 if len(buttons) < 4 else 3) # Row length
  474. ),
  475. resize_keyboard=True
  476. )
  477. @property
  478. def unknown_command_message(self):
  479. """Message to be returned if user sends an unknown command.
  480. If instance message is not set, class message is returned.
  481. """
  482. if self._unknown_command_message:
  483. message = self._unknown_command_message
  484. else:
  485. message = self.__class__._unknown_command_message
  486. if isinstance(message, str):
  487. message = message.format(bot=self)
  488. return message
  489. @property
  490. def callback_data_separator(self):
  491. """Separator between callback data elements.
  492. Example of callback_data: 'my_button_prefix:///1|4|test'
  493. Prefix: `my_button_prefix:///`
  494. Separator: `|` <--- this is returned
  495. Data: `['1', '4', 'test']`
  496. """
  497. return self._callback_data_separator
  498. def set_callback_data_separator(self, separator):
  499. """Set a callback_data separator.
  500. See property `callback_data_separator` for details.
  501. """
  502. assert type(separator) is str, "Separator must be a string!"
  503. self._callback_data_separator = separator
  504. @property
  505. def default_inline_query_answer(self):
  506. """Answer to be returned if inline query returned None.
  507. If instance default answer is not set, class one is returned.
  508. """
  509. if self._default_inline_query_answer:
  510. return self._default_inline_query_answer
  511. return self.__class__._default_inline_query_answer
  512. @classmethod
  513. def set_class_default_inline_query_answer(cls,
  514. default_inline_query_answer):
  515. """Set class default inline query answer.
  516. It will be returned if an inline query returned no answer.
  517. """
  518. cls._default_inline_query_answer = make_inline_query_answer(
  519. default_inline_query_answer
  520. )
  521. def set_default_inline_query_answer(self, default_inline_query_answer):
  522. """Set a custom default_inline_query_answer.
  523. It will be returned when no answer is found for an inline query.
  524. If instance answer is None, default class answer is used.
  525. """
  526. self._default_inline_query_answer = make_inline_query_answer(
  527. default_inline_query_answer
  528. )
  529. def set_get_administrator_function(self,
  530. new_function: Callable[[object],
  531. list]):
  532. """Set a new get_administrators function.
  533. This function should take bot as argument and return an updated list
  534. of its administrators.
  535. Example:
  536. ```python
  537. def get_administrators(bot):
  538. admins = bot.db['users'].find(privileges=2)
  539. return list(admins)
  540. ```
  541. """
  542. self._get_administrators = new_function
  543. @property
  544. def administrators(self):
  545. return self._get_administrators(self)
  546. @classmethod
  547. def set_class_documents_max_dimension(cls, documents_max_dimension: int):
  548. cls._documents_max_dimension = documents_max_dimension
  549. def set_documents_max_dimension(self, documents_max_dimension: int):
  550. self._documents_max_dimension = documents_max_dimension
  551. @property
  552. def documents_max_dimension(self) -> int:
  553. return int(self._documents_max_dimension
  554. or self.__class__._documents_max_dimension)
  555. async def message_router(self, update, user_record, language):
  556. """Route Telegram `message` update to appropriate message handler."""
  557. bot = self
  558. for key in self.message_handlers:
  559. if key in update:
  560. return await self.message_handlers[key](**{
  561. name: argument
  562. for name, argument in locals().items()
  563. if name in inspect.signature(
  564. self.message_handlers[key]
  565. ).parameters
  566. })
  567. logging.error(
  568. f"The following message update was received: {update}\n"
  569. "However, this message type is unknown."
  570. )
  571. async def edited_message_handler(self, update, user_record, language=None):
  572. """Handle Telegram `edited_message` update."""
  573. logging.info(
  574. f"The following update was received: {update}\n"
  575. "However, this edited_message handler does nothing yet."
  576. )
  577. return
  578. async def channel_post_handler(self, update, user_record, language=None):
  579. """Handle Telegram `channel_post` update."""
  580. logging.info(
  581. f"The following update was received: {update}\n"
  582. "However, this channel_post handler does nothing yet."
  583. )
  584. return
  585. async def edited_channel_post_handler(self, update, user_record, language=None):
  586. """Handle Telegram `edited_channel_post` update."""
  587. logging.info(
  588. f"The following update was received: {update}\n"
  589. "However, this edited_channel_post handler does nothing yet."
  590. )
  591. return
  592. async def inline_query_handler(self, update, user_record, language=None):
  593. """Handle Telegram `inline_query` update.
  594. Answer it with results or log errors.
  595. """
  596. query = update['query']
  597. results, switch_pm_text, switch_pm_parameter = None, None, None
  598. for condition, handler in self.inline_query_handlers.items():
  599. if condition(query):
  600. _handler = handler['handler']
  601. results = await _handler(bot=self, update=update,
  602. user_record=user_record)
  603. break
  604. if not results:
  605. results = self.default_inline_query_answer
  606. if isinstance(results, dict) and 'answer' in results:
  607. if 'switch_pm_text' in results:
  608. switch_pm_text = results['switch_pm_text']
  609. if 'switch_pm_parameter' in results:
  610. switch_pm_parameter = results['switch_pm_parameter']
  611. results = results['answer']
  612. try:
  613. await self.answer_inline_query(
  614. update=update,
  615. user_record=user_record,
  616. results=results,
  617. cache_time=10,
  618. is_personal=True,
  619. switch_pm_text=switch_pm_text,
  620. switch_pm_parameter=switch_pm_parameter
  621. )
  622. except Exception as e:
  623. logging.info("Error answering inline query\n{}".format(e))
  624. return
  625. async def chosen_inline_result_handler(self, update, user_record, language=None):
  626. """Handle Telegram `chosen_inline_result` update."""
  627. if user_record is not None:
  628. user_id = user_record['telegram_id']
  629. else:
  630. user_id = update['from']['id']
  631. if user_id in self.chosen_inline_result_handlers:
  632. result_id = update['result_id']
  633. handlers = self.chosen_inline_result_handlers[user_id]
  634. if result_id in handlers:
  635. await handlers[result_id](update)
  636. return
  637. def set_chosen_inline_result_handler(self, user_id, result_id, handler):
  638. """Associate a `handler` to a `result_id` for `user_id`.
  639. When an inline result is chosen having that id, `handler` will
  640. be called and passed the update as argument.
  641. """
  642. if type(user_id) is dict:
  643. user_id = user_id['from']['id']
  644. assert type(user_id) is int, "user_id must be int!"
  645. # Query result ids are parsed as str by telegram
  646. result_id = str(result_id)
  647. assert callable(handler), "Handler must be callable"
  648. if user_id not in self.chosen_inline_result_handlers:
  649. self.chosen_inline_result_handlers[user_id] = {}
  650. self.chosen_inline_result_handlers[user_id][result_id] = handler
  651. return
  652. async def callback_query_handler(self, update, user_record, language=None):
  653. """Handle Telegram `callback_query` update.
  654. A callback query is sent when users press inline keyboard buttons.
  655. Bad clients may send malformed or deceiving callback queries:
  656. never put secrets in buttons and always check request validity!
  657. Get an `answer` from the callback handler associated to the query
  658. prefix and use it to edit the source message (or send new ones
  659. if text is longer than single message limit).
  660. Anyway, the query is answered, otherwise the client would hang and
  661. the bot would look like idle.
  662. """
  663. assert 'data' in update, "Malformed callback query lacking data field."
  664. answer = dict()
  665. data = update['data']
  666. for start_text, handler in self.callback_handlers.items():
  667. if data.startswith(start_text):
  668. _function = handler['handler']
  669. answer = await _function(
  670. bot=self,
  671. update=update,
  672. user_record=user_record,
  673. language=language
  674. )
  675. break
  676. if answer is None:
  677. answer = ''
  678. if type(answer) is str:
  679. answer = dict(text=answer)
  680. assert type(answer) is dict, "Invalid callback query answer."
  681. if 'edit' in answer:
  682. message_identifier = self.get_message_identifier(update)
  683. edit = answer['edit']
  684. method = (
  685. self.edit_message_text if 'text' in edit
  686. else self.editMessageCaption if 'caption' in edit
  687. else self.editMessageReplyMarkup if 'reply_markup' in edit
  688. else (lambda *args, **kwargs: None)
  689. )
  690. try:
  691. await method(**message_identifier, **edit)
  692. except TelegramError as e:
  693. logging.info("Message was not modified:\n{}".format(e))
  694. try:
  695. return await self.answerCallbackQuery(
  696. callback_query_id=update['id'],
  697. **{
  698. key: (val[:180] if key == 'text' else val)
  699. for key, val in answer.items()
  700. if key in ('text', 'show_alert', 'cache_time')
  701. }
  702. )
  703. except TelegramError as e:
  704. logging.error(e)
  705. return
  706. async def shipping_query_handler(self, update, user_record, language=None):
  707. """Handle Telegram `shipping_query` update."""
  708. logging.info(
  709. f"The following update was received: {update}\n"
  710. "However, this shipping_query handler does nothing yet."
  711. )
  712. return
  713. async def pre_checkout_query_handler(self, update, user_record, language=None):
  714. """Handle Telegram `pre_checkout_query` update."""
  715. logging.info(
  716. f"The following update was received: {update}\n"
  717. "However, this pre_checkout_query handler does nothing yet."
  718. )
  719. return
  720. async def poll_handler(self, update, user_record, language=None):
  721. """Handle Telegram `poll` update."""
  722. logging.info(
  723. f"The following update was received: {update}\n"
  724. "However, this poll handler does nothing yet."
  725. )
  726. return
  727. async def text_message_handler(self, update, user_record, language=None):
  728. """Handle `text` message update."""
  729. replier, reply = None, None
  730. text = update['text']
  731. lowered_text = text.lower()
  732. user_id = update['from']['id'] if 'from' in update else None
  733. if user_id in self.individual_text_message_handlers:
  734. replier = self.individual_text_message_handlers[user_id]
  735. del self.individual_text_message_handlers[user_id]
  736. elif text.startswith('/'): # Handle commands
  737. # A command must always start with the ‘/’ symbol and may not be
  738. # longer than 32 characters.
  739. # Commands can use latin letters, numbers and underscores.
  740. command = re.search(
  741. r"([A-z_1-9]){1,32}", # Command pattern (without leading `/`)
  742. lowered_text
  743. ).group(0) # Get the first group of characters matching pattern
  744. if command in self.commands:
  745. replier = self.commands[command]['handler']
  746. elif command in [
  747. description['language_labelled_commands'][language]
  748. for c, description in self.commands.items()
  749. if 'language_labelled_commands' in description
  750. and language in description['language_labelled_commands']
  751. ]:
  752. replier = [
  753. description['handler']
  754. for c, description in self.commands.items()
  755. if 'language_labelled_commands' in description
  756. and language in description['language_labelled_commands']
  757. and command == description['language_labelled_commands'][language]
  758. ][0]
  759. elif 'chat' in update and update['chat']['id'] > 0:
  760. reply = dict(text=self.unknown_command_message)
  761. else: # Handle command aliases and text parsers
  762. # Aliases are case insensitive: text and alias are both .lower()
  763. for alias, function in self.command_aliases.items():
  764. if lowered_text.startswith(alias.lower()):
  765. replier = function
  766. break
  767. # Text message update parsers
  768. for check_function, parser in self.text_message_parsers.items():
  769. if check_function(
  770. **{name: argument
  771. for name, argument in locals().items()
  772. if name in inspect.signature(
  773. check_function).parameters}):
  774. replier = parser['handler']
  775. break
  776. if replier:
  777. reply = await replier(
  778. bot=self,
  779. **{
  780. name: argument
  781. for name, argument in locals().items()
  782. if name in inspect.signature(
  783. replier
  784. ).parameters
  785. }
  786. )
  787. if reply:
  788. if type(reply) is str:
  789. reply = dict(text=reply)
  790. try:
  791. return await self.reply(update=update, **reply)
  792. except Exception as e:
  793. logging.error(
  794. f"Failed to handle text message:\n{e}",
  795. exc_info=True
  796. )
  797. return
  798. async def audio_file_handler(self, update, user_record, language=None):
  799. """Handle `audio` file update."""
  800. logging.info(
  801. "A audio file update was received, "
  802. "but this handler does nothing yet."
  803. )
  804. async def document_message_handler(self, update, user_record, language=None):
  805. """Handle `document` message update."""
  806. replier, reply = None, None
  807. user_id = update['from']['id'] if 'from' in update else None
  808. if user_id in self.individual_document_message_handlers:
  809. replier = self.individual_document_message_handlers[user_id]
  810. del self.individual_document_message_handlers[user_id]
  811. else:
  812. for check_function, handler in self.document_handlers.items():
  813. if check_function(update):
  814. replier = handler['handler']
  815. break
  816. if replier:
  817. reply = await replier(
  818. bot=self,
  819. **{
  820. name: argument
  821. for name, argument in locals().items()
  822. if name in inspect.signature(
  823. replier
  824. ).parameters
  825. }
  826. )
  827. if reply:
  828. if type(reply) is str:
  829. reply = dict(text=reply)
  830. try:
  831. return await self.reply(update=update, **reply)
  832. except Exception as e:
  833. logging.error(
  834. f"Failed to handle document:\n{e}",
  835. exc_info=True
  836. )
  837. return
  838. async def animation_message_handler(self, update, user_record, language=None):
  839. """Handle `animation` message update."""
  840. logging.info(
  841. "A animation message update was received, "
  842. "but this handler does nothing yet."
  843. )
  844. async def game_message_handler(self, update, user_record, language=None):
  845. """Handle `game` message update."""
  846. logging.info(
  847. "A game message update was received, "
  848. "but this handler does nothing yet."
  849. )
  850. async def photo_message_handler(self, update, user_record, language=None):
  851. """Handle `photo` message update."""
  852. return await self.general_handler(update=update,
  853. user_record=user_record,
  854. language=language,
  855. update_type='photo')
  856. async def sticker_message_handler(self, update, user_record, language=None):
  857. """Handle `sticker` message update."""
  858. logging.info(
  859. "A sticker message update was received, "
  860. "but this handler does nothing yet."
  861. )
  862. async def video_message_handler(self, update, user_record, language=None):
  863. """Handle `video` message update."""
  864. logging.info(
  865. "A video message update was received, "
  866. "but this handler does nothing yet."
  867. )
  868. async def voice_message_handler(self, update, user_record, language=None):
  869. """Handle `voice` message update."""
  870. replier, reply = None, None
  871. user_id = update['from']['id'] if 'from' in update else None
  872. if user_id in self.individual_voice_handlers:
  873. replier = self.individual_voice_handlers[user_id]
  874. del self.individual_voice_handlers[user_id]
  875. if replier:
  876. reply = await replier(
  877. bot=self,
  878. **{
  879. name: argument
  880. for name, argument in locals().items()
  881. if name in inspect.signature(
  882. replier
  883. ).parameters
  884. }
  885. )
  886. if reply:
  887. if type(reply) is str:
  888. reply = dict(text=reply)
  889. try:
  890. return await self.reply(update=update, **reply)
  891. except Exception as e:
  892. logging.error(
  893. f"Failed to handle voice message:\n{e}",
  894. exc_info=True
  895. )
  896. return
  897. async def video_note_message_handler(self, update, user_record, language=None):
  898. """Handle `video_note` message update."""
  899. logging.info(
  900. "A video_note message update was received, "
  901. "but this handler does nothing yet."
  902. )
  903. async def contact_message_handler(self, update, user_record, language=None):
  904. """Handle `contact` message update."""
  905. return await self.general_handler(update=update,
  906. user_record=user_record,
  907. language=language,
  908. update_type='contact')
  909. async def general_handler(self, update: dict, user_record: OrderedDict,
  910. language: str, update_type: str):
  911. replier, reply = None, None
  912. user_id = update['from']['id'] if 'from' in update else None
  913. if update_type not in self.individual_handlers:
  914. self.individual_handlers[update_type] = dict()
  915. if update_type not in self.handlers:
  916. self.handlers[update_type] = OrderedDict()
  917. if user_id in self.individual_handlers[update_type]:
  918. replier = self.individual_handlers[update_type][user_id]
  919. del self.individual_handlers[update_type][user_id]
  920. else:
  921. for check_function, handler in self.handlers[update_type].items():
  922. if check_function(update):
  923. replier = handler['handler']
  924. break
  925. if replier:
  926. reply = await replier(
  927. bot=self,
  928. **{
  929. name: argument
  930. for name, argument in locals().items()
  931. if name in inspect.signature(
  932. replier
  933. ).parameters
  934. }
  935. )
  936. if reply:
  937. if type(reply) is str:
  938. reply = dict(text=reply)
  939. try:
  940. return await self.reply(update=update, **reply)
  941. except Exception as e:
  942. logging.error(
  943. f"Failed to handle document:\n{e}",
  944. exc_info=True
  945. )
  946. return
  947. async def location_message_handler(self, update, user_record, language=None):
  948. """Handle `location` message update."""
  949. replier, reply = None, None
  950. user_id = update['from']['id'] if 'from' in update else None
  951. if user_id in self.individual_location_handlers:
  952. replier = self.individual_location_handlers[user_id]
  953. del self.individual_location_handlers[user_id]
  954. if replier:
  955. reply = await replier(
  956. bot=self,
  957. **{
  958. name: argument
  959. for name, argument in locals().items()
  960. if name in inspect.signature(
  961. replier
  962. ).parameters
  963. }
  964. )
  965. if reply:
  966. if type(reply) is str:
  967. reply = dict(text=reply)
  968. try:
  969. return await self.reply(update=update, **reply)
  970. except Exception as e:
  971. logging.error(
  972. f"Failed to handle location message:\n{e}",
  973. exc_info=True
  974. )
  975. return
  976. async def venue_message_handler(self, update, user_record, language=None):
  977. """Handle `venue` message update."""
  978. logging.info(
  979. "A venue message update was received, "
  980. "but this handler does nothing yet."
  981. )
  982. async def poll_message_handler(self, update, user_record, language=None):
  983. """Handle `poll` message update."""
  984. logging.info(
  985. "A poll message update was received, "
  986. "but this handler does nothing yet."
  987. )
  988. async def new_chat_members_message_handler(self, update, user_record, language=None):
  989. """Handle `new_chat_members` message update."""
  990. logging.info(
  991. "A new_chat_members message update was received, "
  992. "but this handler does nothing yet."
  993. )
  994. async def left_chat_member_message_handler(self, update, user_record, language=None):
  995. """Handle `left_chat_member` message update."""
  996. logging.info(
  997. "A left_chat_member message update was received, "
  998. "but this handler does nothing yet."
  999. )
  1000. async def new_chat_title_message_handler(self, update, user_record, language=None):
  1001. """Handle `new_chat_title` message update."""
  1002. logging.info(
  1003. "A new_chat_title message update was received, "
  1004. "but this handler does nothing yet."
  1005. )
  1006. async def new_chat_photo_message_handler(self, update, user_record, language=None):
  1007. """Handle `new_chat_photo` message update."""
  1008. logging.info(
  1009. "A new_chat_photo message update was received, "
  1010. "but this handler does nothing yet."
  1011. )
  1012. async def delete_chat_photo_message_handler(self, update, user_record, language=None):
  1013. """Handle `delete_chat_photo` message update."""
  1014. logging.info(
  1015. "A delete_chat_photo message update was received, "
  1016. "but this handler does nothing yet."
  1017. )
  1018. async def group_chat_created_message_handler(self, update, user_record, language=None):
  1019. """Handle `group_chat_created` message update."""
  1020. logging.info(
  1021. "A group_chat_created message update was received, "
  1022. "but this handler does nothing yet."
  1023. )
  1024. async def supergroup_chat_created_message_handler(self, update,
  1025. user_record):
  1026. """Handle `supergroup_chat_created` message update."""
  1027. logging.info(
  1028. "A supergroup_chat_created message update was received, "
  1029. "but this handler does nothing yet."
  1030. )
  1031. async def channel_chat_created_message_handler(self, update, user_record, language=None):
  1032. """Handle `channel_chat_created` message update."""
  1033. logging.info(
  1034. "A channel_chat_created message update was received, "
  1035. "but this handler does nothing yet."
  1036. )
  1037. async def migrate_to_chat_id_message_handler(self, update, user_record, language=None):
  1038. """Handle `migrate_to_chat_id` message update."""
  1039. logging.info(
  1040. "A migrate_to_chat_id message update was received, "
  1041. "but this handler does nothing yet."
  1042. )
  1043. async def migrate_from_chat_id_message_handler(self, update, user_record, language=None):
  1044. """Handle `migrate_from_chat_id` message update."""
  1045. logging.info(
  1046. "A migrate_from_chat_id message update was received, "
  1047. "but this handler does nothing yet."
  1048. )
  1049. async def pinned_message_message_handler(self, update, user_record, language=None):
  1050. """Handle `pinned_message` message update."""
  1051. logging.info(
  1052. "A pinned_message message update was received, "
  1053. "but this handler does nothing yet."
  1054. )
  1055. async def invoice_message_handler(self, update, user_record, language=None):
  1056. """Handle `invoice` message update."""
  1057. logging.info(
  1058. "A invoice message update was received, "
  1059. "but this handler does nothing yet."
  1060. )
  1061. async def successful_payment_message_handler(self, update, user_record, language=None):
  1062. """Handle `successful_payment` message update."""
  1063. logging.info(
  1064. "A successful_payment message update was received, "
  1065. "but this handler does nothing yet."
  1066. )
  1067. async def connected_website_message_handler(self, update, user_record, language=None):
  1068. """Handle `connected_website` message update."""
  1069. logging.info(
  1070. "A connected_website message update was received, "
  1071. "but this handler does nothing yet."
  1072. )
  1073. async def passport_data_message_handler(self, update, user_record, language=None):
  1074. """Handle `passport_data` message update."""
  1075. logging.info(
  1076. "A passport_data message update was received, "
  1077. "but this handler does nothing yet."
  1078. )
  1079. async def dice_handler(self, update, user_record, language=None):
  1080. """Handle `dice` message update."""
  1081. logging.info(
  1082. "A dice message update was received, "
  1083. "but this handler does nothing yet."
  1084. )
  1085. # noinspection SpellCheckingInspection
  1086. @staticmethod
  1087. def split_message_text(text, limit=None, parse_mode='HTML'):
  1088. r"""Split text if it hits telegram limits for text messages.
  1089. Split at `\n` if possible.
  1090. Add a `[...]` at the end and beginning of split messages,
  1091. with proper code markdown.
  1092. """
  1093. if parse_mode == 'HTML':
  1094. text = escape_html_chars(text)
  1095. tags = (
  1096. ('`', '`')
  1097. if parse_mode == 'Markdown'
  1098. else ('<code>', '</code>')
  1099. if parse_mode.lower() == 'html'
  1100. else ('', '')
  1101. )
  1102. if limit is None:
  1103. limit = Bot.TELEGRAM_MESSAGES_MAX_LEN - 100
  1104. # Example text: "lines\nin\nreversed\order"
  1105. text = text.split("\n")[::-1] # ['order', 'reversed', 'in', 'lines']
  1106. text_part_number = 0
  1107. while len(text) > 0:
  1108. temp = []
  1109. text_part_number += 1
  1110. while (
  1111. len(text) > 0
  1112. and len(
  1113. "\n".join(temp + [text[-1]])
  1114. ) < limit
  1115. ):
  1116. # Append lines of `text` in order (`.pop` returns the last
  1117. # line in text) until the addition of the next line would hit
  1118. # the `limit`.
  1119. temp.append(text.pop())
  1120. # If graceful split failed (last line was longer than limit)
  1121. if len(temp) == 0:
  1122. # Force split last line
  1123. temp.append(text[-1][:limit])
  1124. text[-1] = text[-1][limit:]
  1125. text_chunk = "\n".join(temp) # Re-join this group of lines
  1126. prefix, suffix = '', ''
  1127. is_last = len(text) == 0
  1128. if text_part_number > 1:
  1129. prefix = f"{tags[0]}[...]{tags[1]}\n"
  1130. if not is_last:
  1131. suffix = f"\n{tags[0]}[...]{tags[1]}"
  1132. yield (prefix + text_chunk + suffix), is_last
  1133. return
  1134. async def reply(self, update=None, *args, **kwargs):
  1135. """Reply to `update` with proper method according to `kwargs`."""
  1136. method = None
  1137. if 'text' in kwargs:
  1138. if 'message_id' in kwargs:
  1139. method = self.edit_message_text
  1140. else:
  1141. method = self.send_message
  1142. elif 'photo' in kwargs:
  1143. method = self.send_photo
  1144. elif 'audio' in kwargs:
  1145. method = self.send_audio
  1146. elif 'voice' in kwargs:
  1147. method = self.send_voice
  1148. if method is not None:
  1149. return await method(update=update, *args, **kwargs)
  1150. raise Exception("Unsupported keyword arguments for `Bot().reply`.")
  1151. async def send_message(self, chat_id: Union[int, str] = None,
  1152. text: str = None,
  1153. entities: List[dict] = None,
  1154. parse_mode: str = 'HTML',
  1155. disable_web_page_preview: bool = None,
  1156. disable_notification: bool = None,
  1157. reply_to_message_id: int = None,
  1158. allow_sending_without_reply: bool = None,
  1159. reply_markup=None,
  1160. update: dict = None,
  1161. reply_to_update: bool = False,
  1162. send_default_keyboard: bool = True,
  1163. user_record: OrderedDict = None):
  1164. """Send text via message(s).
  1165. This method wraps lower-level `TelegramBot.sendMessage` method.
  1166. Pass an `update` to extract `chat_id` and `message_id` from it.
  1167. Set `reply_to_update` = True to reply to `update['message_id']`.
  1168. Set `send_default_keyboard` = False to avoid sending default keyboard
  1169. as reply_markup (only those messages can be edited, which were
  1170. sent with no reply markup or with an inline keyboard).
  1171. """
  1172. sent_message_update = None
  1173. if update is None:
  1174. update = dict()
  1175. if 'message' in update:
  1176. update = update['message']
  1177. if chat_id is None and 'chat' in update:
  1178. chat_id = self.get_chat_id(update)
  1179. if user_record is None:
  1180. user_record = self.db['users'].find_one(telegram_id=chat_id)
  1181. if reply_to_update and 'message_id' in update:
  1182. reply_to_message_id = update['message_id']
  1183. if (
  1184. send_default_keyboard
  1185. and reply_markup is None
  1186. and type(chat_id) is int
  1187. and chat_id > 0
  1188. and text != self.authorization_denied_message
  1189. ):
  1190. reply_markup = self.get_keyboard(
  1191. update=update,
  1192. telegram_id=chat_id
  1193. )
  1194. if not text:
  1195. return
  1196. parse_mode = str(parse_mode)
  1197. if isinstance(text, dict):
  1198. text = self.get_message(
  1199. update=update,
  1200. user_record=user_record,
  1201. messages=text
  1202. )
  1203. if len(text) > self.max_message_length:
  1204. message_file = io.StringIO(text)
  1205. message_file.name = self.get_message(
  1206. 'davtelepot', 'long_message', 'file_name',
  1207. update=update,
  1208. user_record=user_record,
  1209. )
  1210. return await self.send_document(
  1211. chat_id=chat_id,
  1212. document=message_file,
  1213. caption=self.get_message(
  1214. 'davtelepot', 'long_message', 'caption',
  1215. update=update,
  1216. user_record=user_record,
  1217. ),
  1218. use_stored_file_id=False,
  1219. parse_mode='HTML'
  1220. )
  1221. text_chunks = self.split_message_text(
  1222. text=text,
  1223. limit=self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 100,
  1224. parse_mode=parse_mode
  1225. )
  1226. for text_chunk, is_last in text_chunks:
  1227. _reply_markup = (reply_markup if is_last else None)
  1228. sent_message_update = await self.sendMessage(
  1229. chat_id=chat_id,
  1230. text=text_chunk,
  1231. parse_mode=parse_mode,
  1232. entities=entities,
  1233. disable_web_page_preview=disable_web_page_preview,
  1234. disable_notification=disable_notification,
  1235. reply_to_message_id=reply_to_message_id,
  1236. allow_sending_without_reply=allow_sending_without_reply,
  1237. reply_markup=_reply_markup
  1238. )
  1239. return sent_message_update
  1240. async def send_disposable_message(self, *args, interval=60, **kwargs):
  1241. sent_message = await self.reply(*args, **kwargs)
  1242. if sent_message is None:
  1243. return
  1244. task = self.delete_message(update=sent_message)
  1245. self.final_tasks.append(task)
  1246. await asyncio.sleep(interval)
  1247. await task
  1248. if task in self.final_tasks:
  1249. self.final_tasks.remove(task)
  1250. return
  1251. async def edit_message_text(self, text: str,
  1252. chat_id: Union[int, str] = None,
  1253. message_id: int = None,
  1254. inline_message_id: str = None,
  1255. parse_mode: str = 'HTML',
  1256. entities: List[dict] = None,
  1257. disable_web_page_preview: bool = None,
  1258. allow_sending_without_reply: bool = None,
  1259. reply_markup=None,
  1260. update: dict = None):
  1261. """Edit message text, sending new messages if necessary.
  1262. This method wraps lower-level `TelegramBot.editMessageText` method.
  1263. Pass an `update` to extract a message identifier from it.
  1264. """
  1265. updates = []
  1266. edited_message = None
  1267. if update is not None:
  1268. message_identifier = self.get_message_identifier(update)
  1269. if 'chat_id' in message_identifier:
  1270. chat_id = message_identifier['chat_id']
  1271. message_id = message_identifier['message_id']
  1272. if 'inline_message_id' in message_identifier:
  1273. inline_message_id = message_identifier['inline_message_id']
  1274. if isinstance(text, dict):
  1275. user_record = self.db['users'].find_one(telegram_id=chat_id)
  1276. text = self.get_message(
  1277. update=update,
  1278. user_record=user_record,
  1279. messages=text
  1280. )
  1281. for i, (text_chunk, is_last) in enumerate(
  1282. self.split_message_text(
  1283. text=text,
  1284. limit=self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 200,
  1285. parse_mode=parse_mode
  1286. )
  1287. ):
  1288. if i == 0:
  1289. edited_message = await self.editMessageText(
  1290. text=text_chunk,
  1291. chat_id=chat_id,
  1292. message_id=message_id,
  1293. inline_message_id=inline_message_id,
  1294. parse_mode=parse_mode,
  1295. entities=entities,
  1296. disable_web_page_preview=disable_web_page_preview,
  1297. reply_markup=(reply_markup if is_last else None)
  1298. )
  1299. if chat_id is None:
  1300. # Cannot send messages without a chat_id
  1301. # Inline keyboards attached to inline query results may be
  1302. # in chats the bot cannot reach.
  1303. break
  1304. updates = [update]
  1305. else:
  1306. updates.append(
  1307. await self.send_message(
  1308. text=text_chunk,
  1309. chat_id=chat_id,
  1310. parse_mode=parse_mode,
  1311. entities=entities,
  1312. disable_web_page_preview=disable_web_page_preview,
  1313. allow_sending_without_reply=allow_sending_without_reply,
  1314. reply_markup=(reply_markup if is_last else None),
  1315. update=updates[-1],
  1316. reply_to_update=True,
  1317. send_default_keyboard=False
  1318. )
  1319. )
  1320. return edited_message
  1321. async def edit_message_media(self,
  1322. chat_id=None, message_id=None,
  1323. inline_message_id=None,
  1324. media=None,
  1325. reply_markup=None,
  1326. caption=None,
  1327. parse_mode=None,
  1328. photo=None,
  1329. update=None):
  1330. if update is not None:
  1331. message_identifier = self.get_message_identifier(update)
  1332. if 'chat_id' in message_identifier:
  1333. chat_id = message_identifier['chat_id']
  1334. message_id = message_identifier['message_id']
  1335. if 'inline_message_id' in message_identifier:
  1336. inline_message_id = message_identifier['inline_message_id']
  1337. if media is None:
  1338. media = {}
  1339. if caption is not None:
  1340. media['caption'] = caption
  1341. if parse_mode is not None:
  1342. media['parse_mode'] = parse_mode
  1343. if photo is not None:
  1344. media['type'] = 'photo'
  1345. media['media'] = photo
  1346. return await self.editMessageMedia(chat_id=chat_id,
  1347. message_id=message_id,
  1348. inline_message_id=inline_message_id,
  1349. media=media,
  1350. reply_markup=reply_markup)
  1351. async def forward_message(self, chat_id, update=None, from_chat_id=None,
  1352. message_id=None, disable_notification=False):
  1353. """Forward message from `from_chat_id` to `chat_id`.
  1354. Set `disable_notification` to True to avoid disturbing recipient.
  1355. Pass the `update` to be forwarded or its identifier (`from_chat_id` and
  1356. `message_id`).
  1357. """
  1358. if from_chat_id is None or message_id is None:
  1359. message_identifier = self.get_message_identifier(update)
  1360. from_chat_id = message_identifier['chat_id']
  1361. message_id = message_identifier['message_id']
  1362. return await self.forwardMessage(
  1363. chat_id=chat_id,
  1364. from_chat_id=from_chat_id,
  1365. message_id=message_id,
  1366. disable_notification=disable_notification,
  1367. )
  1368. async def delete_message(self, update=None, chat_id=None,
  1369. message_id=None):
  1370. """Delete given update with given *args and **kwargs.
  1371. Please note, that a bot can delete only messages sent by itself
  1372. or sent in a group which it is administrator of.
  1373. """
  1374. if update is None:
  1375. update = dict()
  1376. if chat_id is None or message_id is None:
  1377. message_identifier = self.get_message_identifier(update)
  1378. else:
  1379. message_identifier = dict(
  1380. chat_id=chat_id,
  1381. message_id=message_id
  1382. )
  1383. return await self.deleteMessage(
  1384. **message_identifier
  1385. )
  1386. async def send_photo(self, photo, chat_id: Union[int, str] = None,
  1387. caption: str = None,
  1388. parse_mode: str = None,
  1389. caption_entities: List[dict] = None,
  1390. disable_notification: bool = None,
  1391. reply_to_message_id: int = None,
  1392. allow_sending_without_reply: bool = None,
  1393. reply_markup=None,
  1394. update: dict = None,
  1395. reply_to_update: bool = False,
  1396. send_default_keyboard: bool = True,
  1397. use_stored_file_id: bool = True):
  1398. """Send photos.
  1399. This method wraps lower-level `TelegramBot.sendPhoto` method.
  1400. Pass an `update` to extract `chat_id` and `message_id` from it.
  1401. Set `reply_to_update` = True to reply to `update['message_id']`.
  1402. Set `send_default_keyboard` = False to avoid sending default keyboard
  1403. as reply_markup (only those messages can be edited, which were
  1404. sent with no reply markup or with an inline keyboard).
  1405. If photo was already sent by this bot and `use_stored_file_id` is set
  1406. to True, use file_id (it is faster and recommended).
  1407. """
  1408. already_sent = False
  1409. photo_path = None
  1410. if update is None:
  1411. update = dict()
  1412. if 'message' in update:
  1413. update = update['message']
  1414. if chat_id is None and 'chat' in update:
  1415. chat_id = self.get_chat_id(update)
  1416. if reply_to_update and 'message_id' in update:
  1417. reply_to_message_id = update['message_id']
  1418. if (
  1419. send_default_keyboard
  1420. and reply_markup is None
  1421. and type(chat_id) is int
  1422. and chat_id > 0
  1423. and caption != self.authorization_denied_message
  1424. ):
  1425. reply_markup = self.get_keyboard(
  1426. update=update,
  1427. telegram_id=chat_id
  1428. )
  1429. if type(photo) is str:
  1430. photo_path = photo
  1431. with self.db as db:
  1432. already_sent = db['sent_pictures'].find_one(
  1433. path=photo_path,
  1434. errors=False
  1435. )
  1436. if already_sent and use_stored_file_id:
  1437. photo = already_sent['file_id']
  1438. already_sent = True
  1439. else:
  1440. already_sent = False
  1441. if not any(
  1442. [
  1443. photo.startswith(url_starter)
  1444. for url_starter in ('http', 'www',)
  1445. ]
  1446. ): # If `photo` is not a url but a local file path
  1447. try:
  1448. with io.BytesIO() as buffered_picture:
  1449. with open(
  1450. os.path.join(self.path, photo_path),
  1451. 'rb' # Read bytes
  1452. ) as photo_file:
  1453. buffered_picture.write(photo_file.read())
  1454. photo = buffered_picture.getvalue()
  1455. except FileNotFoundError:
  1456. photo = None
  1457. else:
  1458. use_stored_file_id = False
  1459. if photo is None:
  1460. logging.error("Photo is None, `send_photo` returning...")
  1461. return
  1462. sent_update = None
  1463. try:
  1464. sent_update = await self.sendPhoto(
  1465. chat_id=chat_id,
  1466. photo=photo,
  1467. caption=caption,
  1468. parse_mode=parse_mode,
  1469. caption_entities=caption_entities,
  1470. disable_notification=disable_notification,
  1471. reply_to_message_id=reply_to_message_id,
  1472. allow_sending_without_reply=allow_sending_without_reply,
  1473. reply_markup=reply_markup
  1474. )
  1475. if isinstance(sent_update, Exception):
  1476. raise Exception("sendPhoto API call failed!")
  1477. except Exception as e:
  1478. logging.error(f"Error sending photo\n{e}")
  1479. if already_sent:
  1480. with self.db as db:
  1481. db['sent_pictures'].update(
  1482. dict(
  1483. path=photo_path,
  1484. errors=True
  1485. ),
  1486. ['path']
  1487. )
  1488. if (
  1489. type(sent_update) is dict
  1490. and 'photo' in sent_update
  1491. and len(sent_update['photo']) > 0
  1492. and 'file_id' in sent_update['photo'][0]
  1493. and (not already_sent)
  1494. and use_stored_file_id
  1495. ):
  1496. with self.db as db:
  1497. db['sent_pictures'].insert(
  1498. dict(
  1499. path=photo_path,
  1500. file_id=sent_update['photo'][0]['file_id'],
  1501. errors=False
  1502. )
  1503. )
  1504. return sent_update
  1505. async def send_audio(self, chat_id: Union[int, str], audio,
  1506. caption: str = None,
  1507. parse_mode: str = None,
  1508. caption_entities: List[dict] = None,
  1509. duration: int = None,
  1510. performer: str = None,
  1511. title: str = None,
  1512. thumb=None,
  1513. disable_notification: bool = None,
  1514. reply_to_message_id: int = None,
  1515. allow_sending_without_reply: bool = None,
  1516. reply_markup=None,
  1517. update: dict = None,
  1518. reply_to_update: bool = False,
  1519. send_default_keyboard: bool = True,
  1520. use_stored_file_id: bool = True):
  1521. """Send audio files.
  1522. This method wraps lower-level `TelegramBot.sendAudio` method.
  1523. Pass an `update` to extract `chat_id` and `message_id` from it.
  1524. Set `reply_to_update` = True to reply to `update['message_id']`.
  1525. Set `send_default_keyboard` = False to avoid sending default keyboard
  1526. as reply_markup (only those messages can be edited, which were
  1527. sent with no reply markup or with an inline keyboard).
  1528. If photo was already sent by this bot and `use_stored_file_id` is set
  1529. to True, use file_id (it is faster and recommended).
  1530. """
  1531. already_sent = False
  1532. audio_path = None
  1533. if update is None:
  1534. update = dict()
  1535. if 'message' in update:
  1536. update = update['message']
  1537. if chat_id is None and 'chat' in update:
  1538. chat_id = self.get_chat_id(update)
  1539. if reply_to_update and 'message_id' in update:
  1540. reply_to_message_id = update['message_id']
  1541. if (
  1542. send_default_keyboard
  1543. and reply_markup is None
  1544. and type(chat_id) is int
  1545. and chat_id > 0
  1546. and caption != self.authorization_denied_message
  1547. ):
  1548. reply_markup = self.get_keyboard(
  1549. update=update,
  1550. telegram_id=chat_id
  1551. )
  1552. if type(audio) is str:
  1553. audio_path = audio
  1554. with self.db as db:
  1555. already_sent = db['sent_audio_files'].find_one(
  1556. path=audio_path,
  1557. errors=False
  1558. )
  1559. if already_sent and use_stored_file_id:
  1560. audio = already_sent['file_id']
  1561. already_sent = True
  1562. else:
  1563. already_sent = False
  1564. if not any(
  1565. [
  1566. audio.startswith(url_starter)
  1567. for url_starter in ('http', 'www',)
  1568. ]
  1569. ): # If `audio` is not a url but a local file path
  1570. try:
  1571. with io.BytesIO() as buffered_picture:
  1572. with open(
  1573. os.path.join(self.path, audio_path),
  1574. 'rb' # Read bytes
  1575. ) as audio_file:
  1576. buffered_picture.write(audio_file.read())
  1577. audio = buffered_picture.getvalue()
  1578. except FileNotFoundError:
  1579. audio = None
  1580. else:
  1581. use_stored_file_id = False
  1582. if audio is None:
  1583. logging.error("Audio is None, `send_audio` returning...")
  1584. return
  1585. sent_update = None
  1586. try:
  1587. sent_update = await self.sendAudio(
  1588. chat_id=chat_id,
  1589. audio=audio,
  1590. caption=caption,
  1591. parse_mode=parse_mode,
  1592. caption_entities=caption_entities,
  1593. duration=duration,
  1594. performer=performer,
  1595. title=title,
  1596. thumb=thumb,
  1597. disable_notification=disable_notification,
  1598. reply_to_message_id=reply_to_message_id,
  1599. allow_sending_without_reply=allow_sending_without_reply,
  1600. reply_markup=reply_markup
  1601. )
  1602. if isinstance(sent_update, Exception):
  1603. raise Exception("sendAudio API call failed!")
  1604. except Exception as e:
  1605. logging.error(f"Error sending audio\n{e}")
  1606. if already_sent:
  1607. with self.db as db:
  1608. db['sent_audio_files'].update(
  1609. dict(
  1610. path=audio_path,
  1611. errors=True
  1612. ),
  1613. ['path']
  1614. )
  1615. if (
  1616. type(sent_update) is dict
  1617. and 'audio' in sent_update
  1618. and 'file_id' in sent_update['audio']
  1619. and (not already_sent)
  1620. and use_stored_file_id
  1621. ):
  1622. with self.db as db:
  1623. db['sent_audio_files'].insert(
  1624. dict(
  1625. path=audio_path,
  1626. file_id=sent_update['audio']['file_id'],
  1627. errors=False
  1628. )
  1629. )
  1630. return sent_update
  1631. async def send_voice(self, chat_id: Union[int, str], voice,
  1632. caption: str = None,
  1633. parse_mode: str = None,
  1634. caption_entities: List[dict] = None,
  1635. duration: int = None,
  1636. disable_notification: bool = None,
  1637. reply_to_message_id: int = None,
  1638. allow_sending_without_reply: bool = None,
  1639. reply_markup=None,
  1640. update: dict = None,
  1641. reply_to_update: bool = False,
  1642. send_default_keyboard: bool = True,
  1643. use_stored_file_id: bool = True):
  1644. """Send voice messages.
  1645. This method wraps lower-level `TelegramBot.sendVoice` method.
  1646. Pass an `update` to extract `chat_id` and `message_id` from it.
  1647. Set `reply_to_update` = True to reply to `update['message_id']`.
  1648. Set `send_default_keyboard` = False to avoid sending default keyboard
  1649. as reply_markup (only those messages can be edited, which were
  1650. sent with no reply markup or with an inline keyboard).
  1651. If photo was already sent by this bot and `use_stored_file_id` is set
  1652. to True, use file_id (it is faster and recommended).
  1653. """
  1654. already_sent = False
  1655. voice_path = None
  1656. if update is None:
  1657. update = dict()
  1658. if 'message' in update:
  1659. update = update['message']
  1660. if chat_id is None and 'chat' in update:
  1661. chat_id = self.get_chat_id(update)
  1662. if reply_to_update and 'message_id' in update:
  1663. reply_to_message_id = update['message_id']
  1664. if (
  1665. send_default_keyboard
  1666. and reply_markup is None
  1667. and type(chat_id) is int
  1668. and chat_id > 0
  1669. and caption != self.authorization_denied_message
  1670. ):
  1671. reply_markup = self.get_keyboard(
  1672. update=update,
  1673. telegram_id=chat_id
  1674. )
  1675. if type(voice) is str:
  1676. voice_path = voice
  1677. with self.db as db:
  1678. already_sent = db['sent_voice_messages'].find_one(
  1679. path=voice_path,
  1680. errors=False
  1681. )
  1682. if already_sent and use_stored_file_id:
  1683. voice = already_sent['file_id']
  1684. already_sent = True
  1685. else:
  1686. already_sent = False
  1687. if not any(
  1688. [
  1689. voice.startswith(url_starter)
  1690. for url_starter in ('http', 'www',)
  1691. ]
  1692. ): # If `voice` is not a url but a local file path
  1693. try:
  1694. with io.BytesIO() as buffered_picture:
  1695. with open(
  1696. os.path.join(self.path, voice_path),
  1697. 'rb' # Read bytes
  1698. ) as voice_file:
  1699. buffered_picture.write(voice_file.read())
  1700. voice = buffered_picture.getvalue()
  1701. except FileNotFoundError:
  1702. voice = None
  1703. else:
  1704. use_stored_file_id = False
  1705. if voice is None:
  1706. logging.error("Voice is None, `send_voice` returning...")
  1707. return
  1708. sent_update = None
  1709. try:
  1710. sent_update = await self.sendVoice(
  1711. chat_id=chat_id,
  1712. voice=voice,
  1713. caption=caption,
  1714. parse_mode=parse_mode,
  1715. caption_entities=caption_entities,
  1716. duration=duration,
  1717. disable_notification=disable_notification,
  1718. reply_to_message_id=reply_to_message_id,
  1719. allow_sending_without_reply=allow_sending_without_reply,
  1720. reply_markup=reply_markup
  1721. )
  1722. if isinstance(sent_update, Exception):
  1723. raise Exception("sendVoice API call failed!")
  1724. except Exception as e:
  1725. logging.error(f"Error sending voice\n{e}")
  1726. if already_sent:
  1727. with self.db as db:
  1728. db['sent_voice_messages'].update(
  1729. dict(
  1730. path=voice_path,
  1731. errors=True
  1732. ),
  1733. ['path']
  1734. )
  1735. if (
  1736. type(sent_update) is dict
  1737. and 'voice' in sent_update
  1738. and 'file_id' in sent_update['voice']
  1739. and (not already_sent)
  1740. and use_stored_file_id
  1741. ):
  1742. with self.db as db:
  1743. db['sent_voice_messages'].insert(
  1744. dict(
  1745. path=voice_path,
  1746. file_id=sent_update['voice']['file_id'],
  1747. errors=False
  1748. )
  1749. )
  1750. return sent_update
  1751. async def send_document(self, chat_id: Union[int, str] = None, document=None,
  1752. thumb=None,
  1753. caption: str = None,
  1754. parse_mode: str = None,
  1755. caption_entities: List[dict] = None,
  1756. disable_content_type_detection: bool = None,
  1757. disable_notification: bool = None,
  1758. reply_to_message_id: int = None,
  1759. allow_sending_without_reply: bool = None,
  1760. reply_markup=None,
  1761. document_path: str = None,
  1762. document_name: str = None,
  1763. update: dict = None,
  1764. reply_to_update: bool = False,
  1765. send_default_keyboard: bool = True,
  1766. use_stored_file_id: bool = False):
  1767. """Send a document.
  1768. This method wraps lower-level `TelegramBot.sendDocument` method.
  1769. Pass an `update` to extract `chat_id` and `message_id` from it.
  1770. Set `reply_to_update` = True to reply to `update['message_id']`.
  1771. Set `send_default_keyboard` = False to avoid sending default keyboard
  1772. as reply_markup (only those messages can be edited, which were
  1773. sent with no reply markup or with an inline keyboard).
  1774. If document was already sent by this bot and `use_stored_file_id` is
  1775. set to True, use file_id (it is faster and recommended).
  1776. `document_path` may contain `{path}`: it will be replaced by
  1777. `self.path`.
  1778. `document_name` displayed to Telegram may differ from actual document
  1779. name if this parameter is set.
  1780. """
  1781. already_sent = False
  1782. if update is None:
  1783. update = dict()
  1784. # This buffered_file trick is necessary for two reasons
  1785. # 1. File operations must be blocking, but sendDocument is a coroutine
  1786. # 2. A `with` statement is not possible here
  1787. if 'message' in update:
  1788. update = update['message']
  1789. if chat_id is None and 'chat' in update:
  1790. chat_id = self.get_chat_id(update)
  1791. if chat_id is None:
  1792. logging.error("Attempt to send document without providing a chat_id")
  1793. return
  1794. if reply_to_update and 'message_id' in update:
  1795. reply_to_message_id = update['message_id']
  1796. if chat_id > 0:
  1797. user_record = self.db['users'].find_one(telegram_id=chat_id)
  1798. language = self.get_language(update=update, user_record=user_record)
  1799. if (
  1800. send_default_keyboard
  1801. and reply_markup is None
  1802. and type(chat_id) is int
  1803. and caption != self.authorization_denied_message
  1804. ):
  1805. reply_markup = self.get_keyboard(
  1806. user_record=user_record
  1807. )
  1808. else:
  1809. language = self.default_language
  1810. if document_path is not None:
  1811. with self.db as db:
  1812. already_sent = db['sent_documents'].find_one(
  1813. path=document_path,
  1814. errors=False
  1815. )
  1816. if already_sent and use_stored_file_id:
  1817. document = already_sent['file_id']
  1818. already_sent = True
  1819. else:
  1820. already_sent = False
  1821. if not any(
  1822. [
  1823. document_path.startswith(url_starter)
  1824. for url_starter in ('http', 'www',)
  1825. ]
  1826. ): # If `document_path` is not a url but a local file path
  1827. try:
  1828. with open(
  1829. document_path.format(
  1830. path=self.path
  1831. ),
  1832. 'rb' # Read bytes
  1833. ) as file_:
  1834. file_size = os.fstat(file_.fileno()).st_size
  1835. document_chunks = (
  1836. int(
  1837. file_size
  1838. / self.documents_max_dimension
  1839. ) + 1
  1840. )
  1841. original_document_name = (
  1842. document_name
  1843. or file_.name
  1844. or 'Document'
  1845. )
  1846. original_caption = caption
  1847. if '/' in original_document_name:
  1848. original_document_name = os.path.basename(
  1849. os.path.abspath(original_document_name)
  1850. )
  1851. for i in range(document_chunks):
  1852. buffered_file = io.BytesIO(
  1853. file_.read(self.documents_max_dimension)
  1854. )
  1855. if document_chunks > 1:
  1856. part = self.get_message(
  1857. 'davtelepot', 'part',
  1858. language=language
  1859. )
  1860. caption = f"{original_caption} - {part} {i + 1}/{document_chunks}"
  1861. buffered_file.name = (
  1862. f"{original_document_name} - "
  1863. f"{part} {i + 1}"
  1864. )
  1865. else:
  1866. buffered_file.name = original_document_name
  1867. sent_document = await self.send_document(
  1868. chat_id=chat_id,
  1869. document=buffered_file,
  1870. thumb=thumb,
  1871. caption=caption,
  1872. parse_mode=parse_mode,
  1873. disable_notification=disable_notification,
  1874. reply_to_message_id=reply_to_message_id,
  1875. reply_markup=reply_markup,
  1876. update=update,
  1877. reply_to_update=reply_to_update,
  1878. send_default_keyboard=send_default_keyboard,
  1879. use_stored_file_id=use_stored_file_id
  1880. )
  1881. return sent_document
  1882. except FileNotFoundError as e:
  1883. if buffered_file:
  1884. buffered_file.close()
  1885. buffered_file = None
  1886. return e
  1887. else:
  1888. use_stored_file_id = False
  1889. if document is None:
  1890. logging.error(
  1891. "`document` is None, `send_document` returning..."
  1892. )
  1893. return Exception("No `document` provided")
  1894. sent_update = None
  1895. try:
  1896. sent_update = await self.sendDocument(
  1897. chat_id=chat_id,
  1898. document=document,
  1899. thumb=thumb,
  1900. caption=caption,
  1901. parse_mode=parse_mode,
  1902. caption_entities=caption_entities,
  1903. disable_content_type_detection=disable_content_type_detection,
  1904. disable_notification=disable_notification,
  1905. reply_to_message_id=reply_to_message_id,
  1906. allow_sending_without_reply=allow_sending_without_reply,
  1907. reply_markup=reply_markup
  1908. )
  1909. if isinstance(sent_update, Exception):
  1910. raise Exception("sendDocument API call failed!")
  1911. except Exception as e:
  1912. logging.error(f"Error sending document\n{e}")
  1913. if already_sent:
  1914. with self.db as db:
  1915. db['sent_documents'].update(
  1916. dict(
  1917. path=document_path,
  1918. errors=True
  1919. ),
  1920. ['path']
  1921. )
  1922. if (
  1923. type(sent_update) is dict
  1924. and 'document' in sent_update
  1925. and 'file_id' in sent_update['document']
  1926. and (not already_sent)
  1927. and use_stored_file_id
  1928. ):
  1929. with self.db as db:
  1930. db['sent_documents'].insert(
  1931. dict(
  1932. path=document_path,
  1933. file_id=sent_update['document']['file_id'],
  1934. errors=False
  1935. )
  1936. )
  1937. return sent_update
  1938. async def download_file(self, file_id,
  1939. file_name=None, path=None):
  1940. """Given a telegram `file_id`, download the related file.
  1941. Telegram may not preserve the original file name and MIME type: the
  1942. file's MIME type and name (if available) should be stored when the
  1943. File object is received.
  1944. """
  1945. file = await self.getFile(file_id=file_id)
  1946. if file is None or isinstance(file, Exception):
  1947. logging.error(f"{file}")
  1948. return
  1949. file_bytes = await async_get(
  1950. url=(
  1951. f"https://api.telegram.org/file/"
  1952. f"bot{self.token}/"
  1953. f"{file['file_path']}"
  1954. ),
  1955. mode='raw'
  1956. )
  1957. path = path or self.path
  1958. while file_name is None:
  1959. file_name = get_secure_key(length=10)
  1960. if os.path.exists(f"{path}/{file_name}"):
  1961. file_name = None
  1962. try:
  1963. with open(f"{path}/{file_name}", 'wb') as local_file:
  1964. local_file.write(file_bytes)
  1965. except Exception as e:
  1966. logging.error(f"File download failed due to {e}")
  1967. return
  1968. def translate_inline_query_answer_result(self, record,
  1969. update=None, user_record=None):
  1970. """Translate title and message text fields of inline query result.
  1971. This method does not alter original `record`. This way, default
  1972. inline query result is kept multilingual although single results
  1973. sent to users are translated.
  1974. """
  1975. result = dict()
  1976. for key, val in record.items():
  1977. if key == 'title' and isinstance(record[key], dict):
  1978. result[key] = self.get_message(
  1979. update=update,
  1980. user_record=user_record,
  1981. messages=record[key]
  1982. )
  1983. elif (
  1984. key == 'input_message_content'
  1985. and isinstance(record[key], dict)
  1986. ):
  1987. result[key] = self.translate_inline_query_answer_result(
  1988. record[key],
  1989. update=update,
  1990. user_record=user_record
  1991. )
  1992. elif key == 'message_text' and isinstance(record[key], dict):
  1993. result[key] = self.get_message(
  1994. update=update,
  1995. user_record=user_record,
  1996. messages=record[key]
  1997. )
  1998. else:
  1999. result[key] = val
  2000. return result
  2001. async def answer_inline_query(self,
  2002. inline_query_id=None,
  2003. results=None,
  2004. cache_time=None,
  2005. is_personal=None,
  2006. next_offset=None,
  2007. switch_pm_text=None,
  2008. switch_pm_parameter=None,
  2009. update=None,
  2010. user_record=None):
  2011. """Answer inline queries.
  2012. This method wraps lower-level `answerInlineQuery` method.
  2013. If `results` is a string, cast it to proper type (list of dicts having
  2014. certain keys). See utilities.make_inline_query_answer for details.
  2015. """
  2016. if results is None:
  2017. results = []
  2018. if (
  2019. inline_query_id is None
  2020. and isinstance(update, dict)
  2021. and 'id' in update
  2022. ):
  2023. inline_query_id = update['id']
  2024. results = [
  2025. self.translate_inline_query_answer_result(record=result,
  2026. update=update,
  2027. user_record=user_record)
  2028. for result in make_inline_query_answer(results)
  2029. ]
  2030. return await self.answerInlineQuery(
  2031. inline_query_id=inline_query_id,
  2032. results=results,
  2033. cache_time=cache_time,
  2034. is_personal=is_personal,
  2035. next_offset=next_offset,
  2036. switch_pm_text=switch_pm_text,
  2037. switch_pm_parameter=switch_pm_parameter,
  2038. )
  2039. @classmethod
  2040. def set_class_maintenance_message(cls, maintenance_message):
  2041. """Set class maintenance message.
  2042. It will be returned if bot is under maintenance, unless and instance
  2043. `_maintenance_message` is set.
  2044. """
  2045. cls._maintenance_message = maintenance_message
  2046. def set_maintenance_message(self, maintenance_message):
  2047. """Set instance maintenance message.
  2048. It will be returned if bot is under maintenance.
  2049. If instance message is None, default class message is used.
  2050. """
  2051. self._maintenance_message = maintenance_message
  2052. def change_maintenance_status(self, maintenance_message=None, status=None):
  2053. """Put the bot under maintenance or end it.
  2054. While in maintenance, bot will reply to users with maintenance_message
  2055. with a few exceptions.
  2056. If status is not set, it is by default the opposite of the current one.
  2057. Optionally, `maintenance_message` may be set.
  2058. """
  2059. if status is None:
  2060. status = not self.under_maintenance
  2061. assert type(status) is bool, "status must be a boolean value!"
  2062. self._under_maintenance = status
  2063. if maintenance_message:
  2064. self.set_maintenance_message(maintenance_message)
  2065. return self._under_maintenance # Return new status
  2066. def is_allowed_during_maintenance(self, update):
  2067. """Return True if update is allowed during maintenance.
  2068. An update is allowed if any of the criteria in
  2069. `self.allowed_during_maintenance` returns True called on it.
  2070. """
  2071. for criterion in self.allowed_during_maintenance:
  2072. if criterion(update):
  2073. return True
  2074. return False
  2075. def allow_during_maintenance(self, criterion):
  2076. """Add a criterion to allow certain updates during maintenance.
  2077. `criterion` must be a function taking a Telegram `update` dictionary
  2078. and returning a boolean.
  2079. ```# Example of criterion
  2080. def allow_text_messages(update):
  2081. if 'message' in update and 'text' in update['message']:
  2082. return True
  2083. return False
  2084. ```
  2085. """
  2086. self._allowed_during_maintenance.append(criterion)
  2087. async def handle_update_during_maintenance(self, update, user_record=None, language=None):
  2088. """Handle an update while bot is under maintenance.
  2089. Handle all types of updates.
  2090. """
  2091. if (
  2092. 'message' in update
  2093. and 'chat' in update['message']
  2094. and update['message']['chat']['id'] > 0
  2095. ):
  2096. return await self.send_message(
  2097. text=self.maintenance_message,
  2098. update=update['message'],
  2099. reply_to_update=True
  2100. )
  2101. elif 'callback_query' in update:
  2102. await self.answerCallbackQuery(
  2103. callback_query_id=update['id'],
  2104. text=remove_html_tags(self.maintenance_message[:45])
  2105. )
  2106. elif 'inline_query' in update:
  2107. await self.answer_inline_query(
  2108. update['inline_query']['id'],
  2109. self.maintenance_message,
  2110. cache_time=30,
  2111. is_personal=False,
  2112. update=update,
  2113. user_record=user_record
  2114. )
  2115. return
  2116. @classmethod
  2117. def set_class_authorization_denied_message(cls, message):
  2118. """Set class authorization denied message.
  2119. It will be returned if user is unauthorized to make a request.
  2120. """
  2121. cls._authorization_denied_message = message
  2122. def set_authorization_denied_message(self, message):
  2123. """Set instance authorization denied message.
  2124. If instance message is None, default class message is used.
  2125. """
  2126. self._authorization_denied_message = message
  2127. def set_authorization_function(self, authorization_function):
  2128. """Set a custom authorization_function.
  2129. It should evaluate True if user is authorized to perform a specific
  2130. action and False otherwise.
  2131. It should take update and role and return a Boolean.
  2132. Default authorization_function always evaluates True.
  2133. """
  2134. self.authorization_function = authorization_function
  2135. @classmethod
  2136. def set_class_unknown_command_message(cls, unknown_command_message):
  2137. """Set class unknown command message.
  2138. It will be returned if user sends an unknown command in private chat.
  2139. """
  2140. cls._unknown_command_message = unknown_command_message
  2141. def set_unknown_command_message(self, unknown_command_message):
  2142. """Set instance unknown command message.
  2143. It will be returned if user sends an unknown command in private chat.
  2144. If instance message is None, default class message is used.
  2145. """
  2146. self._unknown_command_message = unknown_command_message
  2147. def add_help_section(self, help_section):
  2148. """Add `help_section`."""
  2149. assert (
  2150. isinstance(help_section, dict)
  2151. and 'name' in help_section
  2152. and 'label' in help_section
  2153. and 'description' in help_section
  2154. ), "Invalid help section!"
  2155. if 'authorization_level' not in help_section:
  2156. help_section['authorization_level'] = 'admin'
  2157. self.messages['help_sections'][help_section['name']] = help_section
  2158. def command(self,
  2159. command: Union[str, Dict[str, str]],
  2160. aliases=None,
  2161. reply_keyboard_button=None,
  2162. show_in_keyboard=False, description="",
  2163. help_section=None,
  2164. authorization_level='admin',
  2165. language_labelled_commands: Dict[str, str] = None):
  2166. """Associate a bot command with a custom handler function.
  2167. Decorate command handlers like this:
  2168. ```
  2169. @bot.command('/my_command', ['Button'], True, "My command", 'user')
  2170. async def command_handler(bot, update, user_record, language):
  2171. return "Result"
  2172. ```
  2173. When a message text starts with `/command[@bot_name]`, or with an
  2174. alias, it gets passed to the decorated function.
  2175. `command` is the command name (with or without /). Language-labeled
  2176. commands are supported in the form of {'en': 'command', ...}
  2177. `aliases` is a list of aliases; each will call the command handler
  2178. function; the first alias will appear as button in
  2179. reply keyboard if `reply_keyboard_button` is not set.
  2180. `reply_keyboard_button` is a str or better dict of language-specific
  2181. strings to be shown in default keyboard.
  2182. `show_in_keyboard`, if True, makes a button for this command appear in
  2183. default keyboard.
  2184. `description` can be used to help users understand what `/command`
  2185. does.
  2186. `help_section` is a dict on which the corresponding help section is
  2187. built. It may provide multilanguage support and should be
  2188. structured as follows:
  2189. {
  2190. "label": { # It will be displayed as button label
  2191. 'en': "Label",
  2192. ...
  2193. },
  2194. "name": "section_name",
  2195. # If missing, `authorization_level` is used
  2196. "authorization_level": "everybody",
  2197. "description": {
  2198. 'en': "Description in English",
  2199. ...
  2200. },
  2201. }
  2202. `authorization_level` is the lowest authorization level needed to run
  2203. the command.
  2204. For advanced examples see `davtelepot.helper` or other modules
  2205. (suggestions, administration_tools, ...).
  2206. """
  2207. if language_labelled_commands is None:
  2208. language_labelled_commands = dict()
  2209. language_labelled_commands = {
  2210. key: val.strip('/').lower()
  2211. for key, val in language_labelled_commands.items()
  2212. }
  2213. # Handle language-labelled commands:
  2214. # choose one main command and add others to `aliases`
  2215. if isinstance(command, dict) and len(command) > 0:
  2216. language_labelled_commands = command.copy()
  2217. if 'main' in language_labelled_commands:
  2218. command = language_labelled_commands['main']
  2219. elif self.default_language in language_labelled_commands:
  2220. command = language_labelled_commands[self.default_language]
  2221. else:
  2222. for command in language_labelled_commands.values():
  2223. break
  2224. if aliases is None:
  2225. aliases = []
  2226. if not isinstance(command, str):
  2227. raise TypeError(f'Command `{command}` is not a string')
  2228. if isinstance(reply_keyboard_button, dict):
  2229. for button in reply_keyboard_button.values():
  2230. if button not in aliases:
  2231. aliases.append(button)
  2232. if not isinstance(aliases, list):
  2233. raise TypeError(f'Aliases is not a list: `{aliases}`')
  2234. if not all(
  2235. [
  2236. isinstance(alias, str)
  2237. for alias in aliases
  2238. ]
  2239. ):
  2240. raise TypeError(
  2241. f'Aliases {aliases} is not a list of strings'
  2242. )
  2243. if isinstance(help_section, dict):
  2244. if 'authorization_level' not in help_section:
  2245. help_section['authorization_level'] = authorization_level
  2246. self.add_help_section(help_section)
  2247. command = command.strip('/ ').lower()
  2248. def command_decorator(command_handler):
  2249. async def decorated_command_handler(bot, update, user_record, language=None):
  2250. logging.info(
  2251. f"Command `{command}@{bot.name}` called by "
  2252. f"`{update['from'] if 'from' in update else update['chat']}`"
  2253. )
  2254. if bot.authorization_function(
  2255. update=update,
  2256. user_record=user_record,
  2257. authorization_level=authorization_level
  2258. ):
  2259. # Pass supported arguments from locals() to command_handler
  2260. return await command_handler(
  2261. **{
  2262. name: argument
  2263. for name, argument in locals().items()
  2264. if name in inspect.signature(
  2265. command_handler
  2266. ).parameters
  2267. }
  2268. )
  2269. return dict(text=self.authorization_denied_message)
  2270. self.commands[command] = dict(
  2271. handler=decorated_command_handler,
  2272. description=description,
  2273. authorization_level=authorization_level,
  2274. language_labelled_commands=language_labelled_commands,
  2275. aliases=aliases
  2276. )
  2277. if type(description) is dict:
  2278. self.messages['commands'][command] = dict(
  2279. description=description
  2280. )
  2281. if aliases:
  2282. for alias in aliases:
  2283. if alias.startswith('/'):
  2284. self.commands[alias.strip('/ ').lower()] = dict(
  2285. handler=decorated_command_handler,
  2286. authorization_level=authorization_level
  2287. )
  2288. else:
  2289. self.command_aliases[alias] = decorated_command_handler
  2290. if show_in_keyboard and (aliases or reply_keyboard_button):
  2291. _reply_keyboard_button = reply_keyboard_button or aliases[0]
  2292. self.messages[
  2293. 'reply_keyboard_buttons'][
  2294. command] = _reply_keyboard_button
  2295. self.commands[command][
  2296. 'reply_keyboard_button'] = _reply_keyboard_button
  2297. return command_decorator
  2298. def parser(self, condition, description='', authorization_level='admin'):
  2299. """Define a text message parser.
  2300. Decorate command handlers like this:
  2301. ```
  2302. def custom_criteria(update):
  2303. return 'from' in update
  2304. @bot.parser(custom_criteria, authorization_level='user')
  2305. async def text_parser(bot, update, user_record, language):
  2306. return "Result"
  2307. ```
  2308. If condition evaluates True when run on a message text
  2309. (not starting with '/'), such decorated function gets
  2310. called on update.
  2311. Conditions of parsers are evaluated in order; when one is True,
  2312. others will be skipped.
  2313. `description` provides information about the parser.
  2314. `authorization_level` is the lowest authorization level needed to call
  2315. the parser.
  2316. """
  2317. if not callable(condition):
  2318. raise TypeError(
  2319. f'Condition {condition.__name__} is not a callable'
  2320. )
  2321. def parser_decorator(parser):
  2322. async def decorated_parser(bot, update, user_record, language=None):
  2323. logging.info(
  2324. f"Text message update matching condition "
  2325. f"`{condition.__name__}@{bot.name}` from "
  2326. f"`{update['from'] if 'from' in update else update['chat']}`"
  2327. )
  2328. if bot.authorization_function(
  2329. update=update,
  2330. user_record=user_record,
  2331. authorization_level=authorization_level
  2332. ):
  2333. # Pass supported arguments from locals() to parser
  2334. return await parser(
  2335. **{
  2336. name: arg
  2337. for name, arg in locals().items()
  2338. if name in inspect.signature(parser).parameters
  2339. }
  2340. )
  2341. return dict(text=bot.authorization_denied_message)
  2342. self.text_message_parsers[condition] = dict(
  2343. handler=decorated_parser,
  2344. description=description,
  2345. authorization_level=authorization_level,
  2346. )
  2347. return parser_decorator
  2348. def document_handler(self, condition, description='',
  2349. authorization_level='admin'):
  2350. """Decorator: define a handler for document updates matching `condition`.
  2351. You may provide a description and a minimum authorization level.
  2352. The first handler matching condition is called (other matching handlers
  2353. are ignored).
  2354. """
  2355. if not callable(condition):
  2356. raise TypeError(
  2357. f'Condition {condition.__name__} is not a callable'
  2358. )
  2359. def parser_decorator(parser):
  2360. async def decorated_parser(bot, update, user_record, language=None):
  2361. logging.info(
  2362. f"Document update matching condition "
  2363. f"`{condition.__name__}@{bot.name}` from "
  2364. f"`{update['from'] if 'from' in update else update['chat']}`"
  2365. )
  2366. if bot.authorization_function(
  2367. update=update,
  2368. user_record=user_record,
  2369. authorization_level=authorization_level
  2370. ):
  2371. # Pass supported arguments from locals() to parser
  2372. return await parser(
  2373. **{
  2374. name: arg
  2375. for name, arg in locals().items()
  2376. if name in inspect.signature(parser).parameters
  2377. }
  2378. )
  2379. return dict(text=bot.authorization_denied_message)
  2380. self.document_handlers[condition] = dict(
  2381. handler=decorated_parser,
  2382. description=description,
  2383. authorization_level=authorization_level,
  2384. )
  2385. return parser_decorator
  2386. def handler(self, update_type: str, condition: Callable[[dict], bool],
  2387. description: str = '',
  2388. authorization_level: str = 'admin'):
  2389. """Decorator: define a handler for updates matching `condition`.
  2390. You may provide a description and a minimum authorization level.
  2391. The first handler matching condition is called (other matching handlers
  2392. are ignored).
  2393. """
  2394. if not callable(condition):
  2395. raise TypeError(
  2396. f'Condition {condition.__name__} is not a callable'
  2397. )
  2398. def parser_decorator(parser):
  2399. async def decorated_parser(bot, update, user_record, language=None):
  2400. logging.info(
  2401. f"{update_type} matching condition "
  2402. f"`{condition.__name__}@{bot.name}` from "
  2403. f"`{update['from'] if 'from' in update else update['chat']}`"
  2404. )
  2405. if bot.authorization_function(
  2406. update=update,
  2407. user_record=user_record,
  2408. authorization_level=authorization_level
  2409. ):
  2410. # Pass supported arguments from locals() to parser
  2411. return await parser(
  2412. **{
  2413. name: arg
  2414. for name, arg in locals().items()
  2415. if name in inspect.signature(parser).parameters
  2416. }
  2417. )
  2418. return dict(text=bot.authorization_denied_message)
  2419. if update_type not in self.handlers:
  2420. self.handlers[update_type] = OrderedDict()
  2421. self.handlers[update_type][condition] = dict(
  2422. handler=decorated_parser,
  2423. description=description,
  2424. authorization_level=authorization_level,
  2425. )
  2426. return parser_decorator
  2427. def set_command(self, command, handler, aliases=None,
  2428. reply_keyboard_button=None, show_in_keyboard=False,
  2429. description="",
  2430. authorization_level='admin'):
  2431. """Associate a `command` with a `handler`.
  2432. When a message text starts with `/command[@bot_name]`, or with an
  2433. alias, it gets passed to the decorated function.
  2434. `command` is the command name (with or without /)
  2435. `handler` is the function to be called on update objects.
  2436. `aliases` is a list of aliases; each will call the command handler
  2437. function; the first alias will appear as button in
  2438. reply keyboard if `reply_keyboard_button` is not set.
  2439. `reply_keyboard_button` is a str or better dict of language-specific
  2440. strings to be shown in default keyboard.
  2441. `show_in_keyboard`, if True, makes a button for this command appear in
  2442. default keyboard.
  2443. `description` is a description and can be used to help users understand
  2444. what `/command` does.
  2445. `authorization_level` is the lowest authorization level needed to run
  2446. the command.
  2447. """
  2448. if not callable(handler):
  2449. raise TypeError(f'Handler `{handler}` is not callable.')
  2450. return self.command(
  2451. command=command, aliases=aliases,
  2452. reply_keyboard_button=reply_keyboard_button,
  2453. show_in_keyboard=show_in_keyboard, description=description,
  2454. authorization_level=authorization_level
  2455. )(handler)
  2456. def button(self, prefix, separator=None, description='',
  2457. authorization_level='admin'):
  2458. """Associate a bot button `prefix` with a handler.
  2459. When a callback data text starts with `prefix`, the associated handler
  2460. is called upon the update.
  2461. Decorate button handlers like this:
  2462. ```
  2463. @bot.button('a_prefix:///', description="A button",
  2464. authorization_level='user')
  2465. async def button_handler(bot, update, user_record, language, data):
  2466. return "Result"
  2467. ```
  2468. `separator` will be used to parse callback data received when a button
  2469. starting with `prefix` will be pressed.
  2470. `description` contains information about the button.
  2471. `authorization_level` is the lowest authorization level needed to
  2472. be allowed to push the button.
  2473. """
  2474. if not isinstance(prefix, str):
  2475. raise TypeError(
  2476. f'Inline button callback_data {prefix} is not a string'
  2477. )
  2478. def button_decorator(handler):
  2479. async def decorated_button_handler(bot, update, user_record, language=None):
  2480. logging.info(
  2481. f"Button `{update['data']}`@{bot.name} pressed by "
  2482. f"`{update['from']}`"
  2483. )
  2484. if bot.authorization_function(
  2485. update=update,
  2486. user_record=user_record,
  2487. authorization_level=authorization_level
  2488. ):
  2489. # Remove `prefix` from `data`
  2490. data = extract(update['data'], prefix)
  2491. # If a specific separator or default separator is set,
  2492. # use it to split `data` string in a list.
  2493. # Cast numeric `data` elements to `int`.
  2494. _separator = separator or self.callback_data_separator
  2495. if _separator:
  2496. data = [
  2497. int(element) if element.isnumeric()
  2498. else element
  2499. for element in data.split(_separator)
  2500. ]
  2501. # Pass supported arguments from locals() to handler
  2502. return await handler(
  2503. **{
  2504. name: argument
  2505. for name, argument in locals().items()
  2506. if name in inspect.signature(handler).parameters
  2507. }
  2508. )
  2509. return bot.authorization_denied_message
  2510. self.callback_handlers[prefix] = dict(
  2511. handler=decorated_button_handler,
  2512. description=description,
  2513. authorization_level=authorization_level
  2514. )
  2515. return button_decorator
  2516. def query(self, condition, description='', authorization_level='admin'):
  2517. """Define an inline query.
  2518. Decorator: `@bot.query(example)`
  2519. When an inline query matches the `condition` function,
  2520. decorated function is called and passed the query update object
  2521. as argument.
  2522. `description` is a description
  2523. `authorization_level` is the lowest authorization level needed to run
  2524. the command
  2525. """
  2526. if not callable(condition):
  2527. raise TypeError(
  2528. 'Condition {c} is not a callable'.format(
  2529. c=condition.__name__
  2530. )
  2531. )
  2532. def query_decorator(handler):
  2533. async def decorated_query_handler(bot, update, user_record, language=None):
  2534. logging.info(
  2535. f"Inline query matching condition "
  2536. f"`{condition.__name__}@{bot.name}` from "
  2537. f"`{update['from']}`"
  2538. )
  2539. if self.authorization_function(
  2540. update=update,
  2541. user_record=user_record,
  2542. authorization_level=authorization_level
  2543. ):
  2544. # Pass supported arguments from locals() to handler
  2545. return await handler(
  2546. **{
  2547. name: argument
  2548. for name, argument in locals().items()
  2549. if name in inspect.signature(handler).parameters
  2550. }
  2551. )
  2552. return self.authorization_denied_message
  2553. self.inline_query_handlers[condition] = dict(
  2554. handler=decorated_query_handler,
  2555. description=description,
  2556. authorization_level=authorization_level
  2557. )
  2558. return query_decorator
  2559. def set_chat_id_getter(self, getter):
  2560. """Set chat_id getter.
  2561. It must be a function that takes an update and returns the proper
  2562. chat_id.
  2563. """
  2564. assert callable(getter), "Chat id getter must be a function!"
  2565. self.get_chat_id = getter
  2566. @staticmethod
  2567. def get_user_identifier(user_id=None, update=None):
  2568. """Get telegram id of user given an update.
  2569. Result itself may be passed as either parameter (for backward
  2570. compatibility).
  2571. """
  2572. identifier = user_id or update
  2573. assert identifier is not None, (
  2574. "Provide a user_id or update object to get a user identifier."
  2575. )
  2576. if (
  2577. isinstance(identifier, dict)
  2578. and 'message' in identifier
  2579. and 'from' not in identifier
  2580. ):
  2581. identifier = identifier['message']
  2582. if isinstance(identifier, dict) and 'from' in identifier:
  2583. identifier = identifier['from']['id']
  2584. assert type(identifier) is int, (
  2585. f"Unable to find a user identifier. Got `{identifier}`"
  2586. )
  2587. return identifier
  2588. @staticmethod
  2589. def get_message_identifier(update=None):
  2590. """Get a message identifier dictionary to edit `update`.
  2591. Pass the result as keyword arguments to `edit...` API methods.
  2592. """
  2593. if update is None:
  2594. update = dict()
  2595. if 'message' in update:
  2596. update = update['message']
  2597. if 'chat' in update and 'message_id' in update:
  2598. return dict(
  2599. chat_id=update['chat']['id'],
  2600. message_id=update['message_id']
  2601. )
  2602. elif 'inline_message_id' in update:
  2603. return dict(
  2604. inline_message_id=update['inline_message_id']
  2605. )
  2606. def set_individual_text_message_handler(self, handler,
  2607. update=None, user_id=None):
  2608. """Set a custom text message handler for the user.
  2609. Any text message update from the user will be handled by this custom
  2610. handler instead of default handlers for commands, aliases and text.
  2611. Custom handlers last one single use, but they can call this method and
  2612. set themselves as next custom text message handler.
  2613. """
  2614. identifier = self.get_user_identifier(
  2615. user_id=user_id,
  2616. update=update
  2617. )
  2618. assert callable(handler), (f"Handler `{handler.name}` is not "
  2619. "callable. Custom text message handler "
  2620. "could not be set.")
  2621. self.individual_text_message_handlers[identifier] = handler
  2622. return
  2623. def remove_individual_text_message_handler(self,
  2624. update=None, user_id=None):
  2625. """Remove a custom text message handler for the user.
  2626. Any text message update from the user will be handled by default
  2627. handlers for commands, aliases and text.
  2628. """
  2629. identifier = self.get_user_identifier(
  2630. user_id=user_id,
  2631. update=update
  2632. )
  2633. if identifier in self.individual_text_message_handlers:
  2634. del self.individual_text_message_handlers[identifier]
  2635. return
  2636. def set_individual_location_handler(self, handler,
  2637. update=None, user_id=None):
  2638. """Set a custom location handler for the user.
  2639. Any location update from the user will be handled by this custom
  2640. handler instead of default handlers for locations.
  2641. Custom handlers last one single use, but they can call this method and
  2642. set themselves as next custom handler.
  2643. """
  2644. identifier = self.get_user_identifier(
  2645. user_id=user_id,
  2646. update=update
  2647. )
  2648. assert callable(handler), (f"Handler `{handler.name}` is not "
  2649. "callable. Custom location handler "
  2650. "could not be set.")
  2651. self.individual_location_handlers[identifier] = handler
  2652. return
  2653. def remove_individual_location_handler(self,
  2654. update=None, user_id=None):
  2655. """Remove a custom location handler for the user.
  2656. Any location message update from the user will be handled by default
  2657. handlers for locations.
  2658. """
  2659. identifier = self.get_user_identifier(
  2660. user_id=user_id,
  2661. update=update
  2662. )
  2663. if identifier in self.individual_location_handlers:
  2664. del self.individual_location_handlers[identifier]
  2665. return
  2666. def set_individual_document_handler(self, handler,
  2667. update=None, user_id=None):
  2668. """Set a custom document handler for the user.
  2669. Any document update from the user will be handled by this custom
  2670. handler instead of default handlers for documents.
  2671. Custom handlers last one single use, but they can call this method and
  2672. set themselves as next custom document handler.
  2673. """
  2674. identifier = self.get_user_identifier(
  2675. user_id=user_id,
  2676. update=update
  2677. )
  2678. assert callable(handler), (f"Handler `{handler.name}` is not "
  2679. "callable. Custom document handler "
  2680. "could not be set.")
  2681. self.individual_document_message_handlers[identifier] = handler
  2682. return
  2683. def remove_individual_document_handler(self,
  2684. update=None, user_id=None):
  2685. """Remove a custom document handler for the user.
  2686. Any document update from the user will be handled by default
  2687. handlers for documents.
  2688. """
  2689. identifier = self.get_user_identifier(
  2690. user_id=user_id,
  2691. update=update
  2692. )
  2693. if identifier in self.individual_document_message_handlers:
  2694. del self.individual_document_message_handlers[identifier]
  2695. return
  2696. def set_individual_voice_handler(self, handler,
  2697. update=None, user_id=None):
  2698. """Set a custom voice message handler for the user.
  2699. Any voice message update from the user will be handled by this custom
  2700. handler instead of default handlers for voice messages.
  2701. Custom handlers last one single use, but they can call this method and
  2702. set themselves as next custom handler.
  2703. """
  2704. identifier = self.get_user_identifier(
  2705. user_id=user_id,
  2706. update=update
  2707. )
  2708. assert callable(handler), (f"Handler `{handler.name}` is not "
  2709. "callable. Custom voice handler "
  2710. "could not be set.")
  2711. self.individual_voice_handlers[identifier] = handler
  2712. return
  2713. def remove_individual_voice_handler(self,
  2714. update=None, user_id=None):
  2715. """Remove a custom voice handler for the user.
  2716. Any voice message update from the user will be handled by default
  2717. handlers for voice messages.
  2718. """
  2719. identifier = self.get_user_identifier(
  2720. user_id=user_id,
  2721. update=update
  2722. )
  2723. if identifier in self.individual_voice_handlers:
  2724. del self.individual_voice_handlers[identifier]
  2725. return
  2726. def set_individual_handler(self, handler, update_type: str,
  2727. update=None, user_id=None,):
  2728. """Set a custom `update_type` handler for the user.
  2729. Any update of given type from the user will be handled by this custom
  2730. handler instead of default handler.
  2731. Custom handlers last one single use, but they can call this method and
  2732. set themselves as next custom handler.
  2733. """
  2734. identifier = self.get_user_identifier(
  2735. user_id=user_id,
  2736. update=update
  2737. )
  2738. assert callable(handler), (f"Handler `{handler.name}` is not "
  2739. "callable. Custom handler "
  2740. "could not be set.")
  2741. if update_type not in self.individual_handlers:
  2742. self.individual_handlers[update_type] = dict()
  2743. self.individual_handlers[update_type][identifier] = handler
  2744. return
  2745. def remove_individual_handler(self, update_type: str,
  2746. update=None, user_id=None):
  2747. """Remove a custom `update_type` handler for the user.
  2748. Any update of given type from the user will be handled by default
  2749. handler for its type.
  2750. """
  2751. identifier = self.get_user_identifier(
  2752. user_id=user_id,
  2753. update=update
  2754. )
  2755. if (
  2756. update_type in self.individual_handlers
  2757. and identifier in self.individual_handlers[update_type]
  2758. ):
  2759. del self.individual_handlers[update_type][identifier]
  2760. return
  2761. def set_individual_contact_message_handler(self, handler,
  2762. update: dict,
  2763. user_id: OrderedDict):
  2764. return self.set_individual_handler(handler=handler,
  2765. update_type='contact',
  2766. update=update,
  2767. user_id=user_id)
  2768. def remove_individual_contact_handler(self, update=None, user_id=None):
  2769. return self.remove_individual_handler(update_type='contact',
  2770. update=update,
  2771. user_id=user_id)
  2772. def set_placeholder(self, chat_id,
  2773. text=None, sent_message=None, timeout=1):
  2774. """Set a placeholder chat action or text message.
  2775. If it takes the bot more than `timeout` to answer, send a placeholder
  2776. message or a `is typing` chat action.
  2777. `timeout` may be expressed in seconds (int) or datetime.timedelta
  2778. This method returns a `request_id`. When the calling function has
  2779. performed its task, it must set to 1 the value of
  2780. `self.placeholder_requests[request_id]`.
  2781. If this value is still 0 at `timeout`, the placeholder is sent.
  2782. Otherwise, no action is performed.
  2783. """
  2784. request_id = len(self.placeholder_requests)
  2785. self.placeholder_requests[request_id] = 0
  2786. asyncio.ensure_future(
  2787. self.placeholder_effector(
  2788. request_id=request_id,
  2789. timeout=timeout,
  2790. chat_id=chat_id,
  2791. sent_message=sent_message,
  2792. text=text
  2793. )
  2794. )
  2795. return request_id
  2796. async def placeholder_effector(self, request_id, timeout, chat_id,
  2797. sent_message=None, text=None):
  2798. """Send a placeholder chat action or text message if needed.
  2799. If it takes the bot more than `timeout` to answer, send a placeholder
  2800. message or a `is typing` chat action.
  2801. `timeout` may be expressed in seconds (int) or datetime.timedelta
  2802. """
  2803. if type(timeout) is datetime.timedelta:
  2804. timeout = timeout.total_seconds()
  2805. await asyncio.sleep(timeout)
  2806. if not self.placeholder_requests[request_id]:
  2807. if sent_message and text:
  2808. await self.edit_message_text(
  2809. update=sent_message,
  2810. text=text,
  2811. )
  2812. else:
  2813. await self.sendChatAction(
  2814. chat_id=chat_id,
  2815. action='typing'
  2816. )
  2817. return
  2818. async def webhook_feeder(self, request):
  2819. """Handle incoming HTTP `request`s.
  2820. Get data, feed webhook and return and OK message.
  2821. """
  2822. update = await request.json()
  2823. asyncio.ensure_future(
  2824. self.route_update(update)
  2825. )
  2826. return aiohttp.web.Response(
  2827. body='OK'.encode('utf-8')
  2828. )
  2829. async def get_me(self):
  2830. """Get bot information.
  2831. Restart bots if bot can't be got.
  2832. """
  2833. try:
  2834. me = await self.getMe()
  2835. if isinstance(me, Exception):
  2836. raise me
  2837. elif me is None:
  2838. raise Exception('getMe returned None')
  2839. self._name = me["username"]
  2840. self._telegram_id = me['id']
  2841. except Exception as e:
  2842. logging.error(
  2843. f"API getMe method failed, information about this bot could "
  2844. f"not be retrieved. Restarting in 5 minutes...\n\n"
  2845. f"Error information:\n{e}"
  2846. )
  2847. await asyncio.sleep(5*60)
  2848. self.__class__.stop(
  2849. message="Information about this bot could not be retrieved.\n"
  2850. "Restarting...",
  2851. final_state=65
  2852. )
  2853. def setup(self):
  2854. """Make bot ask for updates and handle responses."""
  2855. if not self.webhook_url:
  2856. asyncio.ensure_future(self.get_updates())
  2857. else:
  2858. asyncio.ensure_future(self.set_webhook())
  2859. self.__class__.app.router.add_route(
  2860. 'POST', self.webhook_local_address, self.webhook_feeder
  2861. )
  2862. asyncio.ensure_future(self.update_users())
  2863. async def close_sessions(self):
  2864. """Close open sessions."""
  2865. for session_name, session in self.sessions.items():
  2866. if not session.closed:
  2867. await session.close()
  2868. async def set_webhook(self, url=None, certificate=None,
  2869. max_connections=None, allowed_updates=None):
  2870. """Set a webhook if token is valid."""
  2871. # Return if token is invalid
  2872. await self.get_me()
  2873. if self.name is None:
  2874. return
  2875. if allowed_updates is None:
  2876. allowed_updates = []
  2877. if certificate is None:
  2878. certificate = self.certificate
  2879. if max_connections is None:
  2880. max_connections = self.max_connections
  2881. if url is None:
  2882. url = self.webhook_url
  2883. webhook_was_set = await self.setWebhook(
  2884. url=url, certificate=certificate, max_connections=max_connections,
  2885. allowed_updates=allowed_updates
  2886. ) # `setWebhook` API method returns `True` on success
  2887. webhook_information = await self.getWebhookInfo()
  2888. webhook_information['url'] = webhook_information['url'].replace(
  2889. self.token, "<BOT_TOKEN>"
  2890. ).replace(
  2891. self.session_token, "<SESSION_TOKEN>"
  2892. )
  2893. if webhook_was_set:
  2894. logging.info(
  2895. f"Webhook was set correctly.\n"
  2896. f"Webhook information: {webhook_information}"
  2897. )
  2898. else:
  2899. logging.error(
  2900. f"Failed to set webhook!\n"
  2901. f"Webhook information: {webhook_information}"
  2902. )
  2903. async def get_updates(self, timeout=30, limit=100, allowed_updates=None,
  2904. error_cooldown=10):
  2905. """Get updates using long polling.
  2906. timeout : int
  2907. Timeout set for Telegram servers. Make sure that connection timeout
  2908. is greater than `timeout`.
  2909. limit : int (1 - 100)
  2910. Max number of updates to be retrieved.
  2911. allowed_updates : List(str)
  2912. List of update types to be retrieved.
  2913. Empty list to allow all updates.
  2914. None to fallback to class default.
  2915. """
  2916. # Return if token is invalid
  2917. await self.get_me()
  2918. if self.name is None:
  2919. return
  2920. # Set custom list of allowed updates or fallback to class default list
  2921. if allowed_updates is None:
  2922. allowed_updates = self.allowed_updates
  2923. await self.deleteWebhook() # Remove eventually active webhook
  2924. update = None # Do not update offset if no update is received
  2925. while True:
  2926. updates = await self.getUpdates(
  2927. offset=self._offset,
  2928. timeout=timeout,
  2929. limit=limit,
  2930. allowed_updates=allowed_updates
  2931. )
  2932. if updates is None:
  2933. continue
  2934. elif isinstance(updates, TelegramError):
  2935. logging.error(
  2936. f"Waiting {error_cooldown} seconds before trying again..."
  2937. )
  2938. await asyncio.sleep(error_cooldown)
  2939. continue
  2940. elif isinstance(updates, Exception):
  2941. logging.error(
  2942. "Unexpected exception. "
  2943. f"Waiting {error_cooldown} seconds before trying again..."
  2944. )
  2945. await asyncio.sleep(error_cooldown)
  2946. continue
  2947. for update in updates:
  2948. asyncio.ensure_future(self.route_update(update))
  2949. if update is not None:
  2950. self._offset = update['update_id'] + 1
  2951. async def update_users(self, interval=60):
  2952. """Every `interval` seconds, store news about bot users.
  2953. Compare `update['from']` data with records in `users` table and keep
  2954. track of differences in `users_history` table.
  2955. """
  2956. while 1:
  2957. await asyncio.sleep(interval)
  2958. users_profile_pictures_to_update = OrderedDict()
  2959. now = datetime.datetime.now()
  2960. # Iterate through a copy since asyncio.sleep(0) is awaited at each
  2961. # cycle iteration.
  2962. for telegram_id, user in self.recent_users.copy().items():
  2963. new_record = dict()
  2964. with self.db as db:
  2965. user_record = db['users'].find_one(telegram_id=telegram_id)
  2966. user_picture_record = db['user_profile_photos'].find_one(
  2967. user_id=user_record['id'],
  2968. order_by=['-update_datetime']
  2969. )
  2970. # If user profile picture needs to be updated, add it to the OD
  2971. if (user_picture_record is None
  2972. or user_picture_record['update_datetime']
  2973. < now - datetime.timedelta(days=1)):
  2974. users_profile_pictures_to_update[telegram_id] = user_picture_record
  2975. for key in ('first_name', 'last_name',
  2976. 'username', 'language_code', ):
  2977. new_record[key] = (user[key] if key in user else None)
  2978. if (
  2979. (
  2980. key not in user_record
  2981. or new_record[key] != user_record[key]
  2982. )
  2983. # Exclude fake updates
  2984. and 'notes' not in user
  2985. ):
  2986. db['users_history'].insert(
  2987. dict(
  2988. until=datetime.datetime.now(),
  2989. user_id=user_record['id'],
  2990. field=key,
  2991. value=(
  2992. user_record[key]
  2993. if key in user_record
  2994. else None
  2995. )
  2996. )
  2997. )
  2998. db['users'].update(
  2999. {
  3000. 'id': user_record['id'],
  3001. key: new_record[key]
  3002. },
  3003. ['id'],
  3004. ensure=True
  3005. )
  3006. if telegram_id in self.recent_users:
  3007. del self.recent_users[telegram_id]
  3008. await asyncio.sleep(0)
  3009. # Update user profile pictures
  3010. for telegram_id, user_picture_record in users_profile_pictures_to_update.items():
  3011. try:
  3012. user_profile_photos = await self.getUserProfilePhotos(
  3013. user_id=telegram_id,
  3014. offset=0,
  3015. limit=1
  3016. )
  3017. if (user_profile_photos is not None
  3018. and 'photos' in user_profile_photos
  3019. and len(user_profile_photos['photos'])):
  3020. current_photo = user_profile_photos['photos'][0][0]
  3021. if (
  3022. user_picture_record is None
  3023. or (
  3024. isinstance(user_picture_record, dict)
  3025. and current_photo['file_id']
  3026. != user_picture_record['telegram_file_id']
  3027. )
  3028. ):
  3029. db['user_profile_photos'].insert(dict(
  3030. user_id=user_record['id'],
  3031. telegram_file_id=current_photo['file_id'],
  3032. update_datetime=now
  3033. ))
  3034. else:
  3035. db['user_profile_photos'].upsert(
  3036. dict(
  3037. user_id=user_record['id'],
  3038. telegram_file_id=current_photo['file_id'],
  3039. update_datetime=now
  3040. ),
  3041. ['user_id', 'telegram_file_id']
  3042. )
  3043. except Exception as e:
  3044. logging.error(e)
  3045. def get_user_record(self, update):
  3046. """Get user_record of update sender.
  3047. If user is unknown add them.
  3048. If update has no `from` field, return None.
  3049. If user data changed, ensure that this event gets stored.
  3050. """
  3051. if 'from' not in update or 'id' not in update['from']:
  3052. return
  3053. telegram_id = update['from']['id']
  3054. with self.db as db:
  3055. user_record = db['users'].find_one(
  3056. telegram_id=telegram_id
  3057. )
  3058. if user_record is None:
  3059. new_user = dict(
  3060. telegram_id=telegram_id,
  3061. privileges=100,
  3062. selected_language_code=None
  3063. )
  3064. for key in [
  3065. 'first_name',
  3066. 'last_name',
  3067. 'username',
  3068. 'language_code'
  3069. ]:
  3070. new_user[key] = (
  3071. update['from'][key]
  3072. if key in update['from']
  3073. else None
  3074. )
  3075. db['users'].insert(new_user)
  3076. user_record = db['users'].find_one(
  3077. telegram_id=telegram_id
  3078. )
  3079. elif (
  3080. telegram_id not in self.recent_users
  3081. and 'notes' not in update['from'] # Exclude fake updates
  3082. ):
  3083. self.recent_users[telegram_id] = update['from']
  3084. return user_record
  3085. def set_router(self, event, handler):
  3086. """Set `handler` as router for `event`."""
  3087. self.routing_table[event] = handler
  3088. def set_message_handler(self, message_type: str, handler: Callable):
  3089. """Set `handler` for `message_type`."""
  3090. self.message_handlers[message_type] = handler
  3091. async def route_update(self, raw_update):
  3092. """Pass `update` to proper method.
  3093. Update objects have two keys:
  3094. - `update_id` (which is used as offset while retrieving new updates)
  3095. - One and only one of the following
  3096. `message`
  3097. `edited_message`
  3098. `channel_post`
  3099. `edited_channel_post`
  3100. `inline_query`
  3101. `chosen_inline_result`
  3102. `callback_query`
  3103. `shipping_query`
  3104. `pre_checkout_query`
  3105. `poll`
  3106. """
  3107. if (
  3108. self.under_maintenance
  3109. and not self.is_allowed_during_maintenance(raw_update)
  3110. ):
  3111. return await self.handle_update_during_maintenance(raw_update)
  3112. for key in self.routing_table:
  3113. if key in raw_update:
  3114. update = raw_update[key]
  3115. update['update_id'] = raw_update['update_id']
  3116. user_record = self.get_user_record(update=update)
  3117. language = self.get_language(update=update,
  3118. user_record=user_record)
  3119. bot = self
  3120. return await self.routing_table[key](**{
  3121. name: argument
  3122. for name, argument in locals().items()
  3123. if name in inspect.signature(
  3124. self.routing_table[key]
  3125. ).parameters
  3126. })
  3127. logging.error(f"Unknown type of update.\n{raw_update}")
  3128. def additional_task(self, when='BEFORE', *args, **kwargs):
  3129. """Add a task before at app start or cleanup.
  3130. Decorate an async function to have it awaited `BEFORE` or `AFTER` main
  3131. loop.
  3132. """
  3133. when = when[0].lower()
  3134. def additional_task_decorator(task):
  3135. if when == 'b':
  3136. self.preliminary_tasks.append(task(*args, **kwargs))
  3137. elif when == 'a':
  3138. self.final_tasks.append(task(*args, **kwargs))
  3139. return additional_task_decorator
  3140. @classmethod
  3141. async def start_app(cls):
  3142. """Start running `aiohttp.web.Application`.
  3143. It will route webhook-received updates and other custom paths.
  3144. """
  3145. assert cls.local_host is not None, "Invalid local host"
  3146. assert cls.port is not None, "Invalid port"
  3147. cls.runner = aiohttp.web.AppRunner(cls.app)
  3148. await cls.runner.setup()
  3149. cls.server = aiohttp.web.TCPSite(cls.runner, cls.local_host, cls.port)
  3150. try:
  3151. await cls.server.start()
  3152. except OSError as e:
  3153. logging.error(e)
  3154. raise KeyboardInterrupt("Unable to start web app.")
  3155. logging.info(f"App running at http://{cls.local_host}:{cls.port}")
  3156. @classmethod
  3157. async def stop_app(cls):
  3158. """Close bot sessions and cleanup."""
  3159. for bot in cls.bots:
  3160. await asyncio.gather(
  3161. *bot.final_tasks
  3162. )
  3163. await bot.close_sessions()
  3164. await cls.runner.cleanup()
  3165. @classmethod
  3166. def stop(cls, message, final_state=0):
  3167. """Log a final `message`, stop loop and set exiting `code`.
  3168. All bots and the web app will be terminated gracefully.
  3169. The final state may be retrieved to get information about what stopped
  3170. the bots.
  3171. """
  3172. logging.info(message)
  3173. cls.final_state = final_state
  3174. cls.loop.stop()
  3175. return
  3176. @classmethod
  3177. def run(cls, local_host=None, port=None):
  3178. """Run aiohttp web app and all Bot instances.
  3179. Each bot will receive updates via long polling or webhook according to
  3180. its initialization parameters.
  3181. A single aiohttp.web.Application instance will be run (cls.app) on
  3182. local_host:port and it may serve custom-defined routes as well.
  3183. """
  3184. if local_host is not None:
  3185. cls.local_host = local_host
  3186. if port is not None:
  3187. cls.port = port
  3188. try:
  3189. cls.loop.run_until_complete(
  3190. asyncio.gather(
  3191. *[
  3192. preliminary_task
  3193. for bot in cls.bots
  3194. for preliminary_task in bot.preliminary_tasks
  3195. ]
  3196. )
  3197. )
  3198. except Exception as e:
  3199. logging.error(f"{e}", exc_info=True)
  3200. for bot in cls.bots:
  3201. bot.setup()
  3202. asyncio.ensure_future(cls.start_app())
  3203. try:
  3204. cls.loop.run_forever()
  3205. except KeyboardInterrupt:
  3206. logging.info("Stopped by KeyboardInterrupt")
  3207. except Exception as e:
  3208. logging.error(f"{e}", exc_info=True)
  3209. finally:
  3210. cls.loop.run_until_complete(cls.stop_app())
  3211. return cls.final_state
  3212. def set_role_class(self, role):
  3213. """Set a Role class for bot.
  3214. `role` must be an instance of `authorization.Role`.
  3215. """
  3216. self.Role = role