Queer European MD passionate about IT

bot.py 132 KB

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