Queer European MD passionate about IT

custombot.py 85 KB

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