Queer European MD passionate about IT

bot.py 135 KB

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