Queer European MD passionate about IT

custombot.py 79 KB

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