Queer European MD passionate about IT

bot.py 143 KB

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