Queer European MD passionate about IT

bot.py 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475
  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. from aiohttp import web
  39. # Project modules
  40. from .api import TelegramBot, TelegramError
  41. from .database import ObjectWithDatabase
  42. from .languages import MultiLanguageObject
  43. from .messages import davtelepot_messages
  44. from .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, chat_id: Union[int, str], photo,
  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], document,
  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 reply_to_update and 'message_id' in update:
  1792. reply_to_message_id = update['message_id']
  1793. if chat_id > 0:
  1794. user_record = self.db['users'].find_one(telegram_id=chat_id)
  1795. language = self.get_language(update=update, user_record=user_record)
  1796. if (
  1797. send_default_keyboard
  1798. and reply_markup is None
  1799. and type(chat_id) is int
  1800. and caption != self.authorization_denied_message
  1801. ):
  1802. reply_markup = self.get_keyboard(
  1803. user_record=user_record
  1804. )
  1805. else:
  1806. language = self.default_language
  1807. if document_path is not None:
  1808. with self.db as db:
  1809. already_sent = db['sent_documents'].find_one(
  1810. path=document_path,
  1811. errors=False
  1812. )
  1813. if already_sent and use_stored_file_id:
  1814. document = already_sent['file_id']
  1815. already_sent = True
  1816. else:
  1817. already_sent = False
  1818. if not any(
  1819. [
  1820. document_path.startswith(url_starter)
  1821. for url_starter in ('http', 'www',)
  1822. ]
  1823. ): # If `document_path` is not a url but a local file path
  1824. try:
  1825. with open(
  1826. document_path.format(
  1827. path=self.path
  1828. ),
  1829. 'rb' # Read bytes
  1830. ) as file_:
  1831. file_size = os.fstat(file_.fileno()).st_size
  1832. document_chunks = (
  1833. int(
  1834. file_size
  1835. / self.documents_max_dimension
  1836. ) + 1
  1837. )
  1838. original_document_name = (
  1839. document_name
  1840. or file_.name
  1841. or 'Document'
  1842. )
  1843. original_caption = caption
  1844. if '/' in original_document_name:
  1845. original_document_name = os.path.basename(
  1846. os.path.abspath(original_document_name)
  1847. )
  1848. for i in range(document_chunks):
  1849. buffered_file = io.BytesIO(
  1850. file_.read(self.documents_max_dimension)
  1851. )
  1852. if document_chunks > 1:
  1853. part = self.get_message(
  1854. 'davtelepot', 'part',
  1855. language=language
  1856. )
  1857. caption = f"{original_caption} - {part} {i + 1}/{document_chunks}"
  1858. buffered_file.name = (
  1859. f"{original_document_name} - "
  1860. f"{part} {i + 1}"
  1861. )
  1862. else:
  1863. buffered_file.name = original_document_name
  1864. sent_document = await self.send_document(
  1865. chat_id=chat_id,
  1866. document=buffered_file,
  1867. thumb=thumb,
  1868. caption=caption,
  1869. parse_mode=parse_mode,
  1870. disable_notification=disable_notification,
  1871. reply_to_message_id=reply_to_message_id,
  1872. reply_markup=reply_markup,
  1873. update=update,
  1874. reply_to_update=reply_to_update,
  1875. send_default_keyboard=send_default_keyboard,
  1876. use_stored_file_id=use_stored_file_id
  1877. )
  1878. return sent_document
  1879. except FileNotFoundError as e:
  1880. if buffered_file:
  1881. buffered_file.close()
  1882. buffered_file = None
  1883. return e
  1884. else:
  1885. use_stored_file_id = False
  1886. if document is None:
  1887. logging.error(
  1888. "`document` is None, `send_document` returning..."
  1889. )
  1890. return Exception("No `document` provided")
  1891. sent_update = None
  1892. try:
  1893. sent_update = await self.sendDocument(
  1894. chat_id=chat_id,
  1895. document=document,
  1896. thumb=thumb,
  1897. caption=caption,
  1898. parse_mode=parse_mode,
  1899. caption_entities=caption_entities,
  1900. disable_content_type_detection=disable_content_type_detection,
  1901. disable_notification=disable_notification,
  1902. reply_to_message_id=reply_to_message_id,
  1903. allow_sending_without_reply=allow_sending_without_reply,
  1904. reply_markup=reply_markup
  1905. )
  1906. if isinstance(sent_update, Exception):
  1907. raise Exception("sendDocument API call failed!")
  1908. except Exception as e:
  1909. logging.error(f"Error sending document\n{e}")
  1910. if already_sent:
  1911. with self.db as db:
  1912. db['sent_documents'].update(
  1913. dict(
  1914. path=document_path,
  1915. errors=True
  1916. ),
  1917. ['path']
  1918. )
  1919. if (
  1920. type(sent_update) is dict
  1921. and 'document' in sent_update
  1922. and 'file_id' in sent_update['document']
  1923. and (not already_sent)
  1924. and use_stored_file_id
  1925. ):
  1926. with self.db as db:
  1927. db['sent_documents'].insert(
  1928. dict(
  1929. path=document_path,
  1930. file_id=sent_update['document']['file_id'],
  1931. errors=False
  1932. )
  1933. )
  1934. return sent_update
  1935. async def download_file(self, file_id,
  1936. file_name=None, path=None):
  1937. """Given a telegram `file_id`, download the related file.
  1938. Telegram may not preserve the original file name and MIME type: the
  1939. file's MIME type and name (if available) should be stored when the
  1940. File object is received.
  1941. """
  1942. file = await self.getFile(file_id=file_id)
  1943. if file is None or isinstance(file, Exception):
  1944. logging.error(f"{file}")
  1945. return
  1946. file_bytes = await async_get(
  1947. url=(
  1948. f"https://api.telegram.org/file/"
  1949. f"bot{self.token}/"
  1950. f"{file['file_path']}"
  1951. ),
  1952. mode='raw'
  1953. )
  1954. path = path or self.path
  1955. while file_name is None:
  1956. file_name = get_secure_key(length=10)
  1957. if os.path.exists(f"{path}/{file_name}"):
  1958. file_name = None
  1959. try:
  1960. with open(f"{path}/{file_name}", 'wb') as local_file:
  1961. local_file.write(file_bytes)
  1962. except Exception as e:
  1963. logging.error(f"File download failed due to {e}")
  1964. return
  1965. def translate_inline_query_answer_result(self, record,
  1966. update=None, user_record=None):
  1967. """Translate title and message text fields of inline query result.
  1968. This method does not alter original `record`. This way, default
  1969. inline query result is kept multilingual although single results
  1970. sent to users are translated.
  1971. """
  1972. result = dict()
  1973. for key, val in record.items():
  1974. if key == 'title' and isinstance(record[key], dict):
  1975. result[key] = self.get_message(
  1976. update=update,
  1977. user_record=user_record,
  1978. messages=record[key]
  1979. )
  1980. elif (
  1981. key == 'input_message_content'
  1982. and isinstance(record[key], dict)
  1983. ):
  1984. result[key] = self.translate_inline_query_answer_result(
  1985. record[key],
  1986. update=update,
  1987. user_record=user_record
  1988. )
  1989. elif key == 'message_text' and isinstance(record[key], dict):
  1990. result[key] = self.get_message(
  1991. update=update,
  1992. user_record=user_record,
  1993. messages=record[key]
  1994. )
  1995. else:
  1996. result[key] = val
  1997. return result
  1998. async def answer_inline_query(self,
  1999. inline_query_id=None,
  2000. results=None,
  2001. cache_time=None,
  2002. is_personal=None,
  2003. next_offset=None,
  2004. switch_pm_text=None,
  2005. switch_pm_parameter=None,
  2006. update=None,
  2007. user_record=None):
  2008. """Answer inline queries.
  2009. This method wraps lower-level `answerInlineQuery` method.
  2010. If `results` is a string, cast it to proper type (list of dicts having
  2011. certain keys). See utilities.make_inline_query_answer for details.
  2012. """
  2013. if results is None:
  2014. results = []
  2015. if (
  2016. inline_query_id is None
  2017. and isinstance(update, dict)
  2018. and 'id' in update
  2019. ):
  2020. inline_query_id = update['id']
  2021. results = [
  2022. self.translate_inline_query_answer_result(record=result,
  2023. update=update,
  2024. user_record=user_record)
  2025. for result in make_inline_query_answer(results)
  2026. ]
  2027. return await self.answerInlineQuery(
  2028. inline_query_id=inline_query_id,
  2029. results=results,
  2030. cache_time=cache_time,
  2031. is_personal=is_personal,
  2032. next_offset=next_offset,
  2033. switch_pm_text=switch_pm_text,
  2034. switch_pm_parameter=switch_pm_parameter,
  2035. )
  2036. @classmethod
  2037. def set_class_maintenance_message(cls, maintenance_message):
  2038. """Set class maintenance message.
  2039. It will be returned if bot is under maintenance, unless and instance
  2040. `_maintenance_message` is set.
  2041. """
  2042. cls._maintenance_message = maintenance_message
  2043. def set_maintenance_message(self, maintenance_message):
  2044. """Set instance maintenance message.
  2045. It will be returned if bot is under maintenance.
  2046. If instance message is None, default class message is used.
  2047. """
  2048. self._maintenance_message = maintenance_message
  2049. def change_maintenance_status(self, maintenance_message=None, status=None):
  2050. """Put the bot under maintenance or end it.
  2051. While in maintenance, bot will reply to users with maintenance_message
  2052. with a few exceptions.
  2053. If status is not set, it is by default the opposite of the current one.
  2054. Optionally, `maintenance_message` may be set.
  2055. """
  2056. if status is None:
  2057. status = not self.under_maintenance
  2058. assert type(status) is bool, "status must be a boolean value!"
  2059. self._under_maintenance = status
  2060. if maintenance_message:
  2061. self.set_maintenance_message(maintenance_message)
  2062. return self._under_maintenance # Return new status
  2063. def is_allowed_during_maintenance(self, update):
  2064. """Return True if update is allowed during maintenance.
  2065. An update is allowed if any of the criteria in
  2066. `self.allowed_during_maintenance` returns True called on it.
  2067. """
  2068. for criterion in self.allowed_during_maintenance:
  2069. if criterion(update):
  2070. return True
  2071. return False
  2072. def allow_during_maintenance(self, criterion):
  2073. """Add a criterion to allow certain updates during maintenance.
  2074. `criterion` must be a function taking a Telegram `update` dictionary
  2075. and returning a boolean.
  2076. ```# Example of criterion
  2077. def allow_text_messages(update):
  2078. if 'message' in update and 'text' in update['message']:
  2079. return True
  2080. return False
  2081. ```
  2082. """
  2083. self._allowed_during_maintenance.append(criterion)
  2084. async def handle_update_during_maintenance(self, update, user_record=None, language=None):
  2085. """Handle an update while bot is under maintenance.
  2086. Handle all types of updates.
  2087. """
  2088. if (
  2089. 'message' in update
  2090. and 'chat' in update['message']
  2091. and update['message']['chat']['id'] > 0
  2092. ):
  2093. return await self.send_message(
  2094. text=self.maintenance_message,
  2095. update=update['message'],
  2096. reply_to_update=True
  2097. )
  2098. elif 'callback_query' in update:
  2099. await self.answerCallbackQuery(
  2100. callback_query_id=update['id'],
  2101. text=remove_html_tags(self.maintenance_message[:45])
  2102. )
  2103. elif 'inline_query' in update:
  2104. await self.answer_inline_query(
  2105. update['inline_query']['id'],
  2106. self.maintenance_message,
  2107. cache_time=30,
  2108. is_personal=False,
  2109. update=update,
  2110. user_record=user_record
  2111. )
  2112. return
  2113. @classmethod
  2114. def set_class_authorization_denied_message(cls, message):
  2115. """Set class authorization denied message.
  2116. It will be returned if user is unauthorized to make a request.
  2117. """
  2118. cls._authorization_denied_message = message
  2119. def set_authorization_denied_message(self, message):
  2120. """Set instance authorization denied message.
  2121. If instance message is None, default class message is used.
  2122. """
  2123. self._authorization_denied_message = message
  2124. def set_authorization_function(self, authorization_function):
  2125. """Set a custom authorization_function.
  2126. It should evaluate True if user is authorized to perform a specific
  2127. action and False otherwise.
  2128. It should take update and role and return a Boolean.
  2129. Default authorization_function always evaluates True.
  2130. """
  2131. self.authorization_function = authorization_function
  2132. @classmethod
  2133. def set_class_unknown_command_message(cls, unknown_command_message):
  2134. """Set class unknown command message.
  2135. It will be returned if user sends an unknown command in private chat.
  2136. """
  2137. cls._unknown_command_message = unknown_command_message
  2138. def set_unknown_command_message(self, unknown_command_message):
  2139. """Set instance unknown command message.
  2140. It will be returned if user sends an unknown command in private chat.
  2141. If instance message is None, default class message is used.
  2142. """
  2143. self._unknown_command_message = unknown_command_message
  2144. def add_help_section(self, help_section):
  2145. """Add `help_section`."""
  2146. assert (
  2147. isinstance(help_section, dict)
  2148. and 'name' in help_section
  2149. and 'label' in help_section
  2150. and 'description' in help_section
  2151. ), "Invalid help section!"
  2152. if 'authorization_level' not in help_section:
  2153. help_section['authorization_level'] = 'admin'
  2154. self.messages['help_sections'][help_section['name']] = help_section
  2155. def command(self,
  2156. command: Union[str, Dict[str, str]],
  2157. aliases=None,
  2158. reply_keyboard_button=None,
  2159. show_in_keyboard=False, description="",
  2160. help_section=None,
  2161. authorization_level='admin',
  2162. language_labelled_commands: Dict[str, str] = None):
  2163. """Associate a bot command with a custom handler function.
  2164. Decorate command handlers like this:
  2165. ```
  2166. @bot.command('/my_command', ['Button'], True, "My command", 'user')
  2167. async def command_handler(bot, update, user_record, language):
  2168. return "Result"
  2169. ```
  2170. When a message text starts with `/command[@bot_name]`, or with an
  2171. alias, it gets passed to the decorated function.
  2172. `command` is the command name (with or without /). Language-labeled
  2173. commands are supported in the form of {'en': 'command', ...}
  2174. `aliases` is a list of aliases; each will call the command handler
  2175. function; the first alias will appear as button in
  2176. reply keyboard if `reply_keyboard_button` is not set.
  2177. `reply_keyboard_button` is a str or better dict of language-specific
  2178. strings to be shown in default keyboard.
  2179. `show_in_keyboard`, if True, makes a button for this command appear in
  2180. default keyboard.
  2181. `description` can be used to help users understand what `/command`
  2182. does.
  2183. `help_section` is a dict on which the corresponding help section is
  2184. built. It may provide multilanguage support and should be
  2185. structured as follows:
  2186. {
  2187. "label": { # It will be displayed as button label
  2188. 'en': "Label",
  2189. ...
  2190. },
  2191. "name": "section_name",
  2192. # If missing, `authorization_level` is used
  2193. "authorization_level": "everybody",
  2194. "description": {
  2195. 'en': "Description in English",
  2196. ...
  2197. },
  2198. }
  2199. `authorization_level` is the lowest authorization level needed to run
  2200. the command.
  2201. For advanced examples see `davtelepot.helper` or other modules
  2202. (suggestions, administration_tools, ...).
  2203. """
  2204. if language_labelled_commands is None:
  2205. language_labelled_commands = dict()
  2206. language_labelled_commands = {
  2207. key: val.strip('/').lower()
  2208. for key, val in language_labelled_commands.items()
  2209. }
  2210. # Handle language-labelled commands:
  2211. # choose one main command and add others to `aliases`
  2212. if isinstance(command, dict) and len(command) > 0:
  2213. language_labelled_commands = command.copy()
  2214. if 'main' in language_labelled_commands:
  2215. command = language_labelled_commands['main']
  2216. elif self.default_language in language_labelled_commands:
  2217. command = language_labelled_commands[self.default_language]
  2218. else:
  2219. for command in language_labelled_commands.values():
  2220. break
  2221. if aliases is None:
  2222. aliases = []
  2223. if not isinstance(command, str):
  2224. raise TypeError(f'Command `{command}` is not a string')
  2225. if isinstance(reply_keyboard_button, dict):
  2226. for button in reply_keyboard_button.values():
  2227. if button not in aliases:
  2228. aliases.append(button)
  2229. if not isinstance(aliases, list):
  2230. raise TypeError(f'Aliases is not a list: `{aliases}`')
  2231. if not all(
  2232. [
  2233. isinstance(alias, str)
  2234. for alias in aliases
  2235. ]
  2236. ):
  2237. raise TypeError(
  2238. f'Aliases {aliases} is not a list of strings'
  2239. )
  2240. if isinstance(help_section, dict):
  2241. if 'authorization_level' not in help_section:
  2242. help_section['authorization_level'] = authorization_level
  2243. self.add_help_section(help_section)
  2244. command = command.strip('/ ').lower()
  2245. def command_decorator(command_handler):
  2246. async def decorated_command_handler(bot, update, user_record, language=None):
  2247. logging.info(
  2248. f"Command `{command}@{bot.name}` called by "
  2249. f"`{update['from'] if 'from' in update else update['chat']}`"
  2250. )
  2251. if bot.authorization_function(
  2252. update=update,
  2253. user_record=user_record,
  2254. authorization_level=authorization_level
  2255. ):
  2256. # Pass supported arguments from locals() to command_handler
  2257. return await command_handler(
  2258. **{
  2259. name: argument
  2260. for name, argument in locals().items()
  2261. if name in inspect.signature(
  2262. command_handler
  2263. ).parameters
  2264. }
  2265. )
  2266. return dict(text=self.authorization_denied_message)
  2267. self.commands[command] = dict(
  2268. handler=decorated_command_handler,
  2269. description=description,
  2270. authorization_level=authorization_level,
  2271. language_labelled_commands=language_labelled_commands,
  2272. aliases=aliases
  2273. )
  2274. if type(description) is dict:
  2275. self.messages['commands'][command] = dict(
  2276. description=description
  2277. )
  2278. if aliases:
  2279. for alias in aliases:
  2280. if alias.startswith('/'):
  2281. self.commands[alias.strip('/ ').lower()] = dict(
  2282. handler=decorated_command_handler,
  2283. authorization_level=authorization_level
  2284. )
  2285. else:
  2286. self.command_aliases[alias] = decorated_command_handler
  2287. if show_in_keyboard and (aliases or reply_keyboard_button):
  2288. _reply_keyboard_button = reply_keyboard_button or aliases[0]
  2289. self.messages[
  2290. 'reply_keyboard_buttons'][
  2291. command] = _reply_keyboard_button
  2292. self.commands[command][
  2293. 'reply_keyboard_button'] = _reply_keyboard_button
  2294. return command_decorator
  2295. def parser(self, condition, description='', authorization_level='admin'):
  2296. """Define a text message parser.
  2297. Decorate command handlers like this:
  2298. ```
  2299. def custom_criteria(update):
  2300. return 'from' in update
  2301. @bot.parser(custom_criteria, authorization_level='user')
  2302. async def text_parser(bot, update, user_record, language):
  2303. return "Result"
  2304. ```
  2305. If condition evaluates True when run on a message text
  2306. (not starting with '/'), such decorated function gets
  2307. called on update.
  2308. Conditions of parsers are evaluated in order; when one is True,
  2309. others will be skipped.
  2310. `description` provides information about the parser.
  2311. `authorization_level` is the lowest authorization level needed to call
  2312. the parser.
  2313. """
  2314. if not callable(condition):
  2315. raise TypeError(
  2316. f'Condition {condition.__name__} is not a callable'
  2317. )
  2318. def parser_decorator(parser):
  2319. async def decorated_parser(bot, update, user_record, language=None):
  2320. logging.info(
  2321. f"Text message update matching condition "
  2322. f"`{condition.__name__}@{bot.name}` from "
  2323. f"`{update['from'] if 'from' in update else update['chat']}`"
  2324. )
  2325. if bot.authorization_function(
  2326. update=update,
  2327. user_record=user_record,
  2328. authorization_level=authorization_level
  2329. ):
  2330. # Pass supported arguments from locals() to parser
  2331. return await parser(
  2332. **{
  2333. name: arg
  2334. for name, arg in locals().items()
  2335. if name in inspect.signature(parser).parameters
  2336. }
  2337. )
  2338. return dict(text=bot.authorization_denied_message)
  2339. self.text_message_parsers[condition] = dict(
  2340. handler=decorated_parser,
  2341. description=description,
  2342. authorization_level=authorization_level,
  2343. )
  2344. return parser_decorator
  2345. def document_handler(self, condition, description='',
  2346. authorization_level='admin'):
  2347. """Decorator: define a handler for document updates matching `condition`.
  2348. You may provide a description and a minimum authorization level.
  2349. The first handler matching condition is called (other matching handlers
  2350. are ignored).
  2351. """
  2352. if not callable(condition):
  2353. raise TypeError(
  2354. f'Condition {condition.__name__} is not a callable'
  2355. )
  2356. def parser_decorator(parser):
  2357. async def decorated_parser(bot, update, user_record, language=None):
  2358. logging.info(
  2359. f"Document update matching condition "
  2360. f"`{condition.__name__}@{bot.name}` from "
  2361. f"`{update['from'] if 'from' in update else update['chat']}`"
  2362. )
  2363. if bot.authorization_function(
  2364. update=update,
  2365. user_record=user_record,
  2366. authorization_level=authorization_level
  2367. ):
  2368. # Pass supported arguments from locals() to parser
  2369. return await parser(
  2370. **{
  2371. name: arg
  2372. for name, arg in locals().items()
  2373. if name in inspect.signature(parser).parameters
  2374. }
  2375. )
  2376. return dict(text=bot.authorization_denied_message)
  2377. self.document_handlers[condition] = dict(
  2378. handler=decorated_parser,
  2379. description=description,
  2380. authorization_level=authorization_level,
  2381. )
  2382. return parser_decorator
  2383. def handler(self, update_type: str, condition: Callable[[dict], bool],
  2384. description: str = '',
  2385. authorization_level: str = 'admin'):
  2386. """Decorator: define a handler for updates matching `condition`.
  2387. You may provide a description and a minimum authorization level.
  2388. The first handler matching condition is called (other matching handlers
  2389. are ignored).
  2390. """
  2391. if not callable(condition):
  2392. raise TypeError(
  2393. f'Condition {condition.__name__} is not a callable'
  2394. )
  2395. def parser_decorator(parser):
  2396. async def decorated_parser(bot, update, user_record, language=None):
  2397. logging.info(
  2398. f"{update_type} matching condition "
  2399. f"`{condition.__name__}@{bot.name}` from "
  2400. f"`{update['from'] if 'from' in update else update['chat']}`"
  2401. )
  2402. if bot.authorization_function(
  2403. update=update,
  2404. user_record=user_record,
  2405. authorization_level=authorization_level
  2406. ):
  2407. # Pass supported arguments from locals() to parser
  2408. return await parser(
  2409. **{
  2410. name: arg
  2411. for name, arg in locals().items()
  2412. if name in inspect.signature(parser).parameters
  2413. }
  2414. )
  2415. return dict(text=bot.authorization_denied_message)
  2416. if update_type not in self.handlers:
  2417. self.handlers[update_type] = OrderedDict()
  2418. self.handlers[update_type][condition] = dict(
  2419. handler=decorated_parser,
  2420. description=description,
  2421. authorization_level=authorization_level,
  2422. )
  2423. return parser_decorator
  2424. def set_command(self, command, handler, aliases=None,
  2425. reply_keyboard_button=None, show_in_keyboard=False,
  2426. description="",
  2427. authorization_level='admin'):
  2428. """Associate a `command` with a `handler`.
  2429. When a message text starts with `/command[@bot_name]`, or with an
  2430. alias, it gets passed to the decorated function.
  2431. `command` is the command name (with or without /)
  2432. `handler` is the function to be called on update objects.
  2433. `aliases` is a list of aliases; each will call the command handler
  2434. function; the first alias will appear as button in
  2435. reply keyboard if `reply_keyboard_button` is not set.
  2436. `reply_keyboard_button` is a str or better dict of language-specific
  2437. strings to be shown in default keyboard.
  2438. `show_in_keyboard`, if True, makes a button for this command appear in
  2439. default keyboard.
  2440. `description` is a description and can be used to help users understand
  2441. what `/command` does.
  2442. `authorization_level` is the lowest authorization level needed to run
  2443. the command.
  2444. """
  2445. if not callable(handler):
  2446. raise TypeError(f'Handler `{handler}` is not callable.')
  2447. return self.command(
  2448. command=command, aliases=aliases,
  2449. reply_keyboard_button=reply_keyboard_button,
  2450. show_in_keyboard=show_in_keyboard, description=description,
  2451. authorization_level=authorization_level
  2452. )(handler)
  2453. def button(self, prefix, separator=None, description='',
  2454. authorization_level='admin'):
  2455. """Associate a bot button `prefix` with a handler.
  2456. When a callback data text starts with `prefix`, the associated handler
  2457. is called upon the update.
  2458. Decorate button handlers like this:
  2459. ```
  2460. @bot.button('a_prefix:///', description="A button",
  2461. authorization_level='user')
  2462. async def button_handler(bot, update, user_record, language, data):
  2463. return "Result"
  2464. ```
  2465. `separator` will be used to parse callback data received when a button
  2466. starting with `prefix` will be pressed.
  2467. `description` contains information about the button.
  2468. `authorization_level` is the lowest authorization level needed to
  2469. be allowed to push the button.
  2470. """
  2471. if not isinstance(prefix, str):
  2472. raise TypeError(
  2473. f'Inline button callback_data {prefix} is not a string'
  2474. )
  2475. def button_decorator(handler):
  2476. async def decorated_button_handler(bot, update, user_record, language=None):
  2477. logging.info(
  2478. f"Button `{update['data']}`@{bot.name} pressed by "
  2479. f"`{update['from']}`"
  2480. )
  2481. if bot.authorization_function(
  2482. update=update,
  2483. user_record=user_record,
  2484. authorization_level=authorization_level
  2485. ):
  2486. # Remove `prefix` from `data`
  2487. data = extract(update['data'], prefix)
  2488. # If a specific separator or default separator is set,
  2489. # use it to split `data` string in a list.
  2490. # Cast numeric `data` elements to `int`.
  2491. _separator = separator or self.callback_data_separator
  2492. if _separator:
  2493. data = [
  2494. int(element) if element.isnumeric()
  2495. else element
  2496. for element in data.split(_separator)
  2497. ]
  2498. # Pass supported arguments from locals() to handler
  2499. return await handler(
  2500. **{
  2501. name: argument
  2502. for name, argument in locals().items()
  2503. if name in inspect.signature(handler).parameters
  2504. }
  2505. )
  2506. return bot.authorization_denied_message
  2507. self.callback_handlers[prefix] = dict(
  2508. handler=decorated_button_handler,
  2509. description=description,
  2510. authorization_level=authorization_level
  2511. )
  2512. return button_decorator
  2513. def query(self, condition, description='', authorization_level='admin'):
  2514. """Define an inline query.
  2515. Decorator: `@bot.query(example)`
  2516. When an inline query matches the `condition` function,
  2517. decorated function is called and passed the query update object
  2518. as argument.
  2519. `description` is a description
  2520. `authorization_level` is the lowest authorization level needed to run
  2521. the command
  2522. """
  2523. if not callable(condition):
  2524. raise TypeError(
  2525. 'Condition {c} is not a callable'.format(
  2526. c=condition.__name__
  2527. )
  2528. )
  2529. def query_decorator(handler):
  2530. async def decorated_query_handler(bot, update, user_record, language=None):
  2531. logging.info(
  2532. f"Inline query matching condition "
  2533. f"`{condition.__name__}@{bot.name}` from "
  2534. f"`{update['from']}`"
  2535. )
  2536. if self.authorization_function(
  2537. update=update,
  2538. user_record=user_record,
  2539. authorization_level=authorization_level
  2540. ):
  2541. # Pass supported arguments from locals() to handler
  2542. return await handler(
  2543. **{
  2544. name: argument
  2545. for name, argument in locals().items()
  2546. if name in inspect.signature(handler).parameters
  2547. }
  2548. )
  2549. return self.authorization_denied_message
  2550. self.inline_query_handlers[condition] = dict(
  2551. handler=decorated_query_handler,
  2552. description=description,
  2553. authorization_level=authorization_level
  2554. )
  2555. return query_decorator
  2556. def set_chat_id_getter(self, getter):
  2557. """Set chat_id getter.
  2558. It must be a function that takes an update and returns the proper
  2559. chat_id.
  2560. """
  2561. assert callable(getter), "Chat id getter must be a function!"
  2562. self.get_chat_id = getter
  2563. @staticmethod
  2564. def get_user_identifier(user_id=None, update=None):
  2565. """Get telegram id of user given an update.
  2566. Result itself may be passed as either parameter (for backward
  2567. compatibility).
  2568. """
  2569. identifier = user_id or update
  2570. assert identifier is not None, (
  2571. "Provide a user_id or update object to get a user identifier."
  2572. )
  2573. if (
  2574. isinstance(identifier, dict)
  2575. and 'message' in identifier
  2576. and 'from' not in identifier
  2577. ):
  2578. identifier = identifier['message']
  2579. if isinstance(identifier, dict) and 'from' in identifier:
  2580. identifier = identifier['from']['id']
  2581. assert type(identifier) is int, (
  2582. f"Unable to find a user identifier. Got `{identifier}`"
  2583. )
  2584. return identifier
  2585. @staticmethod
  2586. def get_message_identifier(update=None):
  2587. """Get a message identifier dictionary to edit `update`.
  2588. Pass the result as keyword arguments to `edit...` API methods.
  2589. """
  2590. if update is None:
  2591. update = dict()
  2592. if 'message' in update:
  2593. update = update['message']
  2594. if 'chat' in update and 'message_id' in update:
  2595. return dict(
  2596. chat_id=update['chat']['id'],
  2597. message_id=update['message_id']
  2598. )
  2599. elif 'inline_message_id' in update:
  2600. return dict(
  2601. inline_message_id=update['inline_message_id']
  2602. )
  2603. def set_individual_text_message_handler(self, handler,
  2604. update=None, user_id=None):
  2605. """Set a custom text message handler for the user.
  2606. Any text message update from the user will be handled by this custom
  2607. handler instead of default handlers for commands, aliases and text.
  2608. Custom handlers last one single use, but they can call this method and
  2609. set themselves as next custom text message handler.
  2610. """
  2611. identifier = self.get_user_identifier(
  2612. user_id=user_id,
  2613. update=update
  2614. )
  2615. assert callable(handler), (f"Handler `{handler.name}` is not "
  2616. "callable. Custom text message handler "
  2617. "could not be set.")
  2618. self.individual_text_message_handlers[identifier] = handler
  2619. return
  2620. def remove_individual_text_message_handler(self,
  2621. update=None, user_id=None):
  2622. """Remove a custom text message handler for the user.
  2623. Any text message update from the user will be handled by default
  2624. handlers for commands, aliases and text.
  2625. """
  2626. identifier = self.get_user_identifier(
  2627. user_id=user_id,
  2628. update=update
  2629. )
  2630. if identifier in self.individual_text_message_handlers:
  2631. del self.individual_text_message_handlers[identifier]
  2632. return
  2633. def set_individual_location_handler(self, handler,
  2634. update=None, user_id=None):
  2635. """Set a custom location handler for the user.
  2636. Any location update from the user will be handled by this custom
  2637. handler instead of default handlers for locations.
  2638. Custom handlers last one single use, but they can call this method and
  2639. set themselves as next custom handler.
  2640. """
  2641. identifier = self.get_user_identifier(
  2642. user_id=user_id,
  2643. update=update
  2644. )
  2645. assert callable(handler), (f"Handler `{handler.name}` is not "
  2646. "callable. Custom location handler "
  2647. "could not be set.")
  2648. self.individual_location_handlers[identifier] = handler
  2649. return
  2650. def remove_individual_location_handler(self,
  2651. update=None, user_id=None):
  2652. """Remove a custom location handler for the user.
  2653. Any location message update from the user will be handled by default
  2654. handlers for locations.
  2655. """
  2656. identifier = self.get_user_identifier(
  2657. user_id=user_id,
  2658. update=update
  2659. )
  2660. if identifier in self.individual_location_handlers:
  2661. del self.individual_location_handlers[identifier]
  2662. return
  2663. def set_individual_document_handler(self, handler,
  2664. update=None, user_id=None):
  2665. """Set a custom document handler for the user.
  2666. Any document update from the user will be handled by this custom
  2667. handler instead of default handlers for documents.
  2668. Custom handlers last one single use, but they can call this method and
  2669. set themselves as next custom document handler.
  2670. """
  2671. identifier = self.get_user_identifier(
  2672. user_id=user_id,
  2673. update=update
  2674. )
  2675. assert callable(handler), (f"Handler `{handler.name}` is not "
  2676. "callable. Custom document handler "
  2677. "could not be set.")
  2678. self.individual_document_message_handlers[identifier] = handler
  2679. return
  2680. def remove_individual_document_handler(self,
  2681. update=None, user_id=None):
  2682. """Remove a custom document handler for the user.
  2683. Any document update from the user will be handled by default
  2684. handlers for documents.
  2685. """
  2686. identifier = self.get_user_identifier(
  2687. user_id=user_id,
  2688. update=update
  2689. )
  2690. if identifier in self.individual_document_message_handlers:
  2691. del self.individual_document_message_handlers[identifier]
  2692. return
  2693. def set_individual_voice_handler(self, handler,
  2694. update=None, user_id=None):
  2695. """Set a custom voice message handler for the user.
  2696. Any voice message update from the user will be handled by this custom
  2697. handler instead of default handlers for voice messages.
  2698. Custom handlers last one single use, but they can call this method and
  2699. set themselves as next custom handler.
  2700. """
  2701. identifier = self.get_user_identifier(
  2702. user_id=user_id,
  2703. update=update
  2704. )
  2705. assert callable(handler), (f"Handler `{handler.name}` is not "
  2706. "callable. Custom voice handler "
  2707. "could not be set.")
  2708. self.individual_voice_handlers[identifier] = handler
  2709. return
  2710. def remove_individual_voice_handler(self,
  2711. update=None, user_id=None):
  2712. """Remove a custom voice handler for the user.
  2713. Any voice message update from the user will be handled by default
  2714. handlers for voice messages.
  2715. """
  2716. identifier = self.get_user_identifier(
  2717. user_id=user_id,
  2718. update=update
  2719. )
  2720. if identifier in self.individual_voice_handlers:
  2721. del self.individual_voice_handlers[identifier]
  2722. return
  2723. def set_individual_handler(self, handler, update_type: str,
  2724. update=None, user_id=None,):
  2725. """Set a custom `update_type` handler for the user.
  2726. Any update of given type from the user will be handled by this custom
  2727. handler instead of default handler.
  2728. Custom handlers last one single use, but they can call this method and
  2729. set themselves as next custom handler.
  2730. """
  2731. identifier = self.get_user_identifier(
  2732. user_id=user_id,
  2733. update=update
  2734. )
  2735. assert callable(handler), (f"Handler `{handler.name}` is not "
  2736. "callable. Custom handler "
  2737. "could not be set.")
  2738. if update_type not in self.individual_handlers:
  2739. self.individual_handlers[update_type] = dict()
  2740. self.individual_handlers[update_type][identifier] = handler
  2741. return
  2742. def remove_individual_handler(self, update_type: str,
  2743. update=None, user_id=None):
  2744. """Remove a custom `update_type` handler for the user.
  2745. Any update of given type from the user will be handled by default
  2746. handler for its type.
  2747. """
  2748. identifier = self.get_user_identifier(
  2749. user_id=user_id,
  2750. update=update
  2751. )
  2752. if (
  2753. update_type in self.individual_handlers
  2754. and identifier in self.individual_handlers[update_type]
  2755. ):
  2756. del self.individual_handlers[update_type][identifier]
  2757. return
  2758. def set_individual_contact_message_handler(self, handler,
  2759. update: dict,
  2760. user_id: OrderedDict):
  2761. return self.set_individual_handler(handler=handler,
  2762. update_type='contact',
  2763. update=update,
  2764. user_id=user_id)
  2765. def remove_individual_contact_handler(self, update=None, user_id=None):
  2766. return self.remove_individual_handler(update_type='contact',
  2767. update=update,
  2768. user_id=user_id)
  2769. def set_placeholder(self, chat_id,
  2770. text=None, sent_message=None, timeout=1):
  2771. """Set a placeholder chat action or text message.
  2772. If it takes the bot more than `timeout` to answer, send a placeholder
  2773. message or a `is typing` chat action.
  2774. `timeout` may be expressed in seconds (int) or datetime.timedelta
  2775. This method returns a `request_id`. When the calling function has
  2776. performed its task, it must set to 1 the value of
  2777. `self.placeholder_requests[request_id]`.
  2778. If this value is still 0 at `timeout`, the placeholder is sent.
  2779. Otherwise, no action is performed.
  2780. """
  2781. request_id = len(self.placeholder_requests)
  2782. self.placeholder_requests[request_id] = 0
  2783. asyncio.ensure_future(
  2784. self.placeholder_effector(
  2785. request_id=request_id,
  2786. timeout=timeout,
  2787. chat_id=chat_id,
  2788. sent_message=sent_message,
  2789. text=text
  2790. )
  2791. )
  2792. return request_id
  2793. async def placeholder_effector(self, request_id, timeout, chat_id,
  2794. sent_message=None, text=None):
  2795. """Send a placeholder chat action or text message if needed.
  2796. If it takes the bot more than `timeout` to answer, send a placeholder
  2797. message or a `is typing` chat action.
  2798. `timeout` may be expressed in seconds (int) or datetime.timedelta
  2799. """
  2800. if type(timeout) is datetime.timedelta:
  2801. timeout = timeout.total_seconds()
  2802. await asyncio.sleep(timeout)
  2803. if not self.placeholder_requests[request_id]:
  2804. if sent_message and text:
  2805. await self.edit_message_text(
  2806. update=sent_message,
  2807. text=text,
  2808. )
  2809. else:
  2810. await self.sendChatAction(
  2811. chat_id=chat_id,
  2812. action='typing'
  2813. )
  2814. return
  2815. async def webhook_feeder(self, request):
  2816. """Handle incoming HTTP `request`s.
  2817. Get data, feed webhook and return and OK message.
  2818. """
  2819. update = await request.json()
  2820. asyncio.ensure_future(
  2821. self.route_update(update)
  2822. )
  2823. return web.Response(
  2824. body='OK'.encode('utf-8')
  2825. )
  2826. async def get_me(self):
  2827. """Get bot information.
  2828. Restart bots if bot can't be got.
  2829. """
  2830. try:
  2831. me = await self.getMe()
  2832. if isinstance(me, Exception):
  2833. raise me
  2834. elif me is None:
  2835. raise Exception('getMe returned None')
  2836. self._name = me["username"]
  2837. self._telegram_id = me['id']
  2838. except Exception as e:
  2839. logging.error(
  2840. f"API getMe method failed, information about this bot could "
  2841. f"not be retrieved. Restarting in 5 minutes...\n\n"
  2842. f"Error information:\n{e}"
  2843. )
  2844. await asyncio.sleep(5*60)
  2845. self.__class__.stop(
  2846. message="Information about this bot could not be retrieved.\n"
  2847. "Restarting...",
  2848. final_state=65
  2849. )
  2850. def setup(self):
  2851. """Make bot ask for updates and handle responses."""
  2852. if not self.webhook_url:
  2853. asyncio.ensure_future(self.get_updates())
  2854. else:
  2855. asyncio.ensure_future(self.set_webhook())
  2856. self.__class__.app.router.add_route(
  2857. 'POST', self.webhook_local_address, self.webhook_feeder
  2858. )
  2859. asyncio.ensure_future(self.update_users())
  2860. async def close_sessions(self):
  2861. """Close open sessions."""
  2862. for session_name, session in self.sessions.items():
  2863. if not session.closed:
  2864. await session.close()
  2865. async def set_webhook(self, url=None, certificate=None,
  2866. max_connections=None, allowed_updates=None):
  2867. """Set a webhook if token is valid."""
  2868. # Return if token is invalid
  2869. await self.get_me()
  2870. if self.name is None:
  2871. return
  2872. if allowed_updates is None:
  2873. allowed_updates = []
  2874. if certificate is None:
  2875. certificate = self.certificate
  2876. if max_connections is None:
  2877. max_connections = self.max_connections
  2878. if url is None:
  2879. url = self.webhook_url
  2880. webhook_was_set = await self.setWebhook(
  2881. url=url, certificate=certificate, max_connections=max_connections,
  2882. allowed_updates=allowed_updates
  2883. ) # `setWebhook` API method returns `True` on success
  2884. webhook_information = await self.getWebhookInfo()
  2885. webhook_information['url'] = webhook_information['url'].replace(
  2886. self.token, "<BOT_TOKEN>"
  2887. ).replace(
  2888. self.session_token, "<SESSION_TOKEN>"
  2889. )
  2890. if webhook_was_set:
  2891. logging.info(
  2892. f"Webhook was set correctly.\n"
  2893. f"Webhook information: {webhook_information}"
  2894. )
  2895. else:
  2896. logging.error(
  2897. f"Failed to set webhook!\n"
  2898. f"Webhook information: {webhook_information}"
  2899. )
  2900. async def get_updates(self, timeout=30, limit=100, allowed_updates=None,
  2901. error_cooldown=10):
  2902. """Get updates using long polling.
  2903. timeout : int
  2904. Timeout set for Telegram servers. Make sure that connection timeout
  2905. is greater than `timeout`.
  2906. limit : int (1 - 100)
  2907. Max number of updates to be retrieved.
  2908. allowed_updates : List(str)
  2909. List of update types to be retrieved.
  2910. Empty list to allow all updates.
  2911. None to fallback to class default.
  2912. """
  2913. # Return if token is invalid
  2914. await self.get_me()
  2915. if self.name is None:
  2916. return
  2917. # Set custom list of allowed updates or fallback to class default list
  2918. if allowed_updates is None:
  2919. allowed_updates = self.allowed_updates
  2920. await self.deleteWebhook() # Remove eventually active webhook
  2921. update = None # Do not update offset if no update is received
  2922. while True:
  2923. updates = await self.getUpdates(
  2924. offset=self._offset,
  2925. timeout=timeout,
  2926. limit=limit,
  2927. allowed_updates=allowed_updates
  2928. )
  2929. if updates is None:
  2930. continue
  2931. elif isinstance(updates, TelegramError):
  2932. logging.error(
  2933. f"Waiting {error_cooldown} seconds before trying again..."
  2934. )
  2935. await asyncio.sleep(error_cooldown)
  2936. continue
  2937. elif isinstance(updates, Exception):
  2938. logging.error(
  2939. "Unexpected exception. "
  2940. f"Waiting {error_cooldown} seconds before trying again..."
  2941. )
  2942. await asyncio.sleep(error_cooldown)
  2943. continue
  2944. for update in updates:
  2945. asyncio.ensure_future(self.route_update(update))
  2946. if update is not None:
  2947. self._offset = update['update_id'] + 1
  2948. async def update_users(self, interval=60):
  2949. """Every `interval` seconds, store news about bot users.
  2950. Compare `update['from']` data with records in `users` table and keep
  2951. track of differences in `users_history` table.
  2952. """
  2953. while 1:
  2954. await asyncio.sleep(interval)
  2955. users_profile_pictures_to_update = OrderedDict()
  2956. now = datetime.datetime.now()
  2957. # Iterate through a copy since asyncio.sleep(0) is awaited at each
  2958. # cycle iteration.
  2959. for telegram_id, user in self.recent_users.copy().items():
  2960. new_record = dict()
  2961. with self.db as db:
  2962. user_record = db['users'].find_one(telegram_id=telegram_id)
  2963. user_picture_record = db['user_profile_photos'].find_one(
  2964. user_id=user_record['id'],
  2965. order_by=['-update_datetime']
  2966. )
  2967. # If user profile picture needs to be updated, add it to the OD
  2968. if (user_picture_record is None
  2969. or user_picture_record['update_datetime']
  2970. < now - datetime.timedelta(days=1)):
  2971. users_profile_pictures_to_update[telegram_id] = user_picture_record
  2972. for key in ('first_name', 'last_name',
  2973. 'username', 'language_code', ):
  2974. new_record[key] = (user[key] if key in user else None)
  2975. if (
  2976. (
  2977. key not in user_record
  2978. or new_record[key] != user_record[key]
  2979. )
  2980. # Exclude fake updates
  2981. and 'notes' not in user
  2982. ):
  2983. db['users_history'].insert(
  2984. dict(
  2985. until=datetime.datetime.now(),
  2986. user_id=user_record['id'],
  2987. field=key,
  2988. value=(
  2989. user_record[key]
  2990. if key in user_record
  2991. else None
  2992. )
  2993. )
  2994. )
  2995. db['users'].update(
  2996. {
  2997. 'id': user_record['id'],
  2998. key: new_record[key]
  2999. },
  3000. ['id'],
  3001. ensure=True
  3002. )
  3003. if telegram_id in self.recent_users:
  3004. del self.recent_users[telegram_id]
  3005. await asyncio.sleep(0)
  3006. # Update user profile pictures
  3007. for telegram_id, user_picture_record in users_profile_pictures_to_update.items():
  3008. try:
  3009. user_profile_photos = await self.getUserProfilePhotos(
  3010. user_id=telegram_id,
  3011. offset=0,
  3012. limit=1
  3013. )
  3014. if (user_profile_photos is not None
  3015. and 'photos' in user_profile_photos
  3016. and len(user_profile_photos['photos'])):
  3017. current_photo = user_profile_photos['photos'][0][0]
  3018. if (
  3019. user_picture_record is None
  3020. or (
  3021. isinstance(user_picture_record, dict)
  3022. and current_photo['file_id']
  3023. != user_picture_record['telegram_file_id']
  3024. )
  3025. ):
  3026. db['user_profile_photos'].insert(dict(
  3027. user_id=user_record['id'],
  3028. telegram_file_id=current_photo['file_id'],
  3029. update_datetime=now
  3030. ))
  3031. else:
  3032. db['user_profile_photos'].upsert(
  3033. dict(
  3034. user_id=user_record['id'],
  3035. telegram_file_id=current_photo['file_id'],
  3036. update_datetime=now
  3037. ),
  3038. ['user_id', 'telegram_file_id']
  3039. )
  3040. except Exception as e:
  3041. logging.error(e)
  3042. def get_user_record(self, update):
  3043. """Get user_record of update sender.
  3044. If user is unknown add them.
  3045. If update has no `from` field, return None.
  3046. If user data changed, ensure that this event gets stored.
  3047. """
  3048. if 'from' not in update or 'id' not in update['from']:
  3049. return
  3050. telegram_id = update['from']['id']
  3051. with self.db as db:
  3052. user_record = db['users'].find_one(
  3053. telegram_id=telegram_id
  3054. )
  3055. if user_record is None:
  3056. new_user = dict(
  3057. telegram_id=telegram_id,
  3058. privileges=100,
  3059. selected_language_code=None
  3060. )
  3061. for key in [
  3062. 'first_name',
  3063. 'last_name',
  3064. 'username',
  3065. 'language_code'
  3066. ]:
  3067. new_user[key] = (
  3068. update['from'][key]
  3069. if key in update['from']
  3070. else None
  3071. )
  3072. db['users'].insert(new_user)
  3073. user_record = db['users'].find_one(
  3074. telegram_id=telegram_id
  3075. )
  3076. elif (
  3077. telegram_id not in self.recent_users
  3078. and 'notes' not in update['from'] # Exclude fake updates
  3079. ):
  3080. self.recent_users[telegram_id] = update['from']
  3081. return user_record
  3082. def set_router(self, event, handler):
  3083. """Set `handler` as router for `event`."""
  3084. self.routing_table[event] = handler
  3085. def set_message_handler(self, message_type: str, handler: Callable):
  3086. """Set `handler` for `message_type`."""
  3087. self.message_handlers[message_type] = handler
  3088. async def route_update(self, raw_update):
  3089. """Pass `update` to proper method.
  3090. Update objects have two keys:
  3091. - `update_id` (which is used as offset while retrieving new updates)
  3092. - One and only one of the following
  3093. `message`
  3094. `edited_message`
  3095. `channel_post`
  3096. `edited_channel_post`
  3097. `inline_query`
  3098. `chosen_inline_result`
  3099. `callback_query`
  3100. `shipping_query`
  3101. `pre_checkout_query`
  3102. `poll`
  3103. """
  3104. if (
  3105. self.under_maintenance
  3106. and not self.is_allowed_during_maintenance(raw_update)
  3107. ):
  3108. return await self.handle_update_during_maintenance(raw_update)
  3109. for key in self.routing_table:
  3110. if key in raw_update:
  3111. update = raw_update[key]
  3112. update['update_id'] = raw_update['update_id']
  3113. user_record = self.get_user_record(update=update)
  3114. language = self.get_language(update=update,
  3115. user_record=user_record)
  3116. bot = self
  3117. return await self.routing_table[key](**{
  3118. name: argument
  3119. for name, argument in locals().items()
  3120. if name in inspect.signature(
  3121. self.routing_table[key]
  3122. ).parameters
  3123. })
  3124. logging.error(f"Unknown type of update.\n{raw_update}")
  3125. def additional_task(self, when='BEFORE', *args, **kwargs):
  3126. """Add a task before at app start or cleanup.
  3127. Decorate an async function to have it awaited `BEFORE` or `AFTER` main
  3128. loop.
  3129. """
  3130. when = when[0].lower()
  3131. def additional_task_decorator(task):
  3132. if when == 'b':
  3133. self.preliminary_tasks.append(task(*args, **kwargs))
  3134. elif when == 'a':
  3135. self.final_tasks.append(task(*args, **kwargs))
  3136. return additional_task_decorator
  3137. @classmethod
  3138. async def start_app(cls):
  3139. """Start running `aiohttp.web.Application`.
  3140. It will route webhook-received updates and other custom paths.
  3141. """
  3142. assert cls.local_host is not None, "Invalid local host"
  3143. assert cls.port is not None, "Invalid port"
  3144. cls.runner = web.AppRunner(cls.app)
  3145. await cls.runner.setup()
  3146. cls.server = web.TCPSite(cls.runner, cls.local_host, cls.port)
  3147. try:
  3148. await cls.server.start()
  3149. except OSError as e:
  3150. logging.error(e)
  3151. raise KeyboardInterrupt("Unable to start web app.")
  3152. logging.info(f"App running at http://{cls.local_host}:{cls.port}")
  3153. @classmethod
  3154. async def stop_app(cls):
  3155. """Close bot sessions and cleanup."""
  3156. for bot in cls.bots:
  3157. await asyncio.gather(
  3158. *bot.final_tasks
  3159. )
  3160. await bot.close_sessions()
  3161. await cls.runner.cleanup()
  3162. @classmethod
  3163. def stop(cls, message, final_state=0):
  3164. """Log a final `message`, stop loop and set exiting `code`.
  3165. All bots and the web app will be terminated gracefully.
  3166. The final state may be retrieved to get information about what stopped
  3167. the bots.
  3168. """
  3169. logging.info(message)
  3170. cls.final_state = final_state
  3171. cls.loop.stop()
  3172. return
  3173. @classmethod
  3174. def run(cls, local_host=None, port=None):
  3175. """Run aiohttp web app and all Bot instances.
  3176. Each bot will receive updates via long polling or webhook according to
  3177. its initialization parameters.
  3178. A single aiohttp.web.Application instance will be run (cls.app) on
  3179. local_host:port and it may serve custom-defined routes as well.
  3180. """
  3181. if local_host is not None:
  3182. cls.local_host = local_host
  3183. if port is not None:
  3184. cls.port = port
  3185. try:
  3186. cls.loop.run_until_complete(
  3187. asyncio.gather(
  3188. *[
  3189. preliminary_task
  3190. for bot in cls.bots
  3191. for preliminary_task in bot.preliminary_tasks
  3192. ]
  3193. )
  3194. )
  3195. except Exception as e:
  3196. logging.error(f"{e}", exc_info=True)
  3197. for bot in cls.bots:
  3198. bot.setup()
  3199. asyncio.ensure_future(cls.start_app())
  3200. try:
  3201. cls.loop.run_forever()
  3202. except KeyboardInterrupt:
  3203. logging.info("Stopped by KeyboardInterrupt")
  3204. except Exception as e:
  3205. logging.error(f"{e}", exc_info=True)
  3206. finally:
  3207. cls.loop.run_until_complete(cls.stop_app())
  3208. return cls.final_state
  3209. def set_role_class(self, role):
  3210. """Set a Role class for bot.
  3211. `role` must be an instance of `authorization.Role`.
  3212. """
  3213. self.Role = role