Queer European MD passionate about IT

bot.py 127 KB

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