Queer European MD passionate about IT

custombot.py 85 KB

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