Queer European MD passionate about IT

custombot.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  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, user_record=None,
  413. language=None, **format_kwargs):
  414. """Given a list of strings (`fields`), return proper message.
  415. If `language` is not passed, it is extracted from `update`.
  416. If `update` is not passed either, `language` is extracted from
  417. `user_record`.
  418. Fall back to English message if language is not available.
  419. Pass `format_kwargs` to format function.
  420. """
  421. if (
  422. language is None
  423. and isinstance(update, dict)
  424. and 'from' in update
  425. and 'language_code' in update['from']
  426. ):
  427. language = update['from']['language_code']
  428. if (
  429. language is None
  430. and isinstance(user_record, dict)
  431. and 'language_code' in user_record
  432. ):
  433. language = user_record['language_code']
  434. if language is None:
  435. language = 'en'
  436. result = self.messages
  437. for field in fields:
  438. if field not in result:
  439. logging.error(
  440. "Please define self.message{f}".format(
  441. f=''.join(
  442. '[\'{field}\']'.format(
  443. field=field
  444. )
  445. for field in fields
  446. )
  447. )
  448. )
  449. return "Invalid message!"
  450. result = result[field]
  451. if language not in result:
  452. language = extract(
  453. language,
  454. ender='-'
  455. )
  456. if language not in result:
  457. language = 'en'
  458. if language not in result:
  459. logging.error(
  460. "Please define self.message{f}['en']".format(
  461. f=''.join(
  462. '[\'{field}\']'.format(
  463. field=field
  464. )
  465. for field in fields
  466. )
  467. )
  468. )
  469. return "Invalid message!"
  470. return result[language].format(
  471. **format_kwargs
  472. )
  473. async def on_inline_query(self, update):
  474. """Schedule handling of received inline queries.
  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_inline_query(update))
  480. return
  481. async def on_chosen_inline_result(self, update):
  482. """Schedule handling of received chosen inline result events.
  483. Notice that handling is only scheduled, not awaited.
  484. This means that all Bot instances may now handle other requests
  485. before this one is completed.
  486. """
  487. asyncio.ensure_future(self.handle_chosen_inline_result(update))
  488. return
  489. async def on_callback_query(self, update):
  490. """Schedule handling of received callback queries.
  491. A callback query is sent when users press inline keyboard buttons.
  492. Bad clients may send malformed or deceiving callback queries:
  493. never use secret keys in buttons and always check request validity!
  494. Notice that handling is only scheduled, not awaited.
  495. This means that all Bot instances may now handle other requests
  496. before this one is completed.
  497. """
  498. # Reject malformed updates lacking of data field
  499. if 'data' not in update:
  500. return
  501. asyncio.ensure_future(self.handle_callback_query(update))
  502. return
  503. async def on_chat_message(self, update):
  504. """Schedule handling of received chat message.
  505. Notice that handling is only scheduled, not awaited.
  506. According to update type, the corresponding handler is
  507. scheduled (see self.chat_message_handlers).
  508. This means that all Bot instances may now handle other
  509. requests before this one is completed.
  510. """
  511. answer = None
  512. content_type, chat_type, chat_id = telepot.glance(
  513. update,
  514. flavor='chat',
  515. long=False
  516. )
  517. if content_type in self.chat_message_handlers:
  518. answer = asyncio.ensure_future(
  519. self.chat_message_handlers[content_type](update)
  520. )
  521. else:
  522. answer = None
  523. logging.debug("Unhandled message")
  524. return answer
  525. async def handle_inline_query(self, update):
  526. """Handle inline query and answer it with results, or log errors."""
  527. query = update['query']
  528. answer = None
  529. switch_pm_text, switch_pm_parameter = None, None
  530. if self.maintenance:
  531. answer = self.maintenance_message
  532. else:
  533. for condition, handler in self.inline_query_handlers.items():
  534. answerer = handler['function']
  535. if condition(update['query']):
  536. if asyncio.iscoroutinefunction(answerer):
  537. answer = await answerer(update)
  538. else:
  539. answer = answerer(update)
  540. break
  541. if not answer:
  542. answer = self.default_inline_query_answer
  543. if type(answer) is dict:
  544. if 'switch_pm_text' in answer:
  545. switch_pm_text = answer['switch_pm_text']
  546. if 'switch_pm_parameter' in answer:
  547. switch_pm_parameter = answer['switch_pm_parameter']
  548. answer = answer['answer']
  549. if type(answer) is str:
  550. answer = make_inline_query_answer(answer)
  551. try:
  552. await self.answerInlineQuery(
  553. update['id'],
  554. answer,
  555. cache_time=10,
  556. is_personal=True,
  557. switch_pm_text=switch_pm_text,
  558. switch_pm_parameter=switch_pm_parameter
  559. )
  560. except Exception as e:
  561. logging.info("Error answering inline query\n{}".format(e))
  562. return
  563. async def handle_chosen_inline_result(self, update):
  564. """When an inline query result is chosen, perform an action.
  565. If chosen inline result id is in self.chosen_inline_result_handlers,
  566. call the related function passing the update as argument.
  567. """
  568. user_id = update['from']['id'] if 'from' in update else None
  569. if self.maintenance:
  570. return
  571. if user_id in self.chosen_inline_result_handlers:
  572. result_id = update['result_id']
  573. handlers = self.chosen_inline_result_handlers[user_id]
  574. if result_id in handlers:
  575. func = handlers[result_id]
  576. if asyncio.iscoroutinefunction(func):
  577. await func(update)
  578. else:
  579. func(update)
  580. return
  581. def set_inline_result_handler(self, user_id, result_id, func):
  582. """Associate a func to a result_id.
  583. When an inline result is chosen having that id, function will
  584. be passed the update as argument.
  585. """
  586. if type(user_id) is dict:
  587. user_id = user_id['from']['id']
  588. assert type(user_id) is int, "user_id must be int!"
  589. # Query result ids are parsed as str by telegram
  590. result_id = str(result_id)
  591. assert callable(func), "func must be a callable"
  592. if user_id not in self.chosen_inline_result_handlers:
  593. self.chosen_inline_result_handlers[user_id] = {}
  594. self.chosen_inline_result_handlers[user_id][result_id] = func
  595. return
  596. async def handle_callback_query(self, update):
  597. """Answer callback queries.
  598. Call the callback handler associated to the query prefix.
  599. The answer is used to edit the source message or send new ones
  600. if text is longer than single message limit.
  601. Anyway, the query is answered, otherwise the client would hang and
  602. the bot would look like idle.
  603. """
  604. answer = None
  605. if self.maintenance:
  606. answer = remove_html_tags(self.maintenance_message[:45])
  607. else:
  608. data = update['data']
  609. for start_text, handler in self.callback_handlers.items():
  610. answerer = handler['function']
  611. if data.startswith(start_text):
  612. if asyncio.iscoroutinefunction(answerer):
  613. answer = await answerer(update)
  614. else:
  615. answer = answerer(update)
  616. break
  617. if answer:
  618. if type(answer) is str:
  619. answer = {'text': answer}
  620. if type(answer) is not dict:
  621. return
  622. if 'edit' in answer:
  623. if 'message' in update:
  624. message_identifier = telepot.message_identifier(
  625. update['message']
  626. )
  627. else:
  628. message_identifier = telepot.message_identifier(update)
  629. edit = answer['edit']
  630. reply_markup = (
  631. edit['reply_markup']
  632. if 'reply_markup' in edit
  633. else None
  634. )
  635. text = (
  636. edit['text']
  637. if 'text' in edit
  638. else None
  639. )
  640. caption = (
  641. edit['caption']
  642. if 'caption' in edit
  643. else None
  644. )
  645. parse_mode = (
  646. edit['parse_mode']
  647. if 'parse_mode' in edit
  648. else None
  649. )
  650. disable_web_page_preview = (
  651. edit['disable_web_page_preview']
  652. if 'disable_web_page_preview' in edit
  653. else None
  654. )
  655. try:
  656. if 'text' in edit:
  657. if (
  658. len(text)
  659. > self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 200
  660. ):
  661. if 'from' in update:
  662. await self.send_message(
  663. chat_id=update['from']['id'],
  664. text=text,
  665. reply_markup=reply_markup,
  666. parse_mode=parse_mode,
  667. disable_web_page_preview=(
  668. disable_web_page_preview
  669. )
  670. )
  671. else:
  672. await self.editMessageText(
  673. msg_identifier=message_identifier,
  674. text=text,
  675. parse_mode=parse_mode,
  676. disable_web_page_preview=(
  677. disable_web_page_preview
  678. ),
  679. reply_markup=reply_markup
  680. )
  681. elif 'caption' in edit:
  682. await self.editMessageCaption(
  683. msg_identifier=message_identifier,
  684. caption=caption,
  685. reply_markup=reply_markup
  686. )
  687. elif 'reply_markup' in edit:
  688. await self.editMessageReplyMarkup(
  689. msg_identifier=message_identifier,
  690. reply_markup=reply_markup
  691. )
  692. except Exception as e:
  693. logging.info("Message was not modified:\n{}".format(e))
  694. text = answer['text'][:180] if 'text' in answer else None
  695. show_alert = (
  696. answer['show_alert']
  697. if 'show_alert' in answer
  698. else None
  699. )
  700. cache_time = (
  701. answer['cache_time']
  702. if 'cache_time' in answer
  703. else None
  704. )
  705. try:
  706. await self.answerCallbackQuery(
  707. callback_query_id=update['id'],
  708. text=text,
  709. show_alert=show_alert,
  710. cache_time=cache_time
  711. )
  712. except telepot.exception.TelegramError as e:
  713. logging.error(e)
  714. else:
  715. try:
  716. await self.answerCallbackQuery(callback_query_id=update['id'])
  717. except telepot.exception.TelegramError as e:
  718. logging.error(e)
  719. return
  720. async def handle_text_message(self, update):
  721. """Answer to chat text messages.
  722. 1) Ignore bot name (case-insensitive) and search bot custom parsers,
  723. commands, aliases and parsers for an answerer.
  724. 2) Get an answer from answerer(update).
  725. 3) Send it to the user.
  726. """
  727. answerer, answer = None, None
  728. # Lower text and replace only bot's tag,
  729. # meaning that `/command@OtherBot` will be ignored.
  730. text = update['text'].lower().replace(
  731. '@{}'.format(
  732. self.name.lower()
  733. ),
  734. ''
  735. )
  736. user_id = update['from']['id'] if 'from' in update else None
  737. if self.maintenance and not any(
  738. text.startswith(x)
  739. for x in ('/coma', '/restart')
  740. ):
  741. if update['chat']['id'] > 0:
  742. answer = self.maintenance_message
  743. elif user_id in self.custom_parsers:
  744. answerer = self.custom_parsers[user_id]
  745. del self.custom_parsers[user_id]
  746. elif text.startswith('/'):
  747. command = text.split()[0].strip(' /@')
  748. if command in self.commands:
  749. answerer = self.commands[command]['function']
  750. elif update['chat']['id'] > 0:
  751. answer = self.unknown_command_message
  752. else:
  753. # If text starts with an alias
  754. # Aliases are case insensitive: text and alias are both .lower()
  755. for alias, parser in self.aliases.items():
  756. if text.startswith(alias.lower()):
  757. answerer = parser
  758. break
  759. # If update matches any parser
  760. for check_function, parser in self.parsers.items():
  761. if (
  762. parser['argument'] == 'text'
  763. and check_function(text)
  764. ) or (
  765. parser['argument'] == 'update'
  766. and check_function(update)
  767. ):
  768. answerer = parser['function']
  769. break
  770. if answerer:
  771. if asyncio.iscoroutinefunction(answerer):
  772. answer = await answerer(update)
  773. else:
  774. answer = answerer(update)
  775. if answer:
  776. try:
  777. return await self.send_message(answer=answer, chat_id=update)
  778. except Exception as e:
  779. logging.error(
  780. "Failed to process answer:\n{}".format(e),
  781. exc_info=True
  782. )
  783. async def handle_pinned_message(self, update):
  784. """Handle pinned message chat action."""
  785. if self.maintenance:
  786. return
  787. answerer = None
  788. for criteria, handler in self.chat_actions['pinned'].items():
  789. if criteria(update):
  790. answerer = handler['function']
  791. break
  792. if answerer is None:
  793. return
  794. elif asyncio.iscoroutinefunction(answerer):
  795. answer = await answerer(update)
  796. else:
  797. answer = answerer(update)
  798. if answer:
  799. try:
  800. return await self.send_message(
  801. answer=answer,
  802. chat_id=update['chat']['id']
  803. )
  804. except Exception as e:
  805. logging.error(
  806. "Failed to process answer:\n{}".format(
  807. e
  808. ),
  809. exc_info=True
  810. )
  811. return
  812. async def handle_photo_message(self, update):
  813. """Handle photo chat message."""
  814. user_id = update['from']['id'] if 'from' in update else None
  815. answerer, answer = None, None
  816. if self.maintenance:
  817. if update['chat']['id'] > 0:
  818. answer = self.maintenance_message
  819. elif user_id in self.custom_photo_parsers:
  820. answerer = self.custom_photo_parsers[user_id]
  821. del self.custom_photo_parsers[user_id]
  822. if answerer:
  823. if asyncio.iscoroutinefunction(answerer):
  824. answer = await answerer(update)
  825. else:
  826. answer = answerer(update)
  827. if answer:
  828. try:
  829. return await self.send_message(answer=answer, chat_id=update)
  830. except Exception as e:
  831. logging.error(
  832. "Failed to process answer:\n{}".format(
  833. e
  834. ),
  835. exc_info=True
  836. )
  837. return
  838. def set_custom_parser(self, parser, update=None, user=None):
  839. """Set a custom parser for the user.
  840. Any chat message update coming from the user will be handled by
  841. this custom parser instead of default parsers (commands, aliases
  842. and text parsers).
  843. Custom parsers last one single use, but their handler can call this
  844. function to provide multiple tries.
  845. """
  846. if user and type(user) is int:
  847. pass
  848. elif type(update) is int:
  849. user = update
  850. elif type(user) is dict:
  851. user = (
  852. user['from']['id']
  853. if 'from' in user
  854. and 'id' in user['from']
  855. else None
  856. )
  857. elif not user and type(update) is dict:
  858. user = (
  859. update['from']['id']
  860. if 'from' in update
  861. and 'id' in update['from']
  862. else None
  863. )
  864. else:
  865. raise TypeError(
  866. 'Invalid user.\nuser: {}\nupdate: {}'.format(
  867. user,
  868. update
  869. )
  870. )
  871. if not type(user) is int:
  872. raise TypeError(
  873. 'User {} is not an int id'.format(
  874. user
  875. )
  876. )
  877. if not callable(parser):
  878. raise TypeError(
  879. 'Parser {} is not a callable'.format(
  880. parser.__name__
  881. )
  882. )
  883. self.custom_parsers[user] = parser
  884. return
  885. def set_custom_photo_parser(self, parser, update=None, user=None):
  886. """Set a custom photo parser for the user.
  887. Any photo chat update coming from the user will be handled by
  888. this custom parser instead of default parsers.
  889. Custom photo parsers last one single use, but their handler can
  890. call this function to provide multiple tries.
  891. """
  892. if user and type(user) is int:
  893. pass
  894. elif type(update) is int:
  895. user = update
  896. elif type(user) is dict:
  897. user = (
  898. user['from']['id']
  899. if 'from' in user
  900. and 'id' in user['from']
  901. else None
  902. )
  903. elif not user and type(update) is dict:
  904. user = (
  905. update['from']['id']
  906. if 'from' in update
  907. and 'id' in update['from']
  908. else None
  909. )
  910. else:
  911. raise TypeError(
  912. 'Invalid user.\nuser: {}\nupdate: {}'.format(
  913. user,
  914. update
  915. )
  916. )
  917. if not type(user) is int:
  918. raise TypeError(
  919. 'User {} is not an int id'.format(
  920. user
  921. )
  922. )
  923. if not callable(parser):
  924. raise TypeError(
  925. 'Parser {} is not a callable'.format(
  926. parser.__name__
  927. )
  928. )
  929. self.custom_photo_parsers[user] = parser
  930. return
  931. def command(self, command, aliases=None, show_in_keyboard=False,
  932. descr="", auth='admin'):
  933. """Define a bot command.
  934. Decorator: `@bot.command(*args)`
  935. When a message text starts with `/command[@bot_name]`, or with an
  936. alias, it gets passed to the decorated function.
  937. `command` is the command name (with or without /)
  938. `aliases` is a list of aliases
  939. `show_in_keyboard`, if True, makes first alias appear
  940. in default_keyboard
  941. `descr` is a description
  942. `auth` is the lowest authorization level needed to run the command
  943. """
  944. command = command.replace('/', '').lower()
  945. if not isinstance(command, str):
  946. raise TypeError('Command {} is not a string'.format(command))
  947. if aliases:
  948. if not isinstance(aliases, list):
  949. raise TypeError('Aliases is not a list: {}'.format(aliases))
  950. for alias in aliases:
  951. if not isinstance(alias, str):
  952. raise TypeError('Alias {} is not a string'.format(alias))
  953. def decorator(func):
  954. if asyncio.iscoroutinefunction(func):
  955. async def decorated(message):
  956. logging.info(
  957. "COMMAND({c}) @{n} FROM({f})".format(
  958. c=command,
  959. n=self.name,
  960. f=(
  961. message['from']
  962. if 'from' in message
  963. else message['chat']
  964. )
  965. )
  966. )
  967. if self.authorization_function(message, auth):
  968. return await func(message)
  969. return self.unauthorized_message
  970. else:
  971. def decorated(message):
  972. logging.info(
  973. "COMMAND({c}) @{n} FROM({f})".format(
  974. c=command,
  975. n=self.name,
  976. f=(
  977. message['from']
  978. if 'from' in message
  979. else message['chat']
  980. )
  981. )
  982. )
  983. if self.authorization_function(message, auth):
  984. return func(message)
  985. return self.unauthorized_message
  986. self.commands[command] = dict(
  987. function=decorated,
  988. descr=descr,
  989. auth=auth
  990. )
  991. if aliases:
  992. for alias in aliases:
  993. self.aliases[alias] = decorated
  994. if show_in_keyboard:
  995. self.default_reply_keyboard_elements.append(aliases[0])
  996. return decorator
  997. def parser(self, condition, descr='', auth='admin', argument='text'):
  998. """Define a message parser.
  999. Decorator: `@bot.parser(condition)`
  1000. If condition evaluates True when run on a message text
  1001. (not starting with '/'), such decorated function gets
  1002. called on update.
  1003. Conditions of parsers are evaluated in order; when one is True,
  1004. others will be skipped.
  1005. `descr` is a description
  1006. `auth` is the lowest authorization level needed to run the command
  1007. """
  1008. if not callable(condition):
  1009. raise TypeError(
  1010. 'Condition {} is not a callable'.format(
  1011. condition.__name__
  1012. )
  1013. )
  1014. def decorator(func):
  1015. if asyncio.iscoroutinefunction(func):
  1016. async def decorated(message):
  1017. logging.info(
  1018. "TEXT MATCHING CONDITION({c}) @{n} FROM({f})".format(
  1019. c=condition.__name__,
  1020. n=self.name,
  1021. f=(
  1022. message['from']
  1023. if 'from' in message
  1024. else message['chat']
  1025. )
  1026. )
  1027. )
  1028. if self.authorization_function(message, auth):
  1029. return await func(message)
  1030. return self.unauthorized_message
  1031. else:
  1032. def decorated(message):
  1033. logging.info(
  1034. "TEXT MATCHING CONDITION({c}) @{n} FROM({f})".format(
  1035. c=condition.__name__,
  1036. n=self.name,
  1037. f=(
  1038. message['from']
  1039. if 'from' in message
  1040. else message['chat']
  1041. )
  1042. )
  1043. )
  1044. if self.authorization_function(message, auth):
  1045. return func(message)
  1046. return self.unauthorized_message
  1047. self.parsers[condition] = dict(
  1048. function=decorated,
  1049. descr=descr,
  1050. auth=auth,
  1051. argument=argument
  1052. )
  1053. return decorator
  1054. def pinned(self, condition, descr='', auth='admin'):
  1055. """Handle pinned messages.
  1056. Decorator: `@bot.pinned(condition)`
  1057. If condition evaluates True when run on a pinned_message update,
  1058. such decorated function gets called on update.
  1059. Conditions are evaluated in order; when one is True,
  1060. others will be skipped.
  1061. `descr` is a description
  1062. `auth` is the lowest authorization level needed to run the command
  1063. """
  1064. if not callable(condition):
  1065. raise TypeError(
  1066. 'Condition {c} is not a callable'.format(
  1067. c=condition.__name__
  1068. )
  1069. )
  1070. def decorator(func):
  1071. if asyncio.iscoroutinefunction(func):
  1072. async def decorated(message):
  1073. logging.info(
  1074. "PINNED MESSAGE MATCHING({c}) @{n} FROM({f})".format(
  1075. c=condition.__name__,
  1076. n=self.name,
  1077. f=(
  1078. message['from']
  1079. if 'from' in message
  1080. else message['chat']
  1081. )
  1082. )
  1083. )
  1084. if self.authorization_function(message, auth):
  1085. return await func(message)
  1086. return
  1087. else:
  1088. def decorated(message):
  1089. logging.info(
  1090. "PINNED MESSAGE MATCHING({c}) @{n} FROM({f})".format(
  1091. c=condition.__name__,
  1092. n=self.name,
  1093. f=(
  1094. message['from']
  1095. if 'from' in message
  1096. else message['chat']
  1097. )
  1098. )
  1099. )
  1100. if self.authorization_function(message, auth):
  1101. return func(message)
  1102. return
  1103. self.chat_actions['pinned'][condition] = dict(
  1104. function=decorated,
  1105. descr=descr,
  1106. auth=auth
  1107. )
  1108. return decorator
  1109. def button(self, data, descr='', auth='admin'):
  1110. """Define a bot button.
  1111. Decorator: `@bot.button('example:///')`
  1112. When a callback data text starts with <data>, it gets passed to the
  1113. decorated function
  1114. `descr` is a description
  1115. `auth` is the lowest authorization level needed to run the command
  1116. """
  1117. if not isinstance(data, str):
  1118. raise TypeError(
  1119. 'Inline button callback_data {d} is not a string'.format(
  1120. d=data
  1121. )
  1122. )
  1123. def decorator(func):
  1124. if asyncio.iscoroutinefunction(func):
  1125. async def decorated(message):
  1126. logging.info(
  1127. "INLINE BUTTON({d}) @{n} FROM({f})".format(
  1128. d=message['data'],
  1129. n=self.name,
  1130. f=(
  1131. message['from']
  1132. )
  1133. )
  1134. )
  1135. if self.authorization_function(message, auth):
  1136. return await func(message)
  1137. return self.unauthorized_message
  1138. else:
  1139. def decorated(message):
  1140. logging.info(
  1141. "INLINE BUTTON({d}) @{n} FROM({f})".format(
  1142. d=message['data'],
  1143. n=self.name,
  1144. f=(
  1145. message['from']
  1146. )
  1147. )
  1148. )
  1149. if self.authorization_function(message, auth):
  1150. return func(message)
  1151. return self.unauthorized_message
  1152. self.callback_handlers[data] = dict(
  1153. function=decorated,
  1154. descr=descr,
  1155. auth=auth
  1156. )
  1157. return decorator
  1158. def query(self, condition, descr='', auth='admin'):
  1159. """Define an inline query.
  1160. Decorator: `@bot.query(example)`
  1161. When an inline query matches the `condition` function,
  1162. decorated function is called and passed the query update object
  1163. as argument.
  1164. `descr` is a description
  1165. `auth` is the lowest authorization level needed to run the command
  1166. """
  1167. if not callable(condition):
  1168. raise TypeError(
  1169. 'Condition {c} is not a callable'.format(
  1170. c=condition.__name__
  1171. )
  1172. )
  1173. def decorator(func):
  1174. if asyncio.iscoroutinefunction(func):
  1175. async def decorated(message):
  1176. logging.info(
  1177. "QUERY MATCHING CONDITION({c}) @{n} FROM({f})".format(
  1178. c=condition.__name__,
  1179. n=self.name,
  1180. f=message['from']
  1181. )
  1182. )
  1183. if self.authorization_function(message, auth):
  1184. return await func(message)
  1185. return self.unauthorized_message
  1186. else:
  1187. def decorated(message):
  1188. logging.info(
  1189. "QUERY MATCHING CONDITION({c}) @{n} FROM({f})".format(
  1190. c=condition.__name__,
  1191. n=self.name,
  1192. f=message['from']
  1193. )
  1194. )
  1195. if self.authorization_function(message, auth):
  1196. return func(message)
  1197. return self.unauthorized_message
  1198. self.inline_query_handlers[condition] = dict(
  1199. function=decorated,
  1200. descr=descr,
  1201. auth=auth
  1202. )
  1203. return decorator
  1204. def additional_task(self, when='BEFORE'):
  1205. """Add a task before or after message_loop.
  1206. Decorator: such decorated async functions get awaited BEFORE or
  1207. AFTER messageloop
  1208. """
  1209. when = when[0].lower()
  1210. def decorator(func):
  1211. if when == 'b':
  1212. self.run_before_loop.append(func)
  1213. elif when == 'a':
  1214. self.run_after_loop.append(func)
  1215. return decorator
  1216. def set_default_keyboard(self, keyboard='set_default'):
  1217. """Set a default keyboard for the bot.
  1218. If a keyboard is not passed as argument, a default one is generated,
  1219. based on aliases of commands.
  1220. """
  1221. if keyboard == 'set_default':
  1222. btns = [
  1223. dict(
  1224. text=x
  1225. )
  1226. for x in self.default_reply_keyboard_elements
  1227. ]
  1228. row_len = 2 if len(btns) < 4 else 3
  1229. self._default_keyboard = dict(
  1230. keyboard=make_lines_of_buttons(
  1231. btns,
  1232. row_len
  1233. ),
  1234. resize_keyboard=True
  1235. )
  1236. else:
  1237. self._default_keyboard = keyboard
  1238. return
  1239. async def edit_message(self, update, *args, **kwargs):
  1240. """Edit given update with given *args and **kwargs.
  1241. Please note, that it is currently only possible to edit messages
  1242. without reply_markup or with inline keyboards.
  1243. """
  1244. try:
  1245. return await self.editMessageText(
  1246. telepot.message_identifier(update),
  1247. *args,
  1248. **kwargs
  1249. )
  1250. except Exception as e:
  1251. logging.error("{}".format(e))
  1252. async def delete_message(self, update, *args, **kwargs):
  1253. """Delete given update with given *args and **kwargs.
  1254. Please note, that a bot can delete only messages sent by itself
  1255. or sent in a group which it is administrator of.
  1256. """
  1257. try:
  1258. return await self.deleteMessage(
  1259. telepot.message_identifier(update),
  1260. *args,
  1261. **kwargs
  1262. )
  1263. except Exception as e:
  1264. logging.error("{}".format(e))
  1265. async def send_message(self, answer=dict(), chat_id=None, text='',
  1266. parse_mode="HTML", disable_web_page_preview=None,
  1267. disable_notification=None, reply_to_message_id=None,
  1268. reply_markup=None):
  1269. """Send a message.
  1270. Convenient method to call telepot.Bot(token).sendMessage
  1271. All sendMessage **kwargs can be either **kwargs of send_message
  1272. or key:val of answer argument.
  1273. Messages longer than telegram limit will be split properly.
  1274. Telegram flood limits won't be reached thanks to
  1275. `await avoid_flooding(chat_id)`
  1276. parse_mode will be checked and edited if necessary.
  1277. Arguments will be checked and adapted.
  1278. """
  1279. if type(answer) is dict and 'chat_id' in answer:
  1280. chat_id = answer['chat_id']
  1281. # chat_id may simply be the update to which the bot should repy
  1282. if type(chat_id) is dict:
  1283. chat_id = self.get_chat_id(chat_id)
  1284. if type(answer) is str:
  1285. text = answer
  1286. if (
  1287. not reply_markup
  1288. and chat_id > 0
  1289. and text != self.unauthorized_message
  1290. ):
  1291. reply_markup = self.default_keyboard
  1292. elif type(answer) is dict:
  1293. if 'text' in answer:
  1294. text = answer['text']
  1295. if 'parse_mode' in answer:
  1296. parse_mode = answer['parse_mode']
  1297. if 'disable_web_page_preview' in answer:
  1298. disable_web_page_preview = answer['disable_web_page_preview']
  1299. if 'disable_notification' in answer:
  1300. disable_notification = answer['disable_notification']
  1301. if 'reply_to_message_id' in answer:
  1302. reply_to_message_id = answer['reply_to_message_id']
  1303. if 'reply_markup' in answer:
  1304. reply_markup = answer['reply_markup']
  1305. elif (
  1306. not reply_markup
  1307. and type(chat_id) is int
  1308. and chat_id > 0
  1309. and text != self.unauthorized_message
  1310. ):
  1311. reply_markup = self.default_keyboard
  1312. assert type(text) is str, "Text is not a string!"
  1313. assert (
  1314. type(chat_id) is int
  1315. or (type(chat_id) is str and chat_id.startswith('@'))
  1316. ), "Invalid chat_id:\n\t\t{}".format(chat_id)
  1317. if not text:
  1318. return
  1319. parse_mode = str(parse_mode)
  1320. text_chunks = split_text_gracefully(
  1321. text=text,
  1322. limit=self.__class__.TELEGRAM_MESSAGES_MAX_LEN - 100,
  1323. parse_mode=parse_mode
  1324. )
  1325. n = len(text_chunks)
  1326. for text_chunk in text_chunks:
  1327. n -= 1
  1328. if parse_mode.lower() == "html":
  1329. this_parse_mode = "HTML"
  1330. # Check that all tags are well-formed
  1331. if not markdown_check(
  1332. text_chunk,
  1333. [
  1334. "<", ">",
  1335. "code>", "bold>", "italic>",
  1336. "b>", "i>", "a>", "pre>"
  1337. ]
  1338. ):
  1339. this_parse_mode = "None"
  1340. text_chunk = (
  1341. "!!![invalid markdown syntax]!!!\n\n"
  1342. + text_chunk
  1343. )
  1344. elif parse_mode != "None":
  1345. this_parse_mode = "Markdown"
  1346. # Check that all markdowns are well-formed
  1347. if not markdown_check(
  1348. text_chunk,
  1349. [
  1350. "*", "_", "`"
  1351. ]
  1352. ):
  1353. this_parse_mode = "None"
  1354. text_chunk = (
  1355. "!!![invalid markdown syntax]!!!\n\n"
  1356. + text_chunk
  1357. )
  1358. else:
  1359. this_parse_mode = parse_mode
  1360. this_reply_markup = reply_markup if n == 0 else None
  1361. try:
  1362. await self.avoid_flooding(chat_id)
  1363. result = await self.sendMessage(
  1364. chat_id=chat_id,
  1365. text=text_chunk,
  1366. parse_mode=this_parse_mode,
  1367. disable_web_page_preview=disable_web_page_preview,
  1368. disable_notification=disable_notification,
  1369. reply_to_message_id=reply_to_message_id,
  1370. reply_markup=this_reply_markup
  1371. )
  1372. except Exception as e:
  1373. logging.debug(
  1374. e,
  1375. exc_info=False # Set exc_info=True for more information
  1376. )
  1377. result = e
  1378. return result
  1379. async def send_photo(self, chat_id=None, answer={},
  1380. photo=None, caption='', parse_mode='HTML',
  1381. disable_notification=None, reply_to_message_id=None,
  1382. reply_markup=None, use_stored=True,
  1383. second_chance=False):
  1384. """Send a photo.
  1385. Convenient method to call telepot.Bot(token).sendPhoto
  1386. All sendPhoto **kwargs can be either **kwargs of send_message
  1387. or key:val of answer argument.
  1388. Captions longer than telegram limit will be shortened gently.
  1389. Telegram flood limits won't be reached thanks to
  1390. `await avoid_flooding(chat_id)`
  1391. Most arguments will be checked and adapted.
  1392. If use_stored is set to True, the bot will store sent photo
  1393. telegram_id and use it for faster sending next times (unless
  1394. future errors).
  1395. Sending photos by their file_id already stored on telegram servers
  1396. is way faster: that's why bot stores and uses this info,
  1397. if required.
  1398. A second_chance is given to send photo on error.
  1399. """
  1400. if 'chat_id' in answer:
  1401. chat_id = answer['chat_id']
  1402. # chat_id may simply be the update to which the bot should repy
  1403. if type(chat_id) is dict:
  1404. chat_id = self.get_chat_id(chat_id)
  1405. assert (
  1406. type(chat_id) is int
  1407. or (type(chat_id) is str and chat_id.startswith('@'))
  1408. ), "Invalid chat_id:\n\t\t{}".format(chat_id)
  1409. if 'photo' in answer:
  1410. photo = answer['photo']
  1411. assert photo is not None, "Null photo!"
  1412. if 'caption' in answer:
  1413. caption = answer['caption']
  1414. if 'parse_mode' in answer:
  1415. parse_mode = answer['parse_mode']
  1416. if 'disable_notification' in answer:
  1417. disable_notification = answer['disable_notification']
  1418. if 'reply_to_message_id' in answer:
  1419. reply_to_message_id = answer['reply_to_message_id']
  1420. if 'reply_markup' in answer:
  1421. reply_markup = answer['reply_markup']
  1422. already_sent = False
  1423. if type(photo) is str:
  1424. photo_url = photo
  1425. with self.db as db:
  1426. already_sent = db['sent_pictures'].find_one(
  1427. url=photo_url,
  1428. errors=False
  1429. )
  1430. if already_sent and use_stored:
  1431. photo = already_sent['file_id']
  1432. already_sent = True
  1433. else:
  1434. already_sent = False
  1435. if not any(photo_url.startswith(x) for x in ['http', 'www']):
  1436. with io.BytesIO() as buffered_picture:
  1437. with open(
  1438. "{}/{}".format(
  1439. self.path,
  1440. photo_url
  1441. ),
  1442. 'rb'
  1443. ) as photo_file:
  1444. buffered_picture.write(photo_file.read())
  1445. photo = buffered_picture.getvalue()
  1446. else:
  1447. use_stored = False
  1448. caption = escape_html_chars(caption)
  1449. if len(caption) > 199:
  1450. new_caption = ''
  1451. tag = False
  1452. tag_body = False
  1453. count = 0
  1454. temp = ''
  1455. for char in caption:
  1456. if tag and char == '>':
  1457. tag = False
  1458. elif char == '<':
  1459. tag = True
  1460. tag_body = not tag_body
  1461. elif not tag:
  1462. count += 1
  1463. if count == 199:
  1464. break
  1465. temp += char
  1466. if not tag_body:
  1467. new_caption += temp
  1468. temp = ''
  1469. caption = new_caption
  1470. sent = None
  1471. try:
  1472. await self.avoid_flooding(chat_id)
  1473. sent = await self.sendPhoto(
  1474. chat_id=chat_id,
  1475. photo=photo,
  1476. caption=caption,
  1477. parse_mode=parse_mode,
  1478. disable_notification=disable_notification,
  1479. reply_to_message_id=reply_to_message_id,
  1480. reply_markup=reply_markup
  1481. )
  1482. if isinstance(sent, Exception):
  1483. raise Exception("SendingFailed")
  1484. except Exception as e:
  1485. logging.error(
  1486. "Error sending photo\n{}".format(
  1487. e
  1488. ),
  1489. exc_info=False # Set exc_info=True for more information
  1490. )
  1491. if already_sent:
  1492. with self.db as db:
  1493. db['sent_pictures'].update(
  1494. dict(
  1495. url=photo_url,
  1496. errors=True
  1497. ),
  1498. ['url']
  1499. )
  1500. if not second_chance:
  1501. logging.info("Trying again (only once)...")
  1502. sent = await self.send_photo(
  1503. chat_id=chat_id,
  1504. answer=answer,
  1505. photo=photo,
  1506. caption=caption,
  1507. parse_mode=parse_mode,
  1508. disable_notification=disable_notification,
  1509. reply_to_message_id=reply_to_message_id,
  1510. reply_markup=reply_markup,
  1511. second_chance=True
  1512. )
  1513. if (
  1514. sent is not None
  1515. and hasattr(sent, '__getitem__')
  1516. and 'photo' in sent
  1517. and len(sent['photo']) > 0
  1518. and 'file_id' in sent['photo'][0]
  1519. and (not already_sent)
  1520. and use_stored
  1521. ):
  1522. with self.db as db:
  1523. db['sent_pictures'].insert(
  1524. dict(
  1525. url=photo_url,
  1526. file_id=sent['photo'][0]['file_id'],
  1527. errors=False
  1528. )
  1529. )
  1530. return sent
  1531. async def forward_message(self, chat_id, update=None, from_chat_id=None,
  1532. message_id=None, disable_notification=False):
  1533. """Forward message from `from_chat_id` to `chat_id`.
  1534. Set disable_notification to True to avoid disturbing recipient.
  1535. """
  1536. try:
  1537. if from_chat_id is None or message_id is None:
  1538. if (
  1539. type(update) is not dict
  1540. or 'chat' not in update
  1541. or 'id' not in update['chat']
  1542. or 'message_id' not in update
  1543. ):
  1544. raise Exception("Wrong parameters, cannot forward.")
  1545. from_chat_id = update['chat']['id']
  1546. message_id = update['message_id']
  1547. await self.avoid_flooding(chat_id)
  1548. sent = await self.forwardMessage(
  1549. chat_id=chat_id,
  1550. from_chat_id=from_chat_id,
  1551. disable_notification=disable_notification,
  1552. message_id=message_id,
  1553. )
  1554. if isinstance(sent, Exception):
  1555. raise Exception("Forwarding failed.")
  1556. except Exception as e:
  1557. logging.error(
  1558. "Error forwarding message:\n{}".format(
  1559. e
  1560. ),
  1561. exc_info=False # Set exc_info=True for more information
  1562. )
  1563. async def send_and_destroy(self, chat_id, answer,
  1564. timer=60, mode='text', **kwargs):
  1565. """Send a message or photo and delete it after `timer` seconds."""
  1566. if mode == 'text':
  1567. sent_message = await self.send_message(
  1568. chat_id=chat_id,
  1569. answer=answer,
  1570. **kwargs
  1571. )
  1572. elif mode == 'pic':
  1573. sent_message = await self.send_photo(
  1574. chat_id=chat_id,
  1575. answer=answer,
  1576. **kwargs
  1577. )
  1578. if sent_message is None:
  1579. return
  1580. self.to_be_destroyed.append(sent_message)
  1581. await asyncio.sleep(timer)
  1582. if await self.delete_message(sent_message):
  1583. self.to_be_destroyed.remove(sent_message)
  1584. return
  1585. async def wait_and_obscure(self, update, when, inline_message_id):
  1586. """Obscure messages which can't be deleted.
  1587. Obscure an inline_message `timer` seconds after sending it,
  1588. by editing its text or caption.
  1589. At the moment Telegram won't let bots delete sent inline query results.
  1590. """
  1591. if type(when) is int:
  1592. when = datetime.datetime.now() + datetime.timedelta(seconds=when)
  1593. assert type(when) is datetime.datetime, (
  1594. "when must be a datetime instance or a number of seconds (int) "
  1595. "to be awaited"
  1596. )
  1597. if 'inline_message_id' not in update:
  1598. logging.info(
  1599. "This inline query result owns no inline_keyboard, so it "
  1600. "can't be modified"
  1601. )
  1602. return
  1603. inline_message_id = update['inline_message_id']
  1604. self.to_be_obscured.append(inline_message_id)
  1605. while datetime.datetime.now() < when:
  1606. await sleep_until(when)
  1607. try:
  1608. await self.editMessageCaption(
  1609. inline_message_id,
  1610. text="Time over"
  1611. )
  1612. except Exception:
  1613. try:
  1614. await self.editMessageText(
  1615. inline_message_id,
  1616. text="Time over"
  1617. )
  1618. except Exception as e:
  1619. logging.error(
  1620. "Couldn't obscure message\n{}\n\n{}".format(
  1621. inline_message_id,
  1622. e
  1623. )
  1624. )
  1625. self.to_be_obscured.remove(inline_message_id)
  1626. return
  1627. async def get_me(self):
  1628. """Get bot information.
  1629. Restart bots if bot can't be got.
  1630. """
  1631. try:
  1632. me = await self.getMe()
  1633. self.bot_name = me["username"]
  1634. self.telegram_id = me['id']
  1635. except Exception as e:
  1636. logging.error(
  1637. "Could not get bot\n{e}".format(
  1638. e=e
  1639. )
  1640. )
  1641. await asyncio.sleep(5*60)
  1642. self.restart_bots()
  1643. return
  1644. async def continue_running(self):
  1645. """Get updates.
  1646. If bot can be got, sets name and telegram_id,
  1647. awaits preliminary tasks and starts getting updates from telegram.
  1648. If bot can't be got, restarts all bots in 5 minutes.
  1649. """
  1650. await self.get_me()
  1651. for task in self.run_before_loop:
  1652. await task()
  1653. self.set_default_keyboard()
  1654. asyncio.ensure_future(
  1655. self.message_loop(handler=self.routing_table)
  1656. )
  1657. return
  1658. def stop_bots(self):
  1659. """Exit script with code 0."""
  1660. Bot.stop = True
  1661. def restart_bots(self):
  1662. """Restart the script exiting with code 65.
  1663. Actually, you need to catch Bot.stop state when Bot.run() returns
  1664. and handle the situation yourself.
  1665. """
  1666. Bot.stop = "Restart"
  1667. @classmethod
  1668. async def check_task(cls):
  1669. """Await until cls.stop, then end session and return."""
  1670. for bot in cls.instances.values():
  1671. asyncio.ensure_future(bot.continue_running())
  1672. while not cls.stop:
  1673. await asyncio.sleep(10)
  1674. return await cls.end_session()
  1675. @classmethod
  1676. async def end_session(cls):
  1677. """Run after stop, before the script exits.
  1678. Await final tasks, obscure and delete pending messages,
  1679. log current operation (stop/restart).
  1680. """
  1681. for bot in cls.instances.values():
  1682. for task in bot.run_after_loop:
  1683. await task()
  1684. for message in bot.to_be_destroyed:
  1685. try:
  1686. await bot.delete_message(message)
  1687. except Exception as e:
  1688. logging.error(
  1689. "Couldn't delete message\n{}\n\n{}".format(
  1690. message,
  1691. e
  1692. )
  1693. )
  1694. for inline_message_id in bot.to_be_obscured:
  1695. try:
  1696. await bot.editMessageCaption(
  1697. inline_message_id,
  1698. text="Time over"
  1699. )
  1700. except Exception:
  1701. try:
  1702. await bot.editMessageText(
  1703. inline_message_id,
  1704. text="Time over"
  1705. )
  1706. except Exception as e:
  1707. logging.error(
  1708. "Couldn't obscure message\n{}\n\n{}".format(
  1709. inline_message_id,
  1710. e
  1711. )
  1712. )
  1713. if cls.stop == "Restart":
  1714. logging.info("\n\t\t---Restart!---")
  1715. elif cls.stop == "KeyboardInterrupt":
  1716. logging.info("Stopped by KeyboardInterrupt.")
  1717. else:
  1718. logging.info("Stopped gracefully by user.")
  1719. return
  1720. @classmethod
  1721. def run(cls, loop=None):
  1722. """Call this method to run the async bots."""
  1723. if loop is None:
  1724. loop = asyncio.get_event_loop()
  1725. logging.info(
  1726. "{sep}{subjvb} STARTED{sep}".format(
  1727. sep='-'*10,
  1728. subjvb='BOT HAS' if len(cls.instances) == 1 else 'BOTS HAVE'
  1729. )
  1730. )
  1731. try:
  1732. loop.run_until_complete(cls.check_task())
  1733. except KeyboardInterrupt:
  1734. logging.info(
  1735. (
  1736. "\n\t\tYour script received a KeyboardInterrupt signal, "
  1737. "your bot{} being stopped."
  1738. ).format(
  1739. 's are'
  1740. if len(cls.instances) > 1
  1741. else ' is'
  1742. )
  1743. )
  1744. cls.stop = "KeyboardInterrupt"
  1745. loop.run_until_complete(cls.end_session())
  1746. except Exception as e:
  1747. logging.error(
  1748. '\nYour bot{vb} been stopped. with error \'{e}\''.format(
  1749. e=e,
  1750. vb='s have' if len(cls.instances) > 1 else ' has'
  1751. ),
  1752. exc_info=True
  1753. )
  1754. logging.info(
  1755. "{sep}{subjvb} STOPPED{sep}".format(
  1756. sep='-'*10,
  1757. subjvb='BOT HAS' if len(cls.instances) == 1 else 'BOTS HAVE'
  1758. )
  1759. )
  1760. return
  1761. @classmethod
  1762. async def _run_manual_mode(cls):
  1763. available_bots = MyOD()
  1764. for code, bot in enumerate(
  1765. cls.instances.values()
  1766. ):
  1767. await bot.get_me()
  1768. available_bots[code] = dict(
  1769. bot=bot,
  1770. code=code,
  1771. name=bot.name
  1772. )
  1773. selected_bot = None
  1774. while selected_bot is None:
  1775. user_input = input(
  1776. "\n=============================================\n"
  1777. "Which bot would you like to control manually?\n"
  1778. "Available bots:\n{}\n\n\t\t".format(
  1779. line_drawing_unordered_list(
  1780. list(
  1781. "{b[code]:>3} - {b[bot].name}".format(
  1782. b=bot,
  1783. )
  1784. for bot in available_bots.values()
  1785. )
  1786. )
  1787. )
  1788. )
  1789. if (
  1790. user_input.isnumeric()
  1791. and int(user_input) in available_bots
  1792. ):
  1793. selected_bot = available_bots[int(user_input)]
  1794. else:
  1795. selected_bot = pick_most_similar_from_list(
  1796. [
  1797. bot['name']
  1798. for bot in available_bots.values()
  1799. ],
  1800. user_input
  1801. )
  1802. selected_bot = available_bots.get_by_key_val(
  1803. key='name',
  1804. val=selected_bot,
  1805. case_sensitive=False,
  1806. return_value=True
  1807. )
  1808. if selected_bot is None:
  1809. logging.error("Invalid selection.")
  1810. continue
  1811. logging.info(
  1812. "Bot `{b[name]}` selected.".format(
  1813. b=selected_bot
  1814. )
  1815. )
  1816. exit_code = await selected_bot['bot']._run_manually()
  1817. if exit_code == 0:
  1818. break
  1819. elif exit_code == 65:
  1820. selected_bot = None
  1821. return
  1822. @classmethod
  1823. def run_manual_mode(cls, loop=None):
  1824. """Run in manual mode: send messages via bots."""
  1825. if loop is None:
  1826. loop = asyncio.get_event_loop()
  1827. logging.info(
  1828. "=== MANUAL MODE STARTED ==="
  1829. )
  1830. try:
  1831. loop.run_until_complete(
  1832. cls._run_manual_mode()
  1833. )
  1834. except KeyboardInterrupt:
  1835. logging.info(
  1836. (
  1837. "\n\t\tYour script received a KeyboardInterrupt signal, "
  1838. "your bot{} being stopped."
  1839. ).format(
  1840. 's are' if len(cls.instances) > 1 else ' is'
  1841. )
  1842. )
  1843. except Exception as e:
  1844. logging.error(
  1845. '\nYour bot{vb} been stopped. with error \'{e}\''.format(
  1846. e=e,
  1847. vb='s have' if len(cls.instances) > 1 else ' has'
  1848. ),
  1849. exc_info=True
  1850. )
  1851. logging.info(
  1852. "=== MANUAL MODE STOPPED ==="
  1853. )
  1854. async def _run_manually(self):
  1855. user_input = ' choose_addressee'
  1856. selected_user = None
  1857. users = []
  1858. while user_input:
  1859. if user_input == ' choose_addressee':
  1860. try:
  1861. user_input = input(
  1862. "Choose an addressee.\n"
  1863. "Press enter to change bot.\n"
  1864. "\n\t\t"
  1865. )
  1866. if len(user_input) == 0:
  1867. return 65 # Let user select a different bot
  1868. except KeyboardInterrupt:
  1869. logging.error("Keyboard interrupt.")
  1870. return 0 # Stop running
  1871. if (
  1872. selected_user is None
  1873. and user_input.strip('-').isnumeric()
  1874. ):
  1875. user_input = int(user_input)
  1876. users = list(
  1877. filter(
  1878. lambda user: user['telegram_id'] == user_input,
  1879. users
  1880. )
  1881. )
  1882. if len(users) == 0:
  1883. users = [
  1884. dict(
  1885. telegram_id=user_input,
  1886. name='Unknown user'
  1887. )
  1888. ]
  1889. elif (
  1890. selected_user is None
  1891. and self.db_url is not None
  1892. ):
  1893. with self.db as db:
  1894. if 'users' not in db.tables:
  1895. db['users'].insert(
  1896. dict(
  1897. telegram_id=0,
  1898. privileges=100,
  1899. username='username',
  1900. first_name='first_name',
  1901. last_name='last_name'
  1902. )
  1903. )
  1904. if 'contacts' not in db.tables:
  1905. db['contacts'].insert(
  1906. dict(
  1907. telegram_id=0,
  1908. name='ZZZXXXAAA',
  1909. )
  1910. )
  1911. users = list(
  1912. db.query(
  1913. """SELECT telegram_id, MAX(name) name
  1914. FROM (
  1915. SELECT telegram_id,
  1916. COALESCE(
  1917. first_name || ' ' || last_name ||
  1918. ' (' || username || ')',
  1919. username,
  1920. first_name || ' ' || last_name,
  1921. last_name,
  1922. first_name
  1923. ) AS name
  1924. FROM users
  1925. WHERE COALESCE(
  1926. first_name || last_name || username,
  1927. first_name || username,
  1928. last_name || username,
  1929. first_name || last_name,
  1930. username,
  1931. last_name,
  1932. first_name
  1933. )
  1934. LIKE '%{u}%'
  1935. UNION ALL
  1936. SELECT telegram_id, name
  1937. FROM contacts
  1938. WHERE name LIKE '%{u}%'
  1939. )
  1940. GROUP BY telegram_id
  1941. """.format(
  1942. u=user_input
  1943. )
  1944. )
  1945. )
  1946. if len(users) == 0:
  1947. logging.info("Sorry, no user matches your query.")
  1948. user_input = ' choose_addressee'
  1949. elif len(users) > 1:
  1950. user_input = input(
  1951. "Please select one of the following users:\n"
  1952. "\n"
  1953. "{users}\n"
  1954. "\n"
  1955. "Paste their telegram_id\n"
  1956. "\t\t".format(
  1957. users=line_drawing_unordered_list(
  1958. sorted(
  1959. map(
  1960. lambda user: (
  1961. "{u[telegram_id]} - {u[name]}"
  1962. ).format(
  1963. u=user
  1964. ),
  1965. users
  1966. )
  1967. )
  1968. )
  1969. )
  1970. )
  1971. elif len(users) == 1:
  1972. selected_user = users[0]
  1973. while selected_user is not None:
  1974. sent = None
  1975. text = input(
  1976. "What would you like to send "
  1977. "{u[name]} ({u[telegram_id]})?\n"
  1978. "Leave it blank if you want to select another "
  1979. "addressee.\n"
  1980. "\t\t\t".format(
  1981. u=selected_user
  1982. )
  1983. )
  1984. if len(text) == 0:
  1985. selected_user = None
  1986. user_input = ' choose_addressee'
  1987. elif text.lower() == 'photo':
  1988. caption = input(
  1989. 'Write a caption (you can leave it blank)\n'
  1990. '\t\t\t'
  1991. )
  1992. try:
  1993. with io.BytesIO() as buffered_picture:
  1994. with open(
  1995. '{path}/sendme.png'.format(
  1996. path=self.path
  1997. ),
  1998. 'rb' # Read bytes
  1999. ) as photo_file:
  2000. buffered_picture.write(
  2001. photo_file.read()
  2002. )
  2003. photo = buffered_picture.getvalue()
  2004. sent = await self.send_photo(
  2005. chat_id=selected_user['telegram_id'],
  2006. photo=photo,
  2007. caption=caption,
  2008. parse_mode='HTML',
  2009. use_stored=False
  2010. )
  2011. except Exception as e:
  2012. logging.error(e)
  2013. else:
  2014. try:
  2015. sent = await self.send_message(
  2016. chat_id=selected_user['telegram_id'],
  2017. text=text,
  2018. parse_mode='HTML'
  2019. )
  2020. except Exception as e:
  2021. logging.error(e)
  2022. if (
  2023. sent is not None
  2024. and not isinstance(sent, Exception)
  2025. ):
  2026. logging.info(
  2027. '\n'
  2028. 'Sent message:\n'
  2029. '{s}\n'
  2030. '\n'.format(
  2031. s=sent
  2032. )
  2033. )
  2034. while (
  2035. self.db_url
  2036. and selected_user['name'] == 'Unknown user'
  2037. ):
  2038. new_name = input(
  2039. "Please enter a nickname for this user.\n"
  2040. "Next time you may retrieve their telegram_id "
  2041. "by passing this nickname (or a part of it).\n"
  2042. "\t\t"
  2043. )
  2044. if len(new_name):
  2045. selected_user['name'] = new_name
  2046. with self.db as db:
  2047. db['contacts'].upsert(
  2048. selected_user,
  2049. ['telegram_id'],
  2050. ensure=True
  2051. )
  2052. else:
  2053. logging.info("Invalid name, please try again.")
  2054. return 65 # Keep running, making user select another bot