Queer European MD passionate about IT

bot.py 140 KB

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