Queer European MD passionate about IT

bot.py 135 KB

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