Queer European MD passionate about IT

bot.py 138 KB

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