Queer European MD passionate about IT

bot.py 138 KB

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