Queer European MD passionate about IT

bot.py 138 KB

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