Queer European MD passionate about IT

custombot.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  1. """Subclass of third party telepot.aio.Bot, providing the following features.
  2. - It prevents hitting Telegram flood limits by waiting
  3. between text and photo messages.
  4. - It provides command, parser, button and other decorators to associate
  5. common Telegram actions with custom handlers.
  6. - It supports multiple bots running in the same script
  7. and allows communications between them
  8. as well as complete independency from each other.
  9. - Each bot is associated with a sqlite database
  10. using dataset, a third party library.
  11. Please note that you need Python3.5+ to run async code
  12. Check requirements.txt for third party dependencies.
  13. """
  14. # Standard library modules
  15. import asyncio
  16. import datetime
  17. import io
  18. import logging
  19. import os
  20. # Third party modules
  21. import dataset
  22. from davteutil.utilities import (
  23. Gettable, escape_html_chars, get_cleaned_text,
  24. line_drawing_unordered_list, make_lines_of_buttons, markdown_check, MyOD,
  25. pick_most_similar_from_list, remove_html_tags, sleep_until
  26. )
  27. import telepot
  28. import telepot.aio
  29. def split_text_gracefully(text, limit, parse_mode):
  30. r"""Split text if it hits telegram limits for text messages.
  31. Split at `\n` if possible.
  32. Add a `[...]` at the end and beginning of split messages,
  33. with proper code markdown.
  34. """
  35. text = text.split("\n")[::-1]
  36. result = []
  37. while len(text) > 0:
  38. temp = []
  39. while len(text) > 0 and len("\n".join(temp + [text[-1]])) < limit:
  40. temp.append(text.pop())
  41. if len(temp) == 0:
  42. temp.append(text[-1][:limit])
  43. text[-1] = text[-1][limit:]
  44. result.append("\n".join(temp))
  45. if len(result) > 1:
  46. for i in range(1, len(result)):
  47. result[i] = "{tag[0]}[...]{tag[1]}\n{text}".format(
  48. tag=(
  49. ('`', '`') if parse_mode == 'Markdown'
  50. else ('<code>', '</code>') if parse_mode.lower() == 'html'
  51. else ('', '')
  52. ),
  53. text=result[i]
  54. )
  55. result[i-1] = "{text}\n{tag[0]}[...]{tag[1]}".format(
  56. tag=(
  57. ('`', '`') if parse_mode == 'Markdown'
  58. else ('<code>', '</code>') if parse_mode.lower() == 'html'
  59. else ('', '')
  60. ),
  61. text=result[i-1]
  62. )
  63. return result
  64. def make_inline_query_answer(answer):
  65. """Return an article-type answer to inline query.
  66. Takes either a string or a dictionary and returns a list.
  67. """
  68. if type(answer) is str:
  69. answer = dict(
  70. type='article',
  71. id=0,
  72. title=remove_html_tags(answer),
  73. input_message_content=dict(
  74. message_text=answer,
  75. parse_mode='HTML'
  76. )
  77. )
  78. if type(answer) is dict:
  79. answer = [answer]
  80. return answer
  81. class Bot(telepot.aio.Bot, Gettable):
  82. """telepot.aio.Bot (async Telegram bot framework) convenient subclass.
  83. === General functioning ===
  84. - While Bot.run() coroutine is executed, HTTP get requests are made
  85. to Telegram servers asking for new messages for each Bot instance.
  86. - Each message causes the proper Bot instance method coroutine
  87. to be awaited, according to its flavour (see routing_table)
  88. -- For example, chat messages cause `Bot().on_chat_message(message)`
  89. to be awaited.
  90. - This even-processing coroutine ensures the proper handling function
  91. a future and returns.
  92. -- That means that simpler tasks are completed before slower ones,
  93. since handling functions are not awaited but scheduled
  94. by `asyncio.ensure_future(handling_function(...))`
  95. -- For example, chat text messages are handled by
  96. `handle_text_message`, which looks for the proper function
  97. to elaborate the request (in bot's commands and parsers)
  98. - The handling function evaluates an answer, depending on the message
  99. content, and eventually provides a reply
  100. -- For example, `handle_text_message` sends its
  101. answer via `send_message`
  102. - All Bot.instances run simultaneously and faster requests
  103. are completed earlier.
  104. - All uncaught events are ignored.
  105. """
  106. instances = {}
  107. stop = False
  108. # Cooldown time between sent messages, to prevent hitting
  109. # Telegram flood limits
  110. # Current limits: 30 total messages sent per second,
  111. # 1 message per second per chat, 20 messages per minute per group
  112. COOLDOWN_TIME_ABSOLUTE = datetime.timedelta(seconds=1/30)
  113. COOLDOWN_TIME_PER_CHAT = datetime.timedelta(seconds=1)
  114. MAX_GROUP_MESSAGES_PER_MINUTE = 20
  115. # Max length of text field for a Telegram message (UTF-8 text)
  116. TELEGRAM_MESSAGES_MAX_LEN = 4096
  117. _path = '.'
  118. _unauthorized_message = None
  119. _unknown_command_message = None
  120. _maintenance_message = None
  121. _default_inline_query_answer = [
  122. dict(
  123. type='article',
  124. id=0,
  125. title="I cannot answer this query, sorry",
  126. input_message_content=dict(
  127. message_text="I'm sorry "
  128. "but I could not find an answer for your query."
  129. )
  130. )
  131. ]
  132. def __init__(self, token, db_name=None):
  133. """Instantiate Bot instance, given a token and a db name."""
  134. super().__init__(token)
  135. self.routing_table = {
  136. 'chat': self.on_chat_message,
  137. 'inline_query': self.on_inline_query,
  138. 'chosen_inline_result': self.on_chosen_inline_result,
  139. 'callback_query': self.on_callback_query
  140. }
  141. self.chat_message_handlers = {
  142. 'text': self.handle_text_message,
  143. 'pinned_message': self.handle_pinned_message,
  144. 'photo': self.handle_photo_message
  145. }
  146. if db_name:
  147. self._db_url = 'sqlite:///{name}{ext}'.format(
  148. name=db_name,
  149. ext='.db' if not db_name.endswith('.db') else ''
  150. )
  151. else:
  152. self._db_url = None
  153. self._unauthorized_message = None
  154. self.authorization_function = lambda update, authorization_level: True
  155. self.get_chat_id = lambda update: (
  156. update['message']['chat']['id']
  157. if 'message' in update
  158. else update['chat']['id']
  159. )
  160. self.commands = dict()
  161. self.callback_handlers = dict()
  162. self.inline_query_handlers = MyOD()
  163. self._default_inline_query_answer = None
  164. self.chosen_inline_result_handlers = dict()
  165. self.aliases = MyOD()
  166. self.parsers = MyOD()
  167. self.custom_parsers = dict()
  168. self.custom_photo_parsers = dict()
  169. self.bot_name = None
  170. self.default_reply_keyboard_elements = []
  171. self._default_keyboard = dict()
  172. self.run_before_loop = []
  173. self.run_after_loop = []
  174. self.to_be_obscured = []
  175. self.to_be_destroyed = []
  176. self.last_sending_time = dict(
  177. absolute=(
  178. datetime.datetime.now()
  179. - self.__class__.COOLDOWN_TIME_ABSOLUTE
  180. )
  181. )
  182. self._maintenance = False
  183. self._maintenance_message = None
  184. self.chat_actions = dict(
  185. pinned=MyOD()
  186. )
  187. self.messages = dict()
  188. @property
  189. def name(self):
  190. """Bot name."""
  191. return self.bot_name
  192. @property
  193. def path(self):
  194. """custombot.py file path."""
  195. return self.__class__._path
  196. @property
  197. def db_url(self):
  198. """Return complete path to database."""
  199. return self._db_url
  200. @property
  201. def db(self):
  202. """Connect to bot's database.
  203. It must be used inside a with statement: `with bot.db as db`
  204. """
  205. if self.db_url:
  206. return dataset.connect(self.db_url)
  207. @property
  208. def default_keyboard(self):
  209. """Get the default keyboard.
  210. It is sent when reply_markup is left blank and chat is private.
  211. """
  212. return self._default_keyboard
  213. @property
  214. def default_inline_query_answer(self):
  215. """Answer to be returned if inline query returned None."""
  216. if self._default_inline_query_answer:
  217. return self._default_inline_query_answer
  218. return self.__class__._default_inline_query_answer
  219. @property
  220. def unauthorized_message(self):
  221. """Return this if user is unauthorized to make a request.
  222. If instance message is not set, class message is returned.
  223. """
  224. if self._unauthorized_message:
  225. return self._unauthorized_message
  226. return self.__class__._unauthorized_message
  227. @property
  228. def unknown_command_message(self):
  229. """Message to be returned if user sends an unknown command in private chat.
  230. If instance message is not set, class message is returned.
  231. """
  232. if self._unknown_command_message:
  233. return self._unknown_command_message
  234. return self.__class__._unknown_command_message
  235. @property
  236. def maintenance(self):
  237. """Check whether bot is under maintenance.
  238. While under maintenance, bot will reply with
  239. `self.maintenance_message` to any request, with few exceptions.
  240. """
  241. return self._maintenance
  242. @property
  243. def maintenance_message(self):
  244. """Message to be returned if bot is under maintenance.
  245. If instance message is not set, class message is returned.
  246. """
  247. if self._maintenance_message:
  248. return self._maintenance_message
  249. if self.__class__.maintenance_message:
  250. return self.__class__._maintenance_message
  251. return "Bot is currently under maintenance! Retry later please."
  252. @classmethod
  253. def set_class_path(csl, path):
  254. """Set class path, where files will be looked for.
  255. For example, if send_photo receives `photo='mypic.png'`,
  256. it will parse it as `'{path}/mypic.png'.format(path=self.path)`
  257. """
  258. csl._path = path
  259. @classmethod
  260. def set_class_unauthorized_message(csl, unauthorized_message):
  261. """Set class unauthorized message.
  262. It will be returned if user is unauthorized to make a request.
  263. """
  264. csl._unauthorized_message = unauthorized_message
  265. @classmethod
  266. def set_class_unknown_command_message(cls, unknown_command_message):
  267. """Set class unknown command message.
  268. It will be returned if user sends an unknown command in private chat.
  269. """
  270. cls._unknown_command_message = unknown_command_message
  271. @classmethod
  272. def set_class_maintenance_message(cls, maintenance_message):
  273. """Set class maintenance message.
  274. It will be returned if bot is under maintenance.
  275. """
  276. cls._maintenance_message = maintenance_message
  277. @classmethod
  278. def set_class_default_inline_query_answer(cls,
  279. default_inline_query_answer):
  280. """Set class default inline query answer.
  281. It will be returned if an inline query returned no answer.
  282. """
  283. cls._default_inline_query_answer = default_inline_query_answer
  284. def set_unauthorized_message(self, unauthorized_message):
  285. """Set instance unauthorized message.
  286. If instance message is None, default class message is used.
  287. """
  288. self._unauthorized_message = unauthorized_message
  289. def set_unknown_command_message(self, unknown_command_message):
  290. """Set instance unknown command message.
  291. It will be returned if user sends an unknown command in private chat.
  292. If instance message is None, default class message is used.
  293. """
  294. self._unknown_command_message = unknown_command_message
  295. def set_maintenance_message(self, maintenance_message):
  296. """Set instance maintenance message.
  297. It will be returned if bot is under maintenance.
  298. If instance message is None, default class message is used.
  299. """
  300. self._maintenance_message = maintenance_message
  301. def set_default_inline_query_answer(self, default_inline_query_answer):
  302. """Set a custom default_inline_query_answer.
  303. It will be returned when no answer is found for an inline query.
  304. If instance answer is None, default class answer is used.
  305. """
  306. if type(default_inline_query_answer) in (str, dict):
  307. default_inline_query_answer = make_inline_query_answer(
  308. default_inline_query_answer
  309. )
  310. if type(default_inline_query_answer) is not list:
  311. return 1
  312. self._default_inline_query_answer = default_inline_query_answer
  313. return 0
  314. def set_maintenance(self, maintenance_message):
  315. """Put the bot under maintenance or ends it.
  316. While in maintenance, bot will reply to users with maintenance_message.
  317. Bot will accept /coma, /stop and /restart commands from admins.
  318. """
  319. self._maintenance = not self.maintenance
  320. if maintenance_message:
  321. self.set_maintenance_message(maintenance_message)
  322. if self.maintenance:
  323. return (
  324. "<i>Bot has just been put under maintenance!</i>\n\n"
  325. "Until further notice, it will reply to users "
  326. "with the following message:\n\n{}"
  327. ).format(
  328. self.maintenance_message
  329. )
  330. return "<i>Maintenance ended!</i>"
  331. def set_authorization_function(self, authorization_function):
  332. """Set a custom authorization_function.
  333. It should evaluate True if user is authorized to perform
  334. a specific action and False otherwise.
  335. It should take update and role and return a Boolean.
  336. Default authorization_function always evaluates True.
  337. """
  338. self.authorization_function = authorization_function
  339. def set_get_chat_id_function(self, get_chat_id_function):
  340. """Set a custom get_chat_id function.
  341. It should take and update and return the chat in which
  342. a reply should be sent.
  343. For instance, a bot could reply in private to group messages
  344. as a default behaviour.
  345. Default chat_id returned is current chat id.
  346. """
  347. self.get_chat_id = get_chat_id_function
  348. async def avoid_flooding(self, chat_id):
  349. """asyncio-sleep until COOLDOWN_TIME (per_chat and absolute) has passed.
  350. To prevent hitting Telegram flood limits, send_message and
  351. send_photo await this function.
  352. """
  353. if type(chat_id) is int and chat_id > 0:
  354. while (
  355. datetime.datetime.now() < (
  356. self.last_sending_time['absolute']
  357. + self.__class__.COOLDOWN_TIME_ABSOLUTE
  358. )
  359. ) or (
  360. chat_id in self.last_sending_time
  361. and (
  362. datetime.datetime.now() < (
  363. self.last_sending_time[chat_id]
  364. + self.__class__.COOLDOWN_TIME_PER_CHAT
  365. )
  366. )
  367. ):
  368. await asyncio.sleep(
  369. self.__class__.COOLDOWN_TIME_ABSOLUTE.seconds
  370. )
  371. self.last_sending_time[chat_id] = datetime.datetime.now()
  372. else:
  373. while (
  374. datetime.datetime.now() < (
  375. self.last_sending_time['absolute']
  376. + self.__class__.COOLDOWN_TIME_ABSOLUTE
  377. )
  378. ) or (
  379. chat_id in self.last_sending_time
  380. and len(
  381. [
  382. sending_datetime
  383. for sending_datetime in self.last_sending_time[chat_id]
  384. if sending_datetime >= (
  385. datetime.datetime.now()
  386. - datetime.timedelta(minutes=1)
  387. )
  388. ]
  389. ) >= self.__class__.MAX_GROUP_MESSAGES_PER_MINUTE
  390. ) or (
  391. chat_id in self.last_sending_time
  392. and len(self.last_sending_time[chat_id]) > 0
  393. and datetime.datetime.now() < (
  394. self.last_sending_time[chat_id][-1]
  395. + self.__class__.COOLDOWN_TIME_PER_CHAT
  396. )
  397. ):
  398. await asyncio.sleep(0.5)
  399. if chat_id not in self.last_sending_time:
  400. self.last_sending_time[chat_id] = []
  401. self.last_sending_time[chat_id].append(datetime.datetime.now())
  402. self.last_sending_time[chat_id] = [
  403. sending_datetime
  404. for sending_datetime in self.last_sending_time[chat_id]
  405. if sending_datetime >= (
  406. datetime.datetime.now()
  407. - datetime.timedelta(minutes=1)
  408. )
  409. ]
  410. self.last_sending_time['absolute'] = datetime.datetime.now()
  411. return
  412. def get_message(self, *fields, update=None, language=None,
  413. **format_kwargs):
  414. """Given a list of strings (`fields`), return proper message.
  415. If `language` is not passed, it is extracted from `update`.
  416. Fall back to English message if language is not available.
  417. """
  418. if (
  419. language is None
  420. and update is not None
  421. and type(update) is dict
  422. and 'from' in update
  423. and 'language_code' in update['from']
  424. ):
  425. language = update['from']['language_code']
  426. if language is None:
  427. language = 'en'
  428. result = self.messages
  429. for field in fields:
  430. if field not in result:
  431. logging.error(
  432. "Please define self.message{f}".format(
  433. f=''.join(
  434. '[\'{field}\']'.format(
  435. field=field
  436. )
  437. for field in fields
  438. )
  439. )
  440. )
  441. return "Invalid message!"
  442. result = result[field]
  443. if language not in result:
  444. language = extract(
  445. language,
  446. ender='-'
  447. )
  448. if language not in result:
  449. language = 'en'
  450. if language not in result:
  451. logging.error(
  452. "Please define self.message{f}['en']".format(
  453. f=''.join(
  454. '[\'{field}\']'.format(
  455. field=field
  456. )
  457. for field in fields
  458. )
  459. )
  460. )
  461. return "Invalid message!"
  462. return result[language].format(
  463. **format_kwargs
  464. )
  465. async def on_inline_query(self, update):
  466. """Schedule handling of received inline queries.
  467. Notice that handling is only scheduled, not awaited.
  468. This means that all Bot instances may now handle other requests
  469. before this one is completed.
  470. """
  471. asyncio.ensure_future(self.handle_inline_query(update))
  472. return
  473. async def on_chosen_inline_result(self, update):
  474. """Schedule handling of received chosen inline result events.
  475. Notice that handling is only scheduled, not awaited.
  476. This means that all Bot instances may now handle other requests
  477. before this one is completed.
  478. """
  479. asyncio.ensure_future(self.handle_chosen_inline_result(update))
  480. return
  481. async def on_callback_query(self, update):
  482. """Schedule handling of received callback queries.
  483. A callback query is sent when users press inline keyboard buttons.
  484. Bad clients may send malformed or deceiving callback queries:
  485. never use secret keys in buttons and always check request validity!
  486. Notice that handling is only scheduled, not awaited.
  487. This means that all Bot instances may now handle other requests
  488. before this one is completed.
  489. """
  490. # Reject malformed updates lacking of data field
  491. if 'data' not in update:
  492. return
  493. asyncio.ensure_future(self.handle_callback_query(update))
  494. return
  495. async def on_chat_message(self, update):
  496. """Schedule handling of received chat message.
  497. Notice that handling is only scheduled, not awaited.
  498. According to update type, the corresponding handler is
  499. scheduled (see self.chat_message_handlers).
  500. This means that all Bot instances may now handle other
  501. requests before this one is completed.
  502. """
  503. answer = None
  504. content_type, chat_type, chat_id = telepot.glance(
  505. update,
  506. flavor='chat',
  507. long=False
  508. )
  509. if content_type in self.chat_message_handlers:
  510. answer = asyncio.ensure_future(
  511. self.chat_message_handlers[content_type](update)
  512. )
  513. else:
  514. answer = None
  515. logging.debug("Unhandled message")
  516. return answer
  517. async def handle_inline_query(self, update):
  518. """Handle inline query and answer it with results, or log errors."""
  519. query = update['query']
  520. answer = None
  521. switch_pm_text, switch_pm_parameter = None, None
  522. if self.maintenance:
  523. answer = self.maintenance_message
  524. else:
  525. for condition, handler in self.inline_query_handlers.items():
  526. answerer = handler['function']
  527. if condition(update['query']):
  528. if asyncio.iscoroutinefunction(answerer):
  529. answer = await answerer(update)
  530. else:
  531. answer = answerer(update)
  532. break
  533. if not answer:
  534. answer = self.default_inline_query_answer
  535. if type(answer) is dict:
  536. if 'switch_pm_text' in answer:
  537. switch_pm_text = answer['switch_pm_text']
  538. if 'switch_pm_parameter' in answer:
  539. switch_pm_parameter = answer['switch_pm_parameter']
  540. answer = answer['answer']
  541. if type(answer) is str:
  542. answer = make_inline_query_answer(answer)
  543. try:
  544. await self.answerInlineQuery(
  545. update['id'],
  546. answer,
  547. cache_time=10,
  548. is_personal=True,
  549. switch_pm_text=switch_pm_text,
  550. switch_pm_parameter=switch_pm_parameter
  551. )
  552. except Exception as e:
  553. logging.info("Error answering inline query\n{}".format(e))
  554. return
  555. async def handle_chosen_inline_result(self, update):
  556. """When an inline query result is chosen, perform an action.
  557. If chosen inline result id is in self.chosen_inline_result_handlers,
  558. call the related function passing the update as argument.
  559. """
  560. user_id = update['from']['id'] if 'from' in update else None
  561. if self.maintenance:
  562. return
  563. if user_id in self.chosen_inline_result_handlers:
  564. result_id = update['result_id']
  565. handlers = self.chosen_inline_result_handlers[user_id]
  566. if result_id in handlers:
  567. func = handlers[result_id]
  568. if asyncio.iscoroutinefunction(func):
  569. await func(update)
  570. else:
  571. func(update)
  572. return
  573. def set_inline_result_handler(self, user_id, result_id, func):
  574. """Associate a func to a result_id.
  575. When an inline result is chosen having that id, function will
  576. be passed the update as argument.
  577. """
  578. if type(user_id) is dict:
  579. user_id = user_id['from']['id']
  580. assert type(user_id) is int, "user_id must be int!"
  581. # Query result ids are parsed as str by telegram
  582. result_id = str(result_id)
  583. assert callable(func), "func must be a callable"
  584. if user_id not in self.chosen_inline_result_handlers:
  585. self.chosen_inline_result_handlers[user_id] = {}
  586. self.chosen_inline_result_handlers[user_id][result_id] = func
  587. return
  588. async def handle_callback_query(self, update):
  589. """Answer callback queries.
  590. Call the callback handler associated to the query prefix.
  591. The answer is used to edit the source message or send new ones
  592. if text is longer than single message limit.
  593. Anyway, the query is answered, otherwise the client would hang and
  594. the bot would look like idle.
  595. """
  596. answer = None
  597. if self.maintenance:
  598. answer = remove_html_tags(self.maintenance_message[:45])
  599. else:
  600. data = update['data']
  601. for start_text, handler in self.callback_handlers.items():
  602. answerer = handler['function']
  603. if data.startswith(start_text):
  604. if asyncio.iscoroutinefunction(answerer):
  605. answer = await answerer(update)
  606. else:
  607. answer = answerer(update)
  608. break
  609. if answer:
  610. if type(answer) is str:
  611. answer = {'text': answer}
  612. if type(answer) is not dict:
  613. return
  614. if 'edit' in answer:
  615. if 'message' in update:
  616. message_identifier = telepot.message_identifier(
  617. update['message']
  618. )
  619. else:
  620. message_identifier = telepot.message_identifier(update)
  621. edit = answer['edit']
  622. reply_markup = (
  623. edit['reply_markup']
  624. if 'reply_markup' in edit
  625. else None
  626. )
  627. text = (
  628. edit['text']
  629. if 'text' in edit
  630. else None
  631. )
  632. caption = (
  633. edit['caption']
  634. if 'caption' in edit
  635. else None
  636. )
  637. parse_mode = (
  638. edit['parse_mode']
  639. if 'parse_mode' in edit
  640. else None
  641. )
  642. disable_web_page_preview = (
  643. edit['disable_web_page_preview']
  644. if 'disable_web_page_preview' in edit
  645. else None
  646. )
  647. try:
  648. if 'text' in edit:
  649. if (
  650. len(text)
  651. > self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 200
  652. ):
  653. if 'from' in update:
  654. await self.send_message(
  655. chat_id=update['from']['id'],
  656. text=text,
  657. reply_markup=reply_markup,
  658. parse_mode=parse_mode,
  659. disable_web_page_preview=(
  660. disable_web_page_preview
  661. )
  662. )
  663. else:
  664. await self.editMessageText(
  665. msg_identifier=message_identifier,
  666. text=text,
  667. parse_mode=parse_mode,
  668. disable_web_page_preview=(
  669. disable_web_page_preview
  670. ),
  671. reply_markup=reply_markup
  672. )
  673. elif 'caption' in edit:
  674. await self.editMessageCaption(
  675. msg_identifier=message_identifier,
  676. caption=caption,
  677. reply_markup=reply_markup
  678. )
  679. elif 'reply_markup' in edit:
  680. await self.editMessageReplyMarkup(
  681. msg_identifier=message_identifier,
  682. reply_markup=reply_markup
  683. )
  684. except Exception as e:
  685. logging.info("Message was not modified:\n{}".format(e))
  686. text = answer['text'][:180] if 'text' in answer else None
  687. show_alert = (
  688. answer['show_alert']
  689. if 'show_alert' in answer
  690. else None
  691. )
  692. cache_time = (
  693. answer['cache_time']
  694. if 'cache_time' in answer
  695. else None
  696. )
  697. try:
  698. await self.answerCallbackQuery(
  699. callback_query_id=update['id'],
  700. text=text,
  701. show_alert=show_alert,
  702. cache_time=cache_time
  703. )
  704. except telepot.exception.TelegramError as e:
  705. logging.error(e)
  706. else:
  707. try:
  708. await self.answerCallbackQuery(callback_query_id=update['id'])
  709. except telepot.exception.TelegramError as e:
  710. logging.error(e)
  711. return
  712. async def handle_text_message(self, update):
  713. """Answer to chat text messages.
  714. 1) Ignore bot name (case-insensitive) and search bot custom parsers,
  715. commands, aliases and parsers for an answerer.
  716. 2) Get an answer from answerer(update).
  717. 3) Send it to the user.
  718. """
  719. answerer, answer = None, None
  720. # Lower text and replace only bot's tag,
  721. # meaning that `/command@OtherBot` will be ignored.
  722. text = update['text'].lower().replace(
  723. '@{}'.format(
  724. self.name.lower()
  725. ),
  726. ''
  727. )
  728. user_id = update['from']['id'] if 'from' in update else None
  729. if self.maintenance and not any(
  730. text.startswith(x)
  731. for x in ('/coma', '/restart')
  732. ):
  733. if update['chat']['id'] > 0:
  734. answer = self.maintenance_message
  735. elif user_id in self.custom_parsers:
  736. answerer = self.custom_parsers[user_id]
  737. del self.custom_parsers[user_id]
  738. elif text.startswith('/'):
  739. command = text.split()[0].strip(' /@')
  740. if command in self.commands:
  741. answerer = self.commands[command]['function']
  742. elif update['chat']['id'] > 0:
  743. answer = self.unknown_command_message
  744. else:
  745. # If text starts with an alias
  746. # Aliases are case insensitive: text and alias are both .lower()
  747. for alias, parser in self.aliases.items():
  748. if text.startswith(alias.lower()):
  749. answerer = parser
  750. break
  751. # If update matches any parser
  752. for check_function, parser in self.parsers.items():
  753. if (
  754. parser['argument'] == 'text'
  755. and check_function(text)
  756. ) or (
  757. parser['argument'] == 'update'
  758. and check_function(update)
  759. ):
  760. answerer = parser['function']
  761. break
  762. if answerer:
  763. if asyncio.iscoroutinefunction(answerer):
  764. answer = await answerer(update)
  765. else:
  766. answer = answerer(update)
  767. if answer:
  768. try:
  769. return await self.send_message(answer=answer, chat_id=update)
  770. except Exception as e:
  771. logging.error(
  772. "Failed to process answer:\n{}".format(e),
  773. exc_info=True
  774. )
  775. async def handle_pinned_message(self, update):
  776. """Handle pinned message chat action."""
  777. if self.maintenance:
  778. return
  779. answerer = None
  780. for criteria, handler in self.chat_actions['pinned'].items():
  781. if criteria(update):
  782. answerer = handler['function']
  783. break
  784. if answerer is None:
  785. return
  786. elif asyncio.iscoroutinefunction(answerer):
  787. answer = await answerer(update)
  788. else:
  789. answer = answerer(update)
  790. if answer:
  791. try:
  792. return await self.send_message(
  793. answer=answer,
  794. chat_id=update['chat']['id']
  795. )
  796. except Exception as e:
  797. logging.error(
  798. "Failed to process answer:\n{}".format(
  799. e
  800. ),
  801. exc_info=True
  802. )
  803. return
  804. async def handle_photo_message(self, update):
  805. """Handle photo chat message."""
  806. user_id = update['from']['id'] if 'from' in update else None
  807. answerer, answer = None, None
  808. if self.maintenance:
  809. if update['chat']['id'] > 0:
  810. answer = self.maintenance_message
  811. elif user_id in self.custom_photo_parsers:
  812. answerer = self.custom_photo_parsers[user_id]
  813. del self.custom_photo_parsers[user_id]
  814. if answerer:
  815. if asyncio.iscoroutinefunction(answerer):
  816. answer = await answerer(update)
  817. else:
  818. answer = answerer(update)
  819. if answer:
  820. try:
  821. return await self.send_message(answer=answer, chat_id=update)
  822. except Exception as e:
  823. logging.error(
  824. "Failed to process answer:\n{}".format(
  825. e
  826. ),
  827. exc_info=True
  828. )
  829. return
  830. def set_custom_parser(self, parser, update=None, user=None):
  831. """Set a custom parser for the user.
  832. Any chat message update coming from the user will be handled by
  833. this custom parser instead of default parsers (commands, aliases
  834. and text parsers).
  835. Custom parsers last one single use, but their handler can call this
  836. function to provide multiple tries.
  837. """
  838. if user and type(user) is int:
  839. pass
  840. elif type(update) is int:
  841. user = update
  842. elif type(user) is dict:
  843. user = (
  844. user['from']['id']
  845. if 'from' in user
  846. and 'id' in user['from']
  847. else None
  848. )
  849. elif not user and type(update) is dict:
  850. user = (
  851. update['from']['id']
  852. if 'from' in update
  853. and 'id' in update['from']
  854. else None
  855. )
  856. else:
  857. raise TypeError(
  858. 'Invalid user.\nuser: {}\nupdate: {}'.format(
  859. user,
  860. update
  861. )
  862. )
  863. if not type(user) is int:
  864. raise TypeError(
  865. 'User {} is not an int id'.format(
  866. user
  867. )
  868. )
  869. if not callable(parser):
  870. raise TypeError(
  871. 'Parser {} is not a callable'.format(
  872. parser.__name__
  873. )
  874. )
  875. self.custom_parsers[user] = parser
  876. return
  877. def set_custom_photo_parser(self, parser, update=None, user=None):
  878. """Set a custom photo parser for the user.
  879. Any photo chat update coming from the user will be handled by
  880. this custom parser instead of default parsers.
  881. Custom photo parsers last one single use, but their handler can
  882. call this function to provide multiple tries.
  883. """
  884. if user and type(user) is int:
  885. pass
  886. elif type(update) is int:
  887. user = update
  888. elif type(user) is dict:
  889. user = (
  890. user['from']['id']
  891. if 'from' in user
  892. and 'id' in user['from']
  893. else None
  894. )
  895. elif not user and type(update) is dict:
  896. user = (
  897. update['from']['id']
  898. if 'from' in update
  899. and 'id' in update['from']
  900. else None
  901. )
  902. else:
  903. raise TypeError(
  904. 'Invalid user.\nuser: {}\nupdate: {}'.format(
  905. user,
  906. update
  907. )
  908. )
  909. if not type(user) is int:
  910. raise TypeError(
  911. 'User {} is not an int id'.format(
  912. user
  913. )
  914. )
  915. if not callable(parser):
  916. raise TypeError(
  917. 'Parser {} is not a callable'.format(
  918. parser.__name__
  919. )
  920. )
  921. self.custom_photo_parsers[user] = parser
  922. return
  923. def command(self, command, aliases=None, show_in_keyboard=False,
  924. descr="", auth='admin'):
  925. """Define a bot command.
  926. Decorator: `@bot.command(*args)`
  927. When a message text starts with `/command[@bot_name]`, or with an
  928. alias, it gets passed to the decorated function.
  929. `command` is the command name (with or without /)
  930. `aliases` is a list of aliases
  931. `show_in_keyboard`, if True, makes first alias appear
  932. in default_keyboard
  933. `descr` is a description
  934. `auth` is the lowest authorization level needed to run the command
  935. """
  936. command = command.replace('/', '').lower()
  937. if not isinstance(command, str):
  938. raise TypeError('Command {} is not a string'.format(command))
  939. if aliases:
  940. if not isinstance(aliases, list):
  941. raise TypeError('Aliases is not a list: {}'.format(aliases))
  942. for alias in aliases:
  943. if not isinstance(alias, str):
  944. raise TypeError('Alias {} is not a string'.format(alias))
  945. def decorator(func):
  946. if asyncio.iscoroutinefunction(func):
  947. async def decorated(message):
  948. logging.info(
  949. "COMMAND({c}) @{n} FROM({f})".format(
  950. c=command,
  951. n=self.name,
  952. f=(
  953. message['from']
  954. if 'from' in message
  955. else message['chat']
  956. )
  957. )
  958. )
  959. if self.authorization_function(message, auth):
  960. return await func(message)
  961. return self.unauthorized_message
  962. else:
  963. def decorated(message):
  964. logging.info(
  965. "COMMAND({c}) @{n} FROM({f})".format(
  966. c=command,
  967. n=self.name,
  968. f=(
  969. message['from']
  970. if 'from' in message
  971. else message['chat']
  972. )
  973. )
  974. )
  975. if self.authorization_function(message, auth):
  976. return func(message)
  977. return self.unauthorized_message
  978. self.commands[command] = dict(
  979. function=decorated,
  980. descr=descr,
  981. auth=auth
  982. )
  983. if aliases:
  984. for alias in aliases:
  985. self.aliases[alias] = decorated
  986. if show_in_keyboard:
  987. self.default_reply_keyboard_elements.append(aliases[0])
  988. return decorator
  989. def parser(self, condition, descr='', auth='admin', argument='text'):
  990. """Define a message parser.
  991. Decorator: `@bot.parser(condition)`
  992. If condition evaluates True when run on a message text
  993. (not starting with '/'), such decorated function gets
  994. called on update.
  995. Conditions of parsers are evaluated in order; when one is True,
  996. others will be skipped.
  997. `descr` is a description
  998. `auth` is the lowest authorization level needed to run the command
  999. """
  1000. if not callable(condition):
  1001. raise TypeError(
  1002. 'Condition {} is not a callable'.format(
  1003. condition.__name__
  1004. )
  1005. )
  1006. def decorator(func):
  1007. if asyncio.iscoroutinefunction(func):
  1008. async def decorated(message):
  1009. logging.info(
  1010. "TEXT MATCHING CONDITION({c}) @{n} FROM({f})".format(
  1011. c=condition.__name__,
  1012. n=self.name,
  1013. f=(
  1014. message['from']
  1015. if 'from' in message
  1016. else message['chat']
  1017. )
  1018. )
  1019. )
  1020. if self.authorization_function(message, auth):
  1021. return await func(message)
  1022. return self.unauthorized_message
  1023. else:
  1024. def decorated(message):
  1025. logging.info(
  1026. "TEXT MATCHING CONDITION({c}) @{n} FROM({f})".format(
  1027. c=condition.__name__,
  1028. n=self.name,
  1029. f=(
  1030. message['from']
  1031. if 'from' in message
  1032. else message['chat']
  1033. )
  1034. )
  1035. )
  1036. if self.authorization_function(message, auth):
  1037. return func(message)
  1038. return self.unauthorized_message
  1039. self.parsers[condition] = dict(
  1040. function=decorated,
  1041. descr=descr,
  1042. auth=auth,
  1043. argument=argument
  1044. )
  1045. return decorator
  1046. def pinned(self, condition, descr='', auth='admin'):
  1047. """Handle pinned messages.
  1048. Decorator: `@bot.pinned(condition)`
  1049. If condition evaluates True when run on a pinned_message update,
  1050. such decorated function gets called on update.
  1051. Conditions are evaluated in order; when one is True,
  1052. others will be skipped.
  1053. `descr` is a description
  1054. `auth` is the lowest authorization level needed to run the command
  1055. """
  1056. if not callable(condition):
  1057. raise TypeError(
  1058. 'Condition {c} is not a callable'.format(
  1059. c=condition.__name__
  1060. )
  1061. )
  1062. def decorator(func):
  1063. if asyncio.iscoroutinefunction(func):
  1064. async def decorated(message):
  1065. logging.info(
  1066. "PINNED MESSAGE MATCHING({c}) @{n} FROM({f})".format(
  1067. c=condition.__name__,
  1068. n=self.name,
  1069. f=(
  1070. message['from']
  1071. if 'from' in message
  1072. else message['chat']
  1073. )
  1074. )
  1075. )
  1076. if self.authorization_function(message, auth):
  1077. return await func(message)
  1078. return
  1079. else:
  1080. def decorated(message):
  1081. logging.info(
  1082. "PINNED MESSAGE MATCHING({c}) @{n} FROM({f})".format(
  1083. c=condition.__name__,
  1084. n=self.name,
  1085. f=(
  1086. message['from']
  1087. if 'from' in message
  1088. else message['chat']
  1089. )
  1090. )
  1091. )
  1092. if self.authorization_function(message, auth):
  1093. return func(message)
  1094. return
  1095. self.chat_actions['pinned'][condition] = dict(
  1096. function=decorated,
  1097. descr=descr,
  1098. auth=auth
  1099. )
  1100. return decorator
  1101. def button(self, data, descr='', auth='admin'):
  1102. """Define a bot button.
  1103. Decorator: `@bot.button('example:///')`
  1104. When a callback data text starts with <data>, it gets passed to the
  1105. decorated function
  1106. `descr` is a description
  1107. `auth` is the lowest authorization level needed to run the command
  1108. """
  1109. if not isinstance(data, str):
  1110. raise TypeError(
  1111. 'Inline button callback_data {d} is not a string'.format(
  1112. d=data
  1113. )
  1114. )
  1115. def decorator(func):
  1116. if asyncio.iscoroutinefunction(func):
  1117. async def decorated(message):
  1118. logging.info(
  1119. "INLINE BUTTON({d}) @{n} FROM({f})".format(
  1120. d=message['data'],
  1121. n=self.name,
  1122. f=(
  1123. message['from']
  1124. )
  1125. )
  1126. )
  1127. if self.authorization_function(message, auth):
  1128. return await func(message)
  1129. return self.unauthorized_message
  1130. else:
  1131. def decorated(message):
  1132. logging.info(
  1133. "INLINE BUTTON({d}) @{n} FROM({f})".format(
  1134. d=message['data'],
  1135. n=self.name,
  1136. f=(
  1137. message['from']
  1138. )
  1139. )
  1140. )
  1141. if self.authorization_function(message, auth):
  1142. return func(message)
  1143. return self.unauthorized_message
  1144. self.callback_handlers[data] = dict(
  1145. function=decorated,
  1146. descr=descr,
  1147. auth=auth
  1148. )
  1149. return decorator
  1150. def query(self, condition, descr='', auth='admin'):
  1151. """Define an inline query.
  1152. Decorator: `@bot.query(example)`
  1153. When an inline query matches the `condition` function,
  1154. decorated function is called and passed the query update object
  1155. as argument.
  1156. `descr` is a description
  1157. `auth` is the lowest authorization level needed to run the command
  1158. """
  1159. if not callable(condition):
  1160. raise TypeError(
  1161. 'Condition {c} is not a callable'.format(
  1162. c=condition.__name__
  1163. )
  1164. )
  1165. def decorator(func):
  1166. if asyncio.iscoroutinefunction(func):
  1167. async def decorated(message):
  1168. logging.info(
  1169. "QUERY MATCHING CONDITION({c}) @{n} FROM({f})".format(
  1170. c=condition.__name__,
  1171. n=self.name,
  1172. f=message['from']
  1173. )
  1174. )
  1175. if self.authorization_function(message, auth):
  1176. return await func(message)
  1177. return self.unauthorized_message
  1178. else:
  1179. def decorated(message):
  1180. logging.info(
  1181. "QUERY MATCHING CONDITION({c}) @{n} FROM({f})".format(
  1182. c=condition.__name__,
  1183. n=self.name,
  1184. f=message['from']
  1185. )
  1186. )
  1187. if self.authorization_function(message, auth):
  1188. return func(message)
  1189. return self.unauthorized_message
  1190. self.inline_query_handlers[condition] = dict(
  1191. function=decorated,
  1192. descr=descr,
  1193. auth=auth
  1194. )
  1195. return decorator
  1196. def additional_task(self, when='BEFORE'):
  1197. """Add a task before or after message_loop.
  1198. Decorator: such decorated async functions get awaited BEFORE or
  1199. AFTER messageloop
  1200. """
  1201. when = when[0].lower()
  1202. def decorator(func):
  1203. if when == 'b':
  1204. self.run_before_loop.append(func)
  1205. elif when == 'a':
  1206. self.run_after_loop.append(func)
  1207. return decorator
  1208. def set_default_keyboard(self, keyboard='set_default'):
  1209. """Set a default keyboard for the bot.
  1210. If a keyboard is not passed as argument, a default one is generated,
  1211. based on aliases of commands.
  1212. """
  1213. if keyboard == 'set_default':
  1214. btns = [
  1215. dict(
  1216. text=x
  1217. )
  1218. for x in self.default_reply_keyboard_elements
  1219. ]
  1220. row_len = 2 if len(btns) < 4 else 3
  1221. self._default_keyboard = dict(
  1222. keyboard=make_lines_of_buttons(
  1223. btns,
  1224. row_len
  1225. ),
  1226. resize_keyboard=True
  1227. )
  1228. else:
  1229. self._default_keyboard = keyboard
  1230. return
  1231. async def edit_message(self, update, *args, **kwargs):
  1232. """Edit given update with given *args and **kwargs.
  1233. Please note, that it is currently only possible to edit messages
  1234. without reply_markup or with inline keyboards.
  1235. """
  1236. try:
  1237. return await self.editMessageText(
  1238. telepot.message_identifier(update),
  1239. *args,
  1240. **kwargs
  1241. )
  1242. except Exception as e:
  1243. logging.error("{}".format(e))
  1244. async def delete_message(self, update, *args, **kwargs):
  1245. """Delete given update with given *args and **kwargs.
  1246. Please note, that a bot can delete only messages sent by itself
  1247. or sent in a group which it is administrator of.
  1248. """
  1249. try:
  1250. return await self.deleteMessage(
  1251. telepot.message_identifier(update),
  1252. *args,
  1253. **kwargs
  1254. )
  1255. except Exception as e:
  1256. logging.error("{}".format(e))
  1257. async def send_message(self, answer=dict(), chat_id=None, text='',
  1258. parse_mode="HTML", disable_web_page_preview=None,
  1259. disable_notification=None, reply_to_message_id=None,
  1260. reply_markup=None):
  1261. """Send a message.
  1262. Convenient method to call telepot.Bot(token).sendMessage
  1263. All sendMessage **kwargs can be either **kwargs of send_message
  1264. or key:val of answer argument.
  1265. Messages longer than telegram limit will be split properly.
  1266. Telegram flood limits won't be reached thanks to
  1267. `await avoid_flooding(chat_id)`
  1268. parse_mode will be checked and edited if necessary.
  1269. Arguments will be checked and adapted.
  1270. """
  1271. if type(answer) is dict and 'chat_id' in answer:
  1272. chat_id = answer['chat_id']
  1273. # chat_id may simply be the update to which the bot should repy
  1274. if type(chat_id) is dict:
  1275. chat_id = self.get_chat_id(chat_id)
  1276. if type(answer) is str:
  1277. text = answer
  1278. if (
  1279. not reply_markup
  1280. and chat_id > 0
  1281. and text != self.unauthorized_message
  1282. ):
  1283. reply_markup = self.default_keyboard
  1284. elif type(answer) is dict:
  1285. if 'text' in answer:
  1286. text = answer['text']
  1287. if 'parse_mode' in answer:
  1288. parse_mode = answer['parse_mode']
  1289. if 'disable_web_page_preview' in answer:
  1290. disable_web_page_preview = answer['disable_web_page_preview']
  1291. if 'disable_notification' in answer:
  1292. disable_notification = answer['disable_notification']
  1293. if 'reply_to_message_id' in answer:
  1294. reply_to_message_id = answer['reply_to_message_id']
  1295. if 'reply_markup' in answer:
  1296. reply_markup = answer['reply_markup']
  1297. elif (
  1298. not reply_markup
  1299. and type(chat_id) is int
  1300. and chat_id > 0
  1301. and text != self.unauthorized_message
  1302. ):
  1303. reply_markup = self.default_keyboard
  1304. assert type(text) is str, "Text is not a string!"
  1305. assert (
  1306. type(chat_id) is int
  1307. or (type(chat_id) is str and chat_id.startswith('@'))
  1308. ), "Invalid chat_id:\n\t\t{}".format(chat_id)
  1309. if not text:
  1310. return
  1311. parse_mode = str(parse_mode)
  1312. text_chunks = split_text_gracefully(
  1313. text=text,
  1314. limit=self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 100,
  1315. parse_mode=parse_mode
  1316. )
  1317. n = len(text_chunks)
  1318. for text_chunk in text_chunks:
  1319. n -= 1
  1320. if parse_mode.lower() == "html":
  1321. this_parse_mode = "HTML"
  1322. # Check that all tags are well-formed
  1323. if not markdown_check(
  1324. text_chunk,
  1325. [
  1326. "<", ">",
  1327. "code>", "bold>", "italic>",
  1328. "b>", "i>", "a>", "pre>"
  1329. ]
  1330. ):
  1331. this_parse_mode = "None"
  1332. text_chunk = (
  1333. "!!![invalid markdown syntax]!!!\n\n"
  1334. + text_chunk
  1335. )
  1336. elif parse_mode != "None":
  1337. this_parse_mode = "Markdown"
  1338. # Check that all markdowns are well-formed
  1339. if not markdown_check(
  1340. text_chunk,
  1341. [
  1342. "*", "_", "`"
  1343. ]
  1344. ):
  1345. this_parse_mode = "None"
  1346. text_chunk = (
  1347. "!!![invalid markdown syntax]!!!\n\n"
  1348. + text_chunk
  1349. )
  1350. else:
  1351. this_parse_mode = parse_mode
  1352. this_reply_markup = reply_markup if n == 0 else None
  1353. try:
  1354. await self.avoid_flooding(chat_id)
  1355. result = await self.sendMessage(
  1356. chat_id=chat_id,
  1357. text=text_chunk,
  1358. parse_mode=this_parse_mode,
  1359. disable_web_page_preview=disable_web_page_preview,
  1360. disable_notification=disable_notification,
  1361. reply_to_message_id=reply_to_message_id,
  1362. reply_markup=this_reply_markup
  1363. )
  1364. except Exception as e:
  1365. logging.debug(
  1366. e,
  1367. exc_info=False # Set exc_info=True for more information
  1368. )
  1369. result = e
  1370. return result
  1371. async def send_photo(self, chat_id=None, answer={},
  1372. photo=None, caption='', parse_mode='HTML',
  1373. disable_notification=None, reply_to_message_id=None,
  1374. reply_markup=None, use_stored=True,
  1375. second_chance=False):
  1376. """Send a photo.
  1377. Convenient method to call telepot.Bot(token).sendPhoto
  1378. All sendPhoto **kwargs can be either **kwargs of send_message
  1379. or key:val of answer argument.
  1380. Captions longer than telegram limit will be shortened gently.
  1381. Telegram flood limits won't be reached thanks to
  1382. `await avoid_flooding(chat_id)`
  1383. Most arguments will be checked and adapted.
  1384. If use_stored is set to True, the bot will store sent photo
  1385. telegram_id and use it for faster sending next times (unless
  1386. future errors).
  1387. Sending photos by their file_id already stored on telegram servers
  1388. is way faster: that's why bot stores and uses this info,
  1389. if required.
  1390. A second_chance is given to send photo on error.
  1391. """
  1392. if 'chat_id' in answer:
  1393. chat_id = answer['chat_id']
  1394. # chat_id may simply be the update to which the bot should repy
  1395. if type(chat_id) is dict:
  1396. chat_id = self.get_chat_id(chat_id)
  1397. assert (
  1398. type(chat_id) is int
  1399. or (type(chat_id) is str and chat_id.startswith('@'))
  1400. ), "Invalid chat_id:\n\t\t{}".format(chat_id)
  1401. if 'photo' in answer:
  1402. photo = answer['photo']
  1403. assert photo is not None, "Null photo!"
  1404. if 'caption' in answer:
  1405. caption = answer['caption']
  1406. if 'parse_mode' in answer:
  1407. parse_mode = answer['parse_mode']
  1408. if 'disable_notification' in answer:
  1409. disable_notification = answer['disable_notification']
  1410. if 'reply_to_message_id' in answer:
  1411. reply_to_message_id = answer['reply_to_message_id']
  1412. if 'reply_markup' in answer:
  1413. reply_markup = answer['reply_markup']
  1414. already_sent = False
  1415. if type(photo) is str:
  1416. photo_url = photo
  1417. with self.db as db:
  1418. already_sent = db['sent_pictures'].find_one(
  1419. url=photo_url,
  1420. errors=False
  1421. )
  1422. if already_sent and use_stored:
  1423. photo = already_sent['file_id']
  1424. already_sent = True
  1425. else:
  1426. already_sent = False
  1427. if not any(photo_url.startswith(x) for x in ['http', 'www']):
  1428. with io.BytesIO() as buffered_picture:
  1429. with open(
  1430. "{}/{}".format(
  1431. self.path,
  1432. photo_url
  1433. ),
  1434. 'rb'
  1435. ) as photo_file:
  1436. buffered_picture.write(photo_file.read())
  1437. photo = buffered_picture.getvalue()
  1438. else:
  1439. use_stored = False
  1440. caption = escape_html_chars(caption)
  1441. if len(caption) > 199:
  1442. new_caption = ''
  1443. tag = False
  1444. tag_body = False
  1445. count = 0
  1446. temp = ''
  1447. for char in caption:
  1448. if tag and char == '>':
  1449. tag = False
  1450. elif char == '<':
  1451. tag = True
  1452. tag_body = not tag_body
  1453. elif not tag:
  1454. count += 1
  1455. if count == 199:
  1456. break
  1457. temp += char
  1458. if not tag_body:
  1459. new_caption += temp
  1460. temp = ''
  1461. caption = new_caption
  1462. sent = None
  1463. try:
  1464. await self.avoid_flooding(chat_id)
  1465. sent = await self.sendPhoto(
  1466. chat_id=chat_id,
  1467. photo=photo,
  1468. caption=caption,
  1469. parse_mode=parse_mode,
  1470. disable_notification=disable_notification,
  1471. reply_to_message_id=reply_to_message_id,
  1472. reply_markup=reply_markup
  1473. )
  1474. if isinstance(sent, Exception):
  1475. raise Exception("SendingFailed")
  1476. except Exception as e:
  1477. logging.error(
  1478. "Error sending photo\n{}".format(
  1479. e
  1480. ),
  1481. exc_info=False # Set exc_info=True for more information
  1482. )
  1483. if already_sent:
  1484. with self.db as db:
  1485. db['sent_pictures'].update(
  1486. dict(
  1487. url=photo_url,
  1488. errors=True
  1489. ),
  1490. ['url']
  1491. )
  1492. if not second_chance:
  1493. logging.info("Trying again (only once)...")
  1494. sent = await self.send_photo(
  1495. chat_id=chat_id,
  1496. answer=answer,
  1497. photo=photo,
  1498. caption=caption,
  1499. parse_mode=parse_mode,
  1500. disable_notification=disable_notification,
  1501. reply_to_message_id=reply_to_message_id,
  1502. reply_markup=reply_markup,
  1503. second_chance=True
  1504. )
  1505. if (
  1506. sent is not None
  1507. and hasattr(sent, '__getitem__')
  1508. and 'photo' in sent
  1509. and len(sent['photo']) > 0
  1510. and 'file_id' in sent['photo'][0]
  1511. and (not already_sent)
  1512. and use_stored
  1513. ):
  1514. with self.db as db:
  1515. db['sent_pictures'].insert(
  1516. dict(
  1517. url=photo_url,
  1518. file_id=sent['photo'][0]['file_id'],
  1519. errors=False
  1520. )
  1521. )
  1522. return sent
  1523. async def forward_message(self, chat_id, update=None, from_chat_id=None,
  1524. message_id=None, disable_notification=False):
  1525. """Forward message from `from_chat_id` to `chat_id`.
  1526. Set disable_notification to True to avoid disturbing recipient.
  1527. """
  1528. try:
  1529. if from_chat_id is None or message_id is None:
  1530. if (
  1531. type(update) is not dict
  1532. or 'chat' not in update
  1533. or 'id' not in update['chat']
  1534. or message_id not in update
  1535. ):
  1536. raise Exception("Wrong parameters, cannot forward.")
  1537. from_chat_id = update['chat']['id']
  1538. message_id = update['message_id']
  1539. await self.avoid_flooding(chat_id)
  1540. sent = await self.forwardMessage(
  1541. chat_id=chat_id,
  1542. from_chat_id=from_chat_id,
  1543. disable_notification=disable_notification,
  1544. message_id=message_id,
  1545. )
  1546. if isinstance(sent, Exception):
  1547. raise Exception("Forwarding failed.")
  1548. except Exception as e:
  1549. logging.error(
  1550. "Error sending photo\n{}".format(
  1551. e
  1552. ),
  1553. exc_info=False # Set exc_info=True for more information
  1554. )
  1555. async def send_and_destroy(self, chat_id, answer,
  1556. timer=60, mode='text', **kwargs):
  1557. """Send a message or photo and delete it after `timer` seconds."""
  1558. if mode == 'text':
  1559. sent_message = await self.send_message(
  1560. chat_id=chat_id,
  1561. answer=answer,
  1562. **kwargs
  1563. )
  1564. elif mode == 'pic':
  1565. sent_message = await self.send_photo(
  1566. chat_id=chat_id,
  1567. answer=answer,
  1568. **kwargs
  1569. )
  1570. if sent_message is None:
  1571. return
  1572. self.to_be_destroyed.append(sent_message)
  1573. await asyncio.sleep(timer)
  1574. if await self.delete_message(sent_message):
  1575. self.to_be_destroyed.remove(sent_message)
  1576. return
  1577. async def wait_and_obscure(self, update, when, inline_message_id):
  1578. """Obscure messages which can't be deleted.
  1579. Obscure an inline_message `timer` seconds after sending it,
  1580. by editing its text or caption.
  1581. At the moment Telegram won't let bots delete sent inline query results.
  1582. """
  1583. if type(when) is int:
  1584. when = datetime.datetime.now() + datetime.timedelta(seconds=when)
  1585. assert type(when) is datetime.datetime, (
  1586. "when must be a datetime instance or a number of seconds (int) "
  1587. "to be awaited"
  1588. )
  1589. if 'inline_message_id' not in update:
  1590. logging.info(
  1591. "This inline query result owns no inline_keyboard, so it "
  1592. "can't be modified"
  1593. )
  1594. return
  1595. inline_message_id = update['inline_message_id']
  1596. self.to_be_obscured.append(inline_message_id)
  1597. while datetime.datetime.now() < when:
  1598. await sleep_until(when)
  1599. try:
  1600. await self.editMessageCaption(
  1601. inline_message_id,
  1602. text="Time over"
  1603. )
  1604. except Exception:
  1605. try:
  1606. await self.editMessageText(
  1607. inline_message_id,
  1608. text="Time over"
  1609. )
  1610. except Exception as e:
  1611. logging.error(
  1612. "Couldn't obscure message\n{}\n\n{}".format(
  1613. inline_message_id,
  1614. e
  1615. )
  1616. )
  1617. self.to_be_obscured.remove(inline_message_id)
  1618. return
  1619. async def get_me(self):
  1620. """Get bot information.
  1621. Restart bots if bot can't be got.
  1622. """
  1623. try:
  1624. me = await self.getMe()
  1625. self.bot_name = me["username"]
  1626. self.telegram_id = me['id']
  1627. except Exception as e:
  1628. logging.error(
  1629. "Could not get bot\n{e}".format(
  1630. e=e
  1631. )
  1632. )
  1633. await asyncio.sleep(5*60)
  1634. self.restart_bots()
  1635. return
  1636. async def continue_running(self):
  1637. """Get updates.
  1638. If bot can be got, sets name and telegram_id,
  1639. awaits preliminary tasks and starts getting updates from telegram.
  1640. If bot can't be got, restarts all bots in 5 minutes.
  1641. """
  1642. await self.get_me()
  1643. for task in self.run_before_loop:
  1644. await task()
  1645. self.set_default_keyboard()
  1646. asyncio.ensure_future(
  1647. self.message_loop(handler=self.routing_table)
  1648. )
  1649. return
  1650. def stop_bots(self):
  1651. """Exit script with code 0."""
  1652. Bot.stop = True
  1653. def restart_bots(self):
  1654. """Restart the script exiting with code 65.
  1655. Actually, you need to catch Bot.stop state when Bot.run() returns
  1656. and handle the situation yourself.
  1657. """
  1658. Bot.stop = "Restart"
  1659. @classmethod
  1660. async def check_task(cls):
  1661. """Await until cls.stop, then end session and return."""
  1662. for bot in cls.instances.values():
  1663. asyncio.ensure_future(bot.continue_running())
  1664. while not cls.stop:
  1665. await asyncio.sleep(10)
  1666. return await cls.end_session()
  1667. @classmethod
  1668. async def end_session(cls):
  1669. """Run after stop, before the script exits.
  1670. Await final tasks, obscure and delete pending messages,
  1671. log current operation (stop/restart).
  1672. """
  1673. for bot in cls.instances.values():
  1674. for task in bot.run_after_loop:
  1675. await task()
  1676. for message in bot.to_be_destroyed:
  1677. try:
  1678. await bot.delete_message(message)
  1679. except Exception as e:
  1680. logging.error(
  1681. "Couldn't delete message\n{}\n\n{}".format(
  1682. message,
  1683. e
  1684. )
  1685. )
  1686. for inline_message_id in bot.to_be_obscured:
  1687. try:
  1688. await bot.editMessageCaption(
  1689. inline_message_id,
  1690. text="Time over"
  1691. )
  1692. except Exception:
  1693. try:
  1694. await bot.editMessageText(
  1695. inline_message_id,
  1696. text="Time over"
  1697. )
  1698. except Exception as e:
  1699. logging.error(
  1700. "Couldn't obscure message\n{}\n\n{}".format(
  1701. inline_message_id,
  1702. e
  1703. )
  1704. )
  1705. if cls.stop == "Restart":
  1706. logging.info("\n\t\t---Restart!---")
  1707. elif cls.stop == "KeyboardInterrupt":
  1708. logging.info("Stopped by KeyboardInterrupt.")
  1709. else:
  1710. logging.info("Stopped gracefully by user.")
  1711. return
  1712. @classmethod
  1713. def run(cls, loop=None):
  1714. """Call this method to run the async bots."""
  1715. if loop is None:
  1716. loop = asyncio.get_event_loop()
  1717. logging.info(
  1718. "{sep}{subjvb} STARTED{sep}".format(
  1719. sep='-'*10,
  1720. subjvb='BOT HAS' if len(cls.instances) == 1 else 'BOTS HAVE'
  1721. )
  1722. )
  1723. try:
  1724. loop.run_until_complete(cls.check_task())
  1725. except KeyboardInterrupt:
  1726. logging.info(
  1727. (
  1728. "\n\t\tYour script received a KeyboardInterrupt signal, "
  1729. "your bot{} being stopped."
  1730. ).format(
  1731. 's are'
  1732. if len(cls.instances) > 1
  1733. else ' is'
  1734. )
  1735. )
  1736. cls.stop = "KeyboardInterrupt"
  1737. loop.run_until_complete(cls.end_session())
  1738. except Exception as e:
  1739. logging.error(
  1740. '\nYour bot{vb} been stopped. with error \'{e}\''.format(
  1741. e=e,
  1742. vb='s have' if len(cls.instances) > 1 else ' has'
  1743. ),
  1744. exc_info=True
  1745. )
  1746. logging.info(
  1747. "{sep}{subjvb} STOPPED{sep}".format(
  1748. sep='-'*10,
  1749. subjvb='BOT HAS' if len(cls.instances) == 1 else 'BOTS HAVE'
  1750. )
  1751. )
  1752. return
  1753. @classmethod
  1754. async def _run_manual_mode(cls):
  1755. available_bots = MyOD()
  1756. for code, bot in enumerate(
  1757. cls.instances.values()
  1758. ):
  1759. await bot.get_me()
  1760. available_bots[code] = dict(
  1761. bot=bot,
  1762. code=code,
  1763. name=bot.name
  1764. )
  1765. selected_bot = None
  1766. while selected_bot is None:
  1767. user_input = input(
  1768. "\n=============================================\n"
  1769. "Which bot would you like to control manually?\n"
  1770. "Available bots:\n{}\n\n\t\t".format(
  1771. line_drawing_unordered_list(
  1772. list(
  1773. "{b[code]:>3} - {b[bot].name}".format(
  1774. b=bot,
  1775. )
  1776. for bot in available_bots.values()
  1777. )
  1778. )
  1779. )
  1780. )
  1781. if (
  1782. user_input.isnumeric()
  1783. and int(user_input) in available_bots
  1784. ):
  1785. selected_bot = available_bots[int(user_input)]
  1786. else:
  1787. selected_bot = pick_most_similar_from_list(
  1788. [
  1789. bot['name']
  1790. for bot in available_bots.values()
  1791. ],
  1792. user_input
  1793. )
  1794. selected_bot = available_bots.get_by_key_val(
  1795. key='name',
  1796. val=selected_bot,
  1797. case_sensitive=False,
  1798. return_value=True
  1799. )
  1800. if selected_bot is None:
  1801. logging.error("Invalid selection.")
  1802. continue
  1803. logging.info(
  1804. "Bot `{b[name]}` selected.".format(
  1805. b=selected_bot
  1806. )
  1807. )
  1808. exit_code = await selected_bot['bot']._run_manually()
  1809. if exit_code == 0:
  1810. break
  1811. elif exit_code == 65:
  1812. selected_bot = None
  1813. return
  1814. @classmethod
  1815. def run_manual_mode(cls, loop=None):
  1816. """Run in manual mode: send messages via bots."""
  1817. if loop is None:
  1818. loop = asyncio.get_event_loop()
  1819. logging.info(
  1820. "=== MANUAL MODE STARTED ==="
  1821. )
  1822. try:
  1823. loop.run_until_complete(
  1824. cls._run_manual_mode()
  1825. )
  1826. except KeyboardInterrupt:
  1827. logging.info(
  1828. (
  1829. "\n\t\tYour script received a KeyboardInterrupt signal, "
  1830. "your bot{} being stopped."
  1831. ).format(
  1832. 's are' if len(cls.instances) > 1 else ' is'
  1833. )
  1834. )
  1835. except Exception as e:
  1836. logging.error(
  1837. '\nYour bot{vb} been stopped. with error \'{e}\''.format(
  1838. e=e,
  1839. vb='s have' if len(cls.instances) > 1 else ' has'
  1840. ),
  1841. exc_info=True
  1842. )
  1843. logging.info(
  1844. "=== MANUAL MODE STOPPED ==="
  1845. )
  1846. async def _run_manually(self):
  1847. user_input = ' choose_addressee'
  1848. selected_user = None
  1849. users = []
  1850. while user_input:
  1851. if user_input == ' choose_addressee':
  1852. try:
  1853. user_input = input(
  1854. "Choose an addressee.\n"
  1855. "Press enter to change bot.\n"
  1856. "\n\t\t"
  1857. )
  1858. if len(user_input) == 0:
  1859. return 65 # Let user select a different bot
  1860. except KeyboardInterrupt:
  1861. logging.error("Keyboard interrupt.")
  1862. return 0 # Stop running
  1863. if (
  1864. selected_user is None
  1865. and user_input.strip('-').isnumeric()
  1866. ):
  1867. user_input = int(user_input)
  1868. users = list(
  1869. filter(
  1870. lambda user: user['telegram_id'] == user_input,
  1871. users
  1872. )
  1873. )
  1874. if len(users) == 0:
  1875. users = [
  1876. dict(
  1877. telegram_id=user_input,
  1878. name='Unknown user'
  1879. )
  1880. ]
  1881. elif (
  1882. selected_user is None
  1883. and self.db_url is not None
  1884. ):
  1885. with self.db as db:
  1886. if 'users' not in db.tables:
  1887. db['users'].insert(
  1888. dict(
  1889. telegram_id=0,
  1890. privileges=100,
  1891. username='username',
  1892. first_name='first_name',
  1893. last_name='last_name'
  1894. )
  1895. )
  1896. if 'contacts' not in db.tables:
  1897. db['contacts'].insert(
  1898. dict(
  1899. telegram_id=0,
  1900. name='ZZZXXXAAA',
  1901. )
  1902. )
  1903. users = list(
  1904. db.query(
  1905. """SELECT telegram_id, MAX(name) name
  1906. FROM (
  1907. SELECT telegram_id,
  1908. COALESCE(
  1909. first_name || ' ' || last_name ||
  1910. ' (' || username || ')',
  1911. username,
  1912. first_name || ' ' || last_name,
  1913. last_name,
  1914. first_name
  1915. ) AS name
  1916. FROM users
  1917. WHERE COALESCE(
  1918. first_name || last_name || username,
  1919. first_name || username,
  1920. last_name || username,
  1921. first_name || last_name,
  1922. username,
  1923. last_name,
  1924. first_name
  1925. )
  1926. LIKE '%{u}%'
  1927. UNION ALL
  1928. SELECT telegram_id, name
  1929. FROM contacts
  1930. WHERE name LIKE '%{u}%'
  1931. )
  1932. GROUP BY telegram_id
  1933. """.format(
  1934. u=user_input
  1935. )
  1936. )
  1937. )
  1938. if len(users) == 0:
  1939. logging.info("Sorry, no user matches your query.")
  1940. user_input = ' choose_addressee'
  1941. elif len(users) > 1:
  1942. user_input = input(
  1943. "Please select one of the following users:\n"
  1944. "\n"
  1945. "{users}\n"
  1946. "\n"
  1947. "Paste their telegram_id\n"
  1948. "\t\t".format(
  1949. users=line_drawing_unordered_list(
  1950. sorted(
  1951. map(
  1952. lambda user: (
  1953. "{u[telegram_id]} - {u[name]}"
  1954. ).format(
  1955. u=user
  1956. ),
  1957. users
  1958. )
  1959. )
  1960. )
  1961. )
  1962. )
  1963. elif len(users) == 1:
  1964. selected_user = users[0]
  1965. while selected_user is not None:
  1966. sent = None
  1967. text = input(
  1968. "What would you like to send "
  1969. "{u[name]} ({u[telegram_id]})?\n"
  1970. "Leave it blank if you want to select another "
  1971. "addressee.\n"
  1972. "\t\t\t".format(
  1973. u=selected_user
  1974. )
  1975. )
  1976. if len(text) == 0:
  1977. selected_user = None
  1978. user_input = ' choose_addressee'
  1979. elif text.lower() == 'photo':
  1980. caption = input(
  1981. 'Write a caption (you can leave it blank)\n'
  1982. '\t\t\t'
  1983. )
  1984. try:
  1985. with io.BytesIO() as buffered_picture:
  1986. with open(
  1987. '{path}/sendme.png'.format(
  1988. path=self.path
  1989. ),
  1990. 'rb' # Read bytes
  1991. ) as photo_file:
  1992. buffered_picture.write(
  1993. photo_file.read()
  1994. )
  1995. photo = buffered_picture.getvalue()
  1996. sent = await self.send_photo(
  1997. chat_id=selected_user['telegram_id'],
  1998. photo=photo,
  1999. caption=caption,
  2000. parse_mode='HTML',
  2001. use_stored=False
  2002. )
  2003. except Exception as e:
  2004. logging.error(e)
  2005. else:
  2006. try:
  2007. sent = await self.send_message(
  2008. chat_id=selected_user['telegram_id'],
  2009. text=text,
  2010. parse_mode='HTML'
  2011. )
  2012. except Exception as e:
  2013. logging.error(e)
  2014. if (
  2015. sent is not None
  2016. and not isinstance(sent, Exception)
  2017. ):
  2018. logging.info(
  2019. '\n'
  2020. 'Sent message:\n'
  2021. '{s}\n'
  2022. '\n'.format(
  2023. s=sent
  2024. )
  2025. )
  2026. while (
  2027. self.db_url
  2028. and selected_user['name'] == 'Unknown user'
  2029. ):
  2030. new_name = input(
  2031. "Please enter a nickname for this user.\n"
  2032. "Next time you may retrieve their telegram_id "
  2033. "by passing this nickname (or a part of it).\n"
  2034. "\t\t"
  2035. )
  2036. if len(new_name):
  2037. selected_user['name'] = new_name
  2038. with self.db as db:
  2039. db['contacts'].upsert(
  2040. selected_user,
  2041. ['telegram_id'],
  2042. ensure=True
  2043. )
  2044. else:
  2045. logging.info("Invalid name, please try again.")
  2046. return 65 # Keep running, making user select another bot