Queer European MD passionate about IT

api.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. """This module provides a glow-like middleware for Telegram bot API.
  2. All methods and parameters are the same as the original json API.
  3. A simple aiohttp asyncronous web client is used to make requests.
  4. """
  5. # Standard library modules
  6. import asyncio
  7. import datetime
  8. import json
  9. import logging
  10. # Third party modules
  11. import aiohttp
  12. from aiohttp import web
  13. class TelegramError(Exception):
  14. """Telegram API exceptions class."""
  15. def __init__(self, error_code=0, description=None, ok=False):
  16. """Get an error response and return corresponding Exception."""
  17. self._code = error_code
  18. if description is None:
  19. self._description = 'Generic error'
  20. else:
  21. self._description = description
  22. super().__init__(self.description)
  23. @property
  24. def code(self):
  25. """Telegram error code."""
  26. return self._code
  27. @property
  28. def description(self):
  29. """Human-readable description of error."""
  30. return f"Error {self.code}: {self._description}"
  31. class TelegramBot(object):
  32. """Provide python method having the same signature as Telegram API methods.
  33. All mirrored methods are camelCase.
  34. """
  35. loop = asyncio.get_event_loop()
  36. app = web.Application(loop=loop)
  37. sessions_timeouts = {
  38. 'getUpdates': dict(
  39. timeout=35,
  40. close=False
  41. ),
  42. 'sendMessage': dict(
  43. timeout=20,
  44. close=False
  45. )
  46. }
  47. _absolute_cooldown_timedelta = datetime.timedelta(seconds=1/30)
  48. _per_chat_cooldown_timedelta = datetime.timedelta(seconds=1)
  49. _allowed_messages_per_group_per_minute = 20
  50. def __init__(self, token):
  51. """Set bot token and store HTTP sessions."""
  52. self._token = token
  53. self.sessions = dict()
  54. self._flood_wait = 0
  55. self.last_sending_time = dict(
  56. absolute=(
  57. datetime.datetime.now()
  58. - self.absolute_cooldown_timedelta
  59. )
  60. )
  61. @property
  62. def token(self):
  63. """Telegram API bot token."""
  64. return self._token
  65. @property
  66. def flood_wait(self):
  67. """Seconds to wait before next API requests."""
  68. return self._flood_wait
  69. @property
  70. def absolute_cooldown_timedelta(self):
  71. """Return time delta to wait between messages (any chat).
  72. Return class value (all bots have the same limits).
  73. """
  74. return self.__class__._absolute_cooldown_timedelta
  75. @property
  76. def per_chat_cooldown_timedelta(self):
  77. """Return time delta to wait between messages in a chat.
  78. Return class value (all bots have the same limits).
  79. """
  80. return self.__class__._per_chat_cooldown_timedelta
  81. @property
  82. def allowed_messages_per_group_per_minute(self):
  83. """Return maximum number of messages allowed in a group per minute.
  84. Group, supergroup and channels are considered.
  85. Return class value (all bots have the same limits).
  86. """
  87. return self.__class__._allowed_messages_per_group_per_minute
  88. @staticmethod
  89. def check_telegram_api_json(response):
  90. """Take a json Telegram response, check it and return its content.
  91. Example of well-formed json Telegram responses:
  92. {
  93. "ok": False,
  94. "error_code": 401,
  95. "description": "Unauthorized"
  96. }
  97. {
  98. "ok": True,
  99. "result": ...
  100. }
  101. """
  102. assert 'ok' in response, (
  103. "All Telegram API responses have an `ok` field."
  104. )
  105. if not response['ok']:
  106. raise TelegramError(**response)
  107. return response['result']
  108. @staticmethod
  109. def adapt_parameters(parameters, exclude=[]):
  110. """Build a aiohttp.FormData object from given `paramters`.
  111. Exclude `self`, empty values and parameters in `exclude` list.
  112. Cast integers to string to avoid TypeError during json serialization.
  113. """
  114. exclude.append('self')
  115. data = aiohttp.FormData()
  116. for key, value in parameters.items():
  117. if not (key in exclude or value is None):
  118. if (
  119. type(value) in (int, list,)
  120. or (type(value) is dict and 'file' not in value)
  121. ):
  122. value = json.dumps(value, separators=(',', ':'))
  123. data.add_field(key, value)
  124. return data
  125. def get_session(self, api_method):
  126. """According to API method, return proper session and information.
  127. Return a tuple (session, session_must_be_closed)
  128. session : aiohttp.ClientSession
  129. Client session with proper timeout
  130. session_must_be_closed : bool
  131. True if session must be closed after being used once
  132. """
  133. cls = self.__class__
  134. if api_method in cls.sessions_timeouts:
  135. if api_method not in self.sessions:
  136. self.sessions[api_method] = aiohttp.ClientSession(
  137. loop=cls.loop,
  138. timeout=aiohttp.ClientTimeout(
  139. total=cls.sessions_timeouts[api_method]['timeout']
  140. )
  141. )
  142. session = self.sessions[api_method]
  143. session_must_be_closed = cls.sessions_timeouts[api_method]['close']
  144. else:
  145. session = aiohttp.ClientSession(
  146. loop=cls.loop,
  147. timeout=aiohttp.ClientTimeout(total=None)
  148. )
  149. session_must_be_closed = True
  150. return session, session_must_be_closed
  151. def set_flood_wait(self, flood_wait):
  152. """Wait `flood_wait` seconds before next request."""
  153. self._flood_wait = flood_wait
  154. async def prevent_flooding(self, chat_id):
  155. """Await until request may be sent safely.
  156. Telegram flood control won't allow too many API requests in a small
  157. period.
  158. Exact limits are unknown, but less than 30 total private chat messages
  159. per second, less than 1 private message per chat and less than 20
  160. group chat messages per chat per minute should be safe.
  161. """
  162. now = datetime.datetime.now
  163. if type(chat_id) is int and chat_id > 0:
  164. while (
  165. now() < (
  166. self.last_sending_time['absolute']
  167. + self.absolute_cooldown_timedelta
  168. )
  169. ) or (
  170. chat_id in self.last_sending_time
  171. and (
  172. now() < (
  173. self.last_sending_time[chat_id]
  174. + self.per_chat_cooldown_timedelta
  175. )
  176. )
  177. ):
  178. await asyncio.sleep(
  179. self.absolute_cooldown_timedelta.seconds
  180. )
  181. self.last_sending_time[chat_id] = now()
  182. else:
  183. while (
  184. now() < (
  185. self.last_sending_time['absolute']
  186. + self.absolute_cooldown_timedelta
  187. )
  188. ) or (
  189. chat_id in self.last_sending_time
  190. and len(
  191. [
  192. sending_datetime
  193. for sending_datetime in self.last_sending_time[chat_id]
  194. if sending_datetime >= (
  195. now()
  196. - datetime.timedelta(minutes=1)
  197. )
  198. ]
  199. ) >= self.allowed_messages_per_group_per_minute
  200. ) or (
  201. chat_id in self.last_sending_time
  202. and len(self.last_sending_time[chat_id]) > 0
  203. and now() < (
  204. self.last_sending_time[chat_id][-1]
  205. + self.per_chat_cooldown_timedelta
  206. )
  207. ):
  208. await asyncio.sleep(0.5)
  209. if chat_id not in self.last_sending_time:
  210. self.last_sending_time[chat_id] = []
  211. self.last_sending_time[chat_id].append(now())
  212. self.last_sending_time[chat_id] = [
  213. sending_datetime
  214. for sending_datetime in self.last_sending_time[chat_id]
  215. if sending_datetime >= (
  216. now()
  217. - self.longest_cooldown_timedelta
  218. )
  219. ]
  220. self.last_sending_time['absolute'] = now()
  221. return
  222. async def api_request(self, method, parameters={}, exclude=[]):
  223. """Return the result of a Telegram bot API request, or an Exception.
  224. Opened sessions will be used more than one time (if appropriate) and
  225. will be closed on `Bot.app.cleanup`.
  226. Result may be a Telegram API json response, None, or Exception.
  227. """
  228. response_object = None
  229. session, session_must_be_closed = self.get_session(method)
  230. # Prevent Telegram flood control for all methodsd having a `chat_id`
  231. if 'chat_id' in parameters:
  232. await self.prevent_flooding(parameters['chat_id'])
  233. parameters = self.adapt_parameters(parameters, exclude=exclude)
  234. try:
  235. async with session.post(
  236. "https://api.telegram.org/bot"
  237. f"{self.token}/{method}",
  238. data=parameters
  239. ) as response:
  240. try:
  241. response_object = self.check_telegram_api_json(
  242. await response.json() # Telegram returns json objects
  243. )
  244. except TelegramError as e:
  245. logging.error(f"API error response - {e}")
  246. if e.code == 420: # Flood error!
  247. try:
  248. flood_wait = int(
  249. e.description.split('_')[-1]
  250. ) + 30
  251. except Exception as e:
  252. logging.error(f"{e}")
  253. flood_wait = 5*60
  254. logging.critical(
  255. "Telegram antiflood control triggered!\n"
  256. f"Wait {flood_wait} seconds before making another "
  257. "request"
  258. )
  259. self.set_flood_wait(flood_wait)
  260. return e
  261. except Exception as e:
  262. logging.error(f"{e}", exc_info=True)
  263. return e
  264. except asyncio.TimeoutError as e:
  265. logging.info(f"{e}: {method} API call timed out")
  266. finally:
  267. if session_must_be_closed:
  268. await session.close()
  269. return response_object
  270. async def getMe(self):
  271. """Get basic information about the bot in form of a User object.
  272. Useful to test `self.token`.
  273. See https://core.telegram.org/bots/api#getme for details.
  274. """
  275. return await self.api_request(
  276. 'getMe',
  277. )
  278. async def getUpdates(self, offset, timeout, limit, allowed_updates):
  279. """Get a list of updates starting from `offset`.
  280. If there are no updates, keep the request hanging until `timeout`.
  281. If there are more than `limit` updates, retrieve them in packs of
  282. `limit`.
  283. Allowed update types (empty list to allow all).
  284. See https://core.telegram.org/bots/api#getupdates for details.
  285. """
  286. return await self.api_request(
  287. method='getUpdates',
  288. parameters=locals()
  289. )
  290. async def setWebhook(self, url=None, certificate=None,
  291. max_connections=None, allowed_updates=None):
  292. """Set or remove a webhook. Telegram will post to `url` new updates.
  293. See https://core.telegram.org/bots/api#setwebhook for details.
  294. """
  295. if url is None:
  296. url = self.webhook_url
  297. if allowed_updates is None:
  298. allowed_updates = self.allowed_updates
  299. if max_connections is None:
  300. max_connections = self.max_connections
  301. if certificate is None:
  302. certificate = self.certificate
  303. if type(certificate) is str:
  304. try:
  305. certificate = dict(
  306. file=open(certificate, 'r')
  307. )
  308. except FileNotFoundError as e:
  309. logging.error(f"{e}\nCertificate set to `None`")
  310. certificate = None
  311. result = await self.api_request(
  312. 'setWebhook',
  313. parameters=locals()
  314. )
  315. if type(certificate) is dict: # Close certificate file, if it was open
  316. certificate['file'].close()
  317. return result
  318. async def deleteWebhook(self):
  319. """Remove webhook integration and switch back to getUpdate.
  320. See https://core.telegram.org/bots/api#deletewebhook for details.
  321. """
  322. return await self.api_request(
  323. 'deleteWebhook',
  324. )
  325. async def getWebhookInfo(self):
  326. """Get current webhook status.
  327. See https://core.telegram.org/bots/api#getwebhookinfo for details.
  328. """
  329. return await self.api_request(
  330. 'getWebhookInfo',
  331. )
  332. async def sendMessage(self, chat_id, text,
  333. parse_mode=None,
  334. disable_web_page_preview=None,
  335. disable_notification=None,
  336. reply_to_message_id=None,
  337. reply_markup=None):
  338. """Send a text message. On success, return it.
  339. See https://core.telegram.org/bots/api#sendmessage for details.
  340. """
  341. return await self.api_request(
  342. 'sendMessage',
  343. parameters=locals()
  344. )
  345. async def forwardMessage(self, chat_id, from_chat_id, message_id,
  346. disable_notification=None):
  347. """Forward a message.
  348. See https://core.telegram.org/bots/api#forwardmessage for details.
  349. """
  350. return await self.api_request(
  351. 'forwardMessage',
  352. parameters=locals()
  353. )
  354. async def sendPhoto(self, chat_id, photo,
  355. caption=None,
  356. parse_mode=None,
  357. disable_notification=None,
  358. reply_to_message_id=None,
  359. reply_markup=None):
  360. """Send a photo from file_id, HTTP url or file.
  361. See https://core.telegram.org/bots/api#sendphoto for details.
  362. """
  363. return await self.api_request(
  364. 'sendPhoto',
  365. parameters=locals()
  366. )
  367. async def sendAudio(self, chat_id, audio,
  368. caption=None,
  369. parse_mode=None,
  370. duration=None,
  371. performer=None,
  372. title=None,
  373. thumb=None,
  374. disable_notification=None,
  375. reply_to_message_id=None,
  376. reply_markup=None):
  377. """Send an audio file from file_id, HTTP url or file.
  378. See https://core.telegram.org/bots/api#sendaudio for details.
  379. """
  380. return await self.api_request(
  381. 'sendAudio',
  382. parameters=locals()
  383. )
  384. async def sendDocument(self, chat_id, document,
  385. thumb=None,
  386. caption=None,
  387. parse_mode=None,
  388. disable_notification=None,
  389. reply_to_message_id=None,
  390. reply_markup=None):
  391. """Send a document from file_id, HTTP url or file.
  392. See https://core.telegram.org/bots/api#senddocument for details.
  393. """
  394. return await self.api_request(
  395. 'sendDocument',
  396. parameters=locals()
  397. )
  398. async def sendVideo(self, chat_id, video,
  399. duration=None,
  400. width=None,
  401. height=None,
  402. thumb=None,
  403. caption=None,
  404. parse_mode=None,
  405. supports_streaming=None,
  406. disable_notification=None,
  407. reply_to_message_id=None,
  408. reply_markup=None):
  409. """Send a video from file_id, HTTP url or file.
  410. See https://core.telegram.org/bots/api#sendvideo for details.
  411. """
  412. return await self.api_request(
  413. 'sendVideo',
  414. parameters=locals()
  415. )
  416. async def sendAnimation(self, chat_id, animation,
  417. duration=None,
  418. width=None,
  419. height=None,
  420. thumb=None,
  421. caption=None,
  422. parse_mode=None,
  423. disable_notification=None,
  424. reply_to_message_id=None,
  425. reply_markup=None):
  426. """Send animation files (GIF or H.264/MPEG-4 AVC video without sound).
  427. See https://core.telegram.org/bots/api#sendanimation for details.
  428. """
  429. return await self.api_request(
  430. 'sendAnimation',
  431. parameters=locals()
  432. )
  433. async def sendVoice(self, chat_id, voice,
  434. caption=None,
  435. parse_mode=None,
  436. duration=None,
  437. disable_notification=None,
  438. reply_to_message_id=None,
  439. reply_markup=None):
  440. """Send an audio file to be displayed as playable voice message.
  441. `voice` must be in an .ogg file encoded with OPUS.
  442. See https://core.telegram.org/bots/api#sendvoice for details.
  443. """
  444. return await self.api_request(
  445. 'sendVoice',
  446. parameters=locals()
  447. )
  448. async def sendVideoNote(self, chat_id, video_note,
  449. duration=None,
  450. length=None,
  451. thumb=None,
  452. disable_notification=None,
  453. reply_to_message_id=None,
  454. reply_markup=None):
  455. """Send a rounded square mp4 video message of up to 1 minute long.
  456. See https://core.telegram.org/bots/api#sendvideonote for details.
  457. """
  458. return await self.api_request(
  459. 'sendVideoNote',
  460. parameters=locals()
  461. )
  462. async def sendMediaGroup(self, chat_id, media,
  463. disable_notification=None,
  464. reply_to_message_id=None):
  465. """Send a group of photos or videos as an album.
  466. `media` must be a list of `InputMediaPhoto` and/or `InputMediaVideo`
  467. objects.
  468. See https://core.telegram.org/bots/api#sendmediagroup for details.
  469. """
  470. return await self.api_request(
  471. 'sendMediaGroup',
  472. parameters=locals()
  473. )
  474. async def sendLocation(self, chat_id, latitude, longitude,
  475. live_period=None,
  476. disable_notification=None,
  477. reply_to_message_id=None,
  478. reply_markup=None):
  479. """Send a point on the map. May be kept updated for a `live_period`.
  480. See https://core.telegram.org/bots/api#sendlocation for details.
  481. """
  482. return await self.api_request(
  483. 'sendLocation',
  484. parameters=locals()
  485. )
  486. async def editMessageLiveLocation(self, latitude, longitude,
  487. chat_id=None, message_id=None,
  488. inline_message_id=None,
  489. reply_markup=None):
  490. """Edit live location messages.
  491. A location can be edited until its live_period expires or editing is
  492. explicitly disabled by a call to stopMessageLiveLocation.
  493. The message to be edited may be identified through `inline_message_id`
  494. OR the couple (`chat_id`, `message_id`).
  495. See https://core.telegram.org/bots/api#editmessagelivelocation
  496. for details.
  497. """
  498. return await self.api_request(
  499. 'editMessageLiveLocation',
  500. parameters=locals()
  501. )
  502. async def stopMessageLiveLocation(self,
  503. chat_id=None, message_id=None,
  504. inline_message_id=None,
  505. reply_markup=None):
  506. """Stop updating a live location message before live_period expires.
  507. The position to be stopped may be identified through
  508. `inline_message_id` OR the couple (`chat_id`, `message_id`).
  509. `reply_markup` type may be only `InlineKeyboardMarkup`.
  510. See https://core.telegram.org/bots/api#stopmessagelivelocation
  511. for details.
  512. """
  513. return await self.api_request(
  514. 'stopMessageLiveLocation',
  515. parameters=locals()
  516. )
  517. async def sendVenue(self, chat_id, latitude, longitude, title, address,
  518. foursquare_id=None,
  519. foursquare_type=None,
  520. disable_notification=None,
  521. reply_to_message_id=None,
  522. reply_markup=None):
  523. """Send information about a venue.
  524. Integrated with FourSquare.
  525. See https://core.telegram.org/bots/api#sendvenue for details.
  526. """
  527. return await self.api_request(
  528. 'sendVenue',
  529. parameters=locals()
  530. )
  531. async def sendContact(self, chat_id, phone_number, first_name,
  532. last_name=None,
  533. vcard=None,
  534. disable_notification=None,
  535. reply_to_message_id=None,
  536. reply_markup=None):
  537. """Send a phone contact.
  538. See https://core.telegram.org/bots/api#sendcontact for details.
  539. """
  540. return await self.api_request(
  541. 'sendContact',
  542. parameters=locals()
  543. )
  544. async def sendPoll(self, chat_id, question, options,
  545. dummy=None,
  546. disable_notification=None,
  547. reply_to_message_id=None,
  548. reply_markup=None):
  549. """Send a native poll in a group, a supergroup or channel.
  550. See https://core.telegram.org/bots/api#sendpoll for details.
  551. """
  552. return await self.api_request(
  553. 'sendPoll',
  554. parameters=locals()
  555. )
  556. async def sendChatAction(self, chat_id, action):
  557. """Fake a typing status or similar.
  558. See https://core.telegram.org/bots/api#sendchataction for details.
  559. """
  560. return await self.api_request(
  561. 'sendChatAction',
  562. parameters=locals()
  563. )
  564. async def getUserProfilePhotos(self, user_id,
  565. offset=None,
  566. limit=None,):
  567. """Get a list of profile pictures for a user.
  568. See https://core.telegram.org/bots/api#getuserprofilephotos
  569. for details.
  570. """
  571. return await self.api_request(
  572. 'getUserProfilePhotos',
  573. parameters=locals()
  574. )
  575. async def getFile(self, file_id):
  576. """Get basic info about a file and prepare it for downloading.
  577. For the moment, bots can download files of up to
  578. 20MB in size.
  579. On success, a File object is returned. The file can then be downloaded
  580. via the link https://api.telegram.org/file/bot<token>/<file_path>,
  581. where <file_path> is taken from the response.
  582. See https://core.telegram.org/bots/api#getfile for details.
  583. """
  584. return await self.api_request(
  585. 'getFile',
  586. parameters=locals()
  587. )
  588. async def kickChatMember(self, chat_id, user_id,
  589. until_date=None):
  590. """Kick a user from a group, a supergroup or a channel.
  591. In the case of supergroups and channels, the user will not be able to
  592. return to the group on their own using invite links, etc., unless
  593. unbanned first.
  594. Note: In regular groups (non-supergroups), this method will only work
  595. if the ‘All Members Are Admins’ setting is off in the target group.
  596. Otherwise members may only be removed by the group's creator or by
  597. the member that added them.
  598. See https://core.telegram.org/bots/api#kickchatmember for details.
  599. """
  600. return await self.api_request(
  601. 'kickChatMember',
  602. parameters=locals()
  603. )
  604. async def unbanChatMember(self, chat_id, user_id):
  605. """Unban a previously kicked user in a supergroup or channel.
  606. The user will not return to the group or channel automatically, but
  607. will be able to join via link, etc.
  608. The bot must be an administrator for this to work.
  609. Return True on success.
  610. See https://core.telegram.org/bots/api#unbanchatmember for details.
  611. """
  612. return await self.api_request(
  613. 'unbanChatMember',
  614. parameters=locals()
  615. )
  616. async def restrictChatMember(self, chat_id, user_id,
  617. until_date=None,
  618. can_send_messages=None,
  619. can_send_media_messages=None,
  620. can_send_other_messages=None,
  621. can_add_web_page_previews=None):
  622. """Restrict a user in a supergroup.
  623. The bot must be an administrator in the supergroup for this to work
  624. and must have the appropriate admin rights.
  625. Pass True for all boolean parameters to lift restrictions from a
  626. user.
  627. Return True on success.
  628. See https://core.telegram.org/bots/api#restrictchatmember for details.
  629. """
  630. return await self.api_request(
  631. 'restrictChatMember',
  632. parameters=locals()
  633. )
  634. async def promoteChatMember(self, chat_id, user_id,
  635. can_change_info=None,
  636. can_post_messages=None,
  637. can_edit_messages=None,
  638. can_delete_messages=None,
  639. can_invite_users=None,
  640. can_restrict_members=None,
  641. can_pin_messages=None,
  642. can_promote_members=None):
  643. """Promote or demote a user in a supergroup or a channel.
  644. The bot must be an administrator in the chat for this to work and must
  645. have the appropriate admin rights.
  646. Pass False for all boolean parameters to demote a user.
  647. Return True on success.
  648. See https://core.telegram.org/bots/api#promotechatmember for details.
  649. """
  650. return await self.api_request(
  651. 'promoteChatMember',
  652. parameters=locals()
  653. )
  654. async def exportChatInviteLink(self, chat_id):
  655. """Generate a new invite link for a chat and revoke any active link.
  656. The bot must be an administrator in the chat for this to work and must
  657. have the appropriate admin rights.
  658. Return the new invite link as String on success.
  659. NOTE: to get the current invite link, use `getChat` method.
  660. See https://core.telegram.org/bots/api#exportchatinvitelink
  661. for details.
  662. """
  663. return await self.api_request(
  664. 'exportChatInviteLink',
  665. parameters=locals()
  666. )
  667. async def setChatPhoto(self, chat_id, photo):
  668. """Set a new profile photo for the chat.
  669. Photos can't be changed for private chats.
  670. `photo` must be an input file (file_id and urls are not allowed).
  671. The bot must be an administrator in the chat for this to work and must
  672. have the appropriate admin rights.
  673. Return True on success.
  674. See https://core.telegram.org/bots/api#setchatphoto for details.
  675. """
  676. return await self.api_request(
  677. 'setChatPhoto',
  678. parameters=locals()
  679. )
  680. async def deleteChatPhoto(self, chat_id):
  681. """Delete a chat photo.
  682. Photos can't be changed for private chats.
  683. The bot must be an administrator in the chat for this to work and must
  684. have the appropriate admin rights.
  685. Return True on success.
  686. See https://core.telegram.org/bots/api#deletechatphoto for details.
  687. """
  688. return await self.api_request(
  689. 'deleteChatPhoto',
  690. parameters=locals()
  691. )
  692. async def setChatTitle(self, chat_id, title):
  693. """Change the title of a chat.
  694. Titles can't be changed for private chats.
  695. The bot must be an administrator in the chat for this to work and must
  696. have the appropriate admin rights.
  697. Return True on success.
  698. See https://core.telegram.org/bots/api#setchattitle for details.
  699. """
  700. return await self.api_request(
  701. 'setChatTitle',
  702. parameters=locals()
  703. )
  704. async def setChatDescription(self, chat_id, description):
  705. """Change the description of a supergroup or a channel.
  706. The bot must be an administrator in the chat for this to work and must
  707. have the appropriate admin rights.
  708. Return True on success.
  709. See https://core.telegram.org/bots/api#setchatdescription for details.
  710. """
  711. return await self.api_request(
  712. 'setChatDescription',
  713. parameters=locals()
  714. )
  715. async def pinChatMessage(self, chat_id, message_id,
  716. disable_notification=None):
  717. """Pin a message in a group, a supergroup, or a channel.
  718. The bot must be an administrator in the chat for this to work and must
  719. have the ‘can_pin_messages’ admin right in the supergroup or
  720. ‘can_edit_messages’ admin right in the channel.
  721. Return True on success.
  722. See https://core.telegram.org/bots/api#pinchatmessage for details.
  723. """
  724. return await self.api_request(
  725. 'pinChatMessage',
  726. parameters=locals()
  727. )
  728. async def unpinChatMessage(self, chat_id):
  729. """Unpin a message in a group, a supergroup, or a channel.
  730. The bot must be an administrator in the chat for this to work and must
  731. have the ‘can_pin_messages’ admin right in the supergroup or
  732. ‘can_edit_messages’ admin right in the channel.
  733. Return True on success.
  734. See https://core.telegram.org/bots/api#unpinchatmessage for details.
  735. """
  736. return await self.api_request(
  737. 'unpinChatMessage',
  738. parameters=locals()
  739. )
  740. async def leaveChat(self, chat_id):
  741. """Make the bot leave a group, supergroup or channel.
  742. Return True on success.
  743. See https://core.telegram.org/bots/api#leavechat for details.
  744. """
  745. return await self.api_request(
  746. 'leaveChat',
  747. parameters=locals()
  748. )
  749. async def getChat(self, chat_id):
  750. """Get up to date information about the chat.
  751. Return a Chat object on success.
  752. See https://core.telegram.org/bots/api#getchat for details.
  753. """
  754. return await self.api_request(
  755. 'getChat',
  756. parameters=locals()
  757. )
  758. async def getChatAdministrators(self, chat_id):
  759. """Get a list of administrators in a chat.
  760. On success, return an Array of ChatMember objects that contains
  761. information about all chat administrators except other bots.
  762. If the chat is a group or a supergroup and no administrators were
  763. appointed, only the creator will be returned.
  764. See https://core.telegram.org/bots/api#getchatadministrators
  765. for details.
  766. """
  767. return await self.api_request(
  768. 'getChatAdministrators',
  769. parameters=locals()
  770. )
  771. async def getChatMembersCount(self, chat_id):
  772. """Get the number of members in a chat.
  773. Returns Int on success.
  774. See https://core.telegram.org/bots/api#getchatmemberscount for details.
  775. """
  776. return await self.api_request(
  777. 'getChatMembersCount',
  778. parameters=locals()
  779. )
  780. async def getChatMember(self, chat_id, user_id):
  781. """Get information about a member of a chat.
  782. Returns a ChatMember object on success.
  783. See https://core.telegram.org/bots/api#getchatmember for details.
  784. """
  785. return await self.api_request(
  786. 'getChatMember',
  787. parameters=locals()
  788. )
  789. async def setChatStickerSet(self, chat_id, sticker_set_name):
  790. """Set a new group sticker set for a supergroup.
  791. The bot must be an administrator in the chat for this to work and must
  792. have the appropriate admin rights.
  793. Use the field `can_set_sticker_set` optionally returned in getChat
  794. requests to check if the bot can use this method.
  795. Returns True on success.
  796. See https://core.telegram.org/bots/api#setchatstickerset for details.
  797. """
  798. return await self.api_request(
  799. 'setChatStickerSet',
  800. parameters=locals()
  801. )
  802. async def deleteChatStickerSet(self, chat_id):
  803. """Delete a group sticker set from a supergroup.
  804. The bot must be an administrator in the chat for this to work and must
  805. have the appropriate admin rights.
  806. Use the field `can_set_sticker_set` optionally returned in getChat
  807. requests to check if the bot can use this method.
  808. Returns True on success.
  809. See https://core.telegram.org/bots/api#deletechatstickerset for
  810. details.
  811. """
  812. return await self.api_request(
  813. 'deleteChatStickerSet',
  814. parameters=locals()
  815. )
  816. async def answerCallbackQuery(self, callback_query_id,
  817. text=None,
  818. show_alert=None,
  819. url=None,
  820. cache_time=None):
  821. """Send answers to callback queries sent from inline keyboards.
  822. The answer will be displayed to the user as a notification at the top
  823. of the chat screen or as an alert.
  824. On success, True is returned.
  825. See https://core.telegram.org/bots/api#answercallbackquery for details.
  826. """
  827. return await self.api_request(
  828. 'answerCallbackQuery',
  829. parameters=locals()
  830. )
  831. async def editMessageText(self, text,
  832. chat_id=None, message_id=None,
  833. inline_message_id=None,
  834. parse_mode=None,
  835. disable_web_page_preview=None,
  836. reply_markup=None):
  837. """Edit text and game messages.
  838. On success, if edited message is sent by the bot, the edited Message
  839. is returned, otherwise True is returned.
  840. See https://core.telegram.org/bots/api#editmessagetext for details.
  841. """
  842. return await self.api_request(
  843. 'editMessageText',
  844. parameters=locals()
  845. )
  846. async def editMessageCaption(self,
  847. chat_id=None, message_id=None,
  848. inline_message_id=None,
  849. caption=None,
  850. parse_mode=None,
  851. reply_markup=None):
  852. """Edit captions of messages.
  853. On success, if edited message is sent by the bot, the edited Message is
  854. returned, otherwise True is returned.
  855. See https://core.telegram.org/bots/api#editmessagecaption for details.
  856. """
  857. return await self.api_request(
  858. 'editMessageCaption',
  859. parameters=locals()
  860. )
  861. async def editMessageMedia(self,
  862. chat_id=None, message_id=None,
  863. inline_message_id=None,
  864. media=None,
  865. reply_markup=None):
  866. """Edit animation, audio, document, photo, or video messages.
  867. If a message is a part of a message album, then it can be edited only
  868. to a photo or a video. Otherwise, message type can be changed
  869. arbitrarily.
  870. When inline message is edited, new file can't be uploaded.
  871. Use previously uploaded file via its file_id or specify a URL.
  872. On success, if the edited message was sent by the bot, the edited
  873. Message is returned, otherwise True is returned.
  874. See https://core.telegram.org/bots/api#editmessagemedia for details.
  875. """
  876. return await self.api_request(
  877. 'editMessageMedia',
  878. parameters=locals()
  879. )
  880. async def editMessageReplyMarkup(self,
  881. chat_id=None, message_id=None,
  882. inline_message_id=None,
  883. reply_markup=None):
  884. """Edit only the reply markup of messages.
  885. On success, if edited message is sent by the bot, the edited Message is
  886. returned, otherwise True is returned.
  887. See https://core.telegram.org/bots/api#editmessagereplymarkup for
  888. details.
  889. """
  890. return await self.api_request(
  891. 'editMessageReplyMarkup',
  892. parameters=locals()
  893. )
  894. async def stopPoll(self, chat_id, message_id,
  895. reply_markup=None):
  896. """Stop a poll which was sent by the bot.
  897. On success, the stopped Poll with the final results is returned.
  898. `reply_markup` type may be only `InlineKeyboardMarkup`.
  899. See https://core.telegram.org/bots/api#stoppoll for details.
  900. """
  901. return await self.api_request(
  902. 'stopPoll',
  903. parameters=locals()
  904. )
  905. async def deleteMessage(self, chat_id, message_id):
  906. """Delete a message, including service messages.
  907. - A message can only be deleted if it was sent less than 48 hours
  908. ago.
  909. - Bots can delete outgoing messages in private chats, groups, and
  910. supergroups.
  911. - Bots can delete incoming messages in private chats.
  912. - Bots granted can_post_messages permissions can delete outgoing
  913. messages in channels.
  914. - If the bot is an administrator of a group, it can delete any
  915. message there.
  916. - If the bot has can_delete_messages permission in a supergroup or
  917. a channel, it can delete any message there.
  918. Returns True on success.
  919. See https://core.telegram.org/bots/api#deletemessage for details.
  920. """
  921. return await self.api_request(
  922. 'deleteMessage',
  923. parameters=locals()
  924. )
  925. async def sendSticker(self, chat_id, sticker,
  926. disable_notification=None,
  927. reply_to_message_id=None,
  928. reply_markup=None):
  929. """Send .webp stickers.
  930. On success, the sent Message is returned.
  931. See https://core.telegram.org/bots/api#sendsticker for details.
  932. """
  933. return await self.api_request(
  934. 'sendSticker',
  935. parameters=locals()
  936. )
  937. async def getStickerSet(self, name):
  938. """Get a sticker set.
  939. On success, a StickerSet object is returned.
  940. See https://core.telegram.org/bots/api#getstickerset for details.
  941. """
  942. return await self.api_request(
  943. 'getStickerSet',
  944. parameters=locals()
  945. )
  946. async def uploadStickerFile(self, user_id, png_sticker):
  947. """Upload a .png file as a sticker.
  948. Use it later via `createNewStickerSet` and `addStickerToSet` methods
  949. (can be used multiple times).
  950. Return the uploaded File on success.
  951. `png_sticker` must be a *.png image up to 512 kilobytes in size,
  952. dimensions must not exceed 512px, and either width or height must
  953. be exactly 512px.
  954. See https://core.telegram.org/bots/api#uploadstickerfile for details.
  955. """
  956. return await self.api_request(
  957. 'uploadStickerFile',
  958. parameters=locals()
  959. )
  960. async def createNewStickerSet(self, user_id,
  961. name, title, png_sticker, emojis,
  962. contains_masks=None,
  963. mask_position=None):
  964. """Create new sticker set owned by a user.
  965. The bot will be able to edit the created sticker set.
  966. Returns True on success.
  967. See https://core.telegram.org/bots/api#createnewstickerset for details.
  968. """
  969. return await self.api_request(
  970. 'createNewStickerSet',
  971. parameters=locals()
  972. )
  973. async def addStickerToSet(self, user_id, name, png_sticker, emojis,
  974. mask_position=None):
  975. """Add a new sticker to a set created by the bot.
  976. Returns True on success.
  977. See https://core.telegram.org/bots/api#addstickertoset for details.
  978. """
  979. return await self.api_request(
  980. 'addStickerToSet',
  981. parameters=locals()
  982. )
  983. async def setStickerPositionInSet(self, sticker, position):
  984. """Move a sticker in a set created by the bot to a specific position .
  985. Position is 0-based.
  986. Returns True on success.
  987. See https://core.telegram.org/bots/api#setstickerpositioninset for
  988. details.
  989. """
  990. return await self.api_request(
  991. 'setStickerPositionInSet',
  992. parameters=locals()
  993. )
  994. async def deleteStickerFromSet(self, sticker):
  995. """Delete a sticker from a set created by the bot.
  996. Returns True on success.
  997. See https://core.telegram.org/bots/api#deletestickerfromset for
  998. details.
  999. """
  1000. return await self.api_request(
  1001. 'deleteStickerFromSet',
  1002. parameters=locals()
  1003. )
  1004. async def answerInlineQuery(self, inline_query_id, results,
  1005. cache_time=None,
  1006. is_personal=None,
  1007. next_offset=None,
  1008. switch_pm_text=None,
  1009. switch_pm_parameter=None):
  1010. """Send answers to an inline query.
  1011. On success, True is returned.
  1012. No more than 50 results per query are allowed.
  1013. See https://core.telegram.org/bots/api#answerinlinequery for details.
  1014. """
  1015. return await self.api_request(
  1016. 'answerInlineQuery',
  1017. parameters=locals()
  1018. )
  1019. async def sendInvoice(self, chat_id, title, description, payload,
  1020. provider_token, start_parameter, currency, prices,
  1021. provider_data=None,
  1022. photo_url=None,
  1023. photo_size=None,
  1024. photo_width=None,
  1025. photo_height=None,
  1026. need_name=None,
  1027. need_phone_number=None,
  1028. need_email=None,
  1029. need_shipping_address=None,
  1030. send_phone_number_to_provider=None,
  1031. send_email_to_provider=None,
  1032. is_flexible=None,
  1033. disable_notification=None,
  1034. reply_to_message_id=None,
  1035. reply_markup=None):
  1036. """Send an invoice.
  1037. On success, the sent Message is returned.
  1038. See https://core.telegram.org/bots/api#sendinvoice for details.
  1039. """
  1040. return await self.api_request(
  1041. 'sendInvoice',
  1042. parameters=locals()
  1043. )
  1044. async def answerShippingQuery(self, shipping_query_id, ok,
  1045. shipping_options=None,
  1046. error_message=None):
  1047. """Reply to shipping queries.
  1048. On success, True is returned.
  1049. If you sent an invoice requesting a shipping address and the parameter
  1050. is_flexible was specified, the Bot API will send an Update with a
  1051. shipping_query field to the bot.
  1052. See https://core.telegram.org/bots/api#answershippingquery for details.
  1053. """
  1054. return await self.api_request(
  1055. 'answerShippingQuery',
  1056. parameters=locals()
  1057. )
  1058. async def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
  1059. error_message=None):
  1060. """Respond to pre-checkout queries.
  1061. Once the user has confirmed their payment and shipping details, the Bot
  1062. API sends the final confirmation in the form of an Update with the
  1063. field pre_checkout_query.
  1064. On success, True is returned.
  1065. Note: The Bot API must receive an answer within 10 seconds after the
  1066. pre-checkout query was sent.
  1067. See https://core.telegram.org/bots/api#answerprecheckoutquery for
  1068. details.
  1069. """
  1070. return await self.api_request(
  1071. 'answerPreCheckoutQuery',
  1072. parameters=locals()
  1073. )
  1074. async def setPassportDataErrors(self, user_id, errors):
  1075. """Refuse a Telegram Passport element with `errors`.
  1076. Inform a user that some of the Telegram Passport elements they provided
  1077. contains errors.
  1078. The user will not be able to re-submit their Passport to you until the
  1079. errors are fixed (the contents of the field for which you returned
  1080. the error must change).
  1081. Returns True on success.
  1082. Use this if the data submitted by the user doesn't satisfy the
  1083. standards your service requires for any reason.
  1084. For example, if a birthday date seems invalid, a submitted document
  1085. is blurry, a scan shows evidence of tampering, etc.
  1086. Supply some details in the error message to make sure the user knows
  1087. how to correct the issues.
  1088. See https://core.telegram.org/bots/api#setpassportdataerrors for
  1089. details.
  1090. """
  1091. return await self.api_request(
  1092. 'setPassportDataErrors',
  1093. parameters=locals()
  1094. )
  1095. async def sendGame(self, chat_id, game_short_name,
  1096. disable_notification=None,
  1097. reply_to_message_id=None,
  1098. reply_markup=None):
  1099. """Send a game.
  1100. On success, the sent Message is returned.
  1101. See https://core.telegram.org/bots/api#sendgame for
  1102. details.
  1103. """
  1104. return await self.api_request(
  1105. 'sendGame',
  1106. parameters=locals()
  1107. )
  1108. async def setGameScore(self, user_id, score,
  1109. force=None,
  1110. disable_edit_message=None,
  1111. chat_id=None, message_id=None,
  1112. inline_message_id=None):
  1113. """Set the score of the specified user in a game.
  1114. On success, if the message was sent by the bot, returns the edited
  1115. Message, otherwise returns True.
  1116. Returns an error, if the new score is not greater than the user's
  1117. current score in the chat and force is False.
  1118. See https://core.telegram.org/bots/api#setgamescore for
  1119. details.
  1120. """
  1121. return await self.api_request(
  1122. 'setGameScore',
  1123. parameters=locals()
  1124. )
  1125. async def getGameHighScores(self, user_id,
  1126. chat_id=None, message_id=None,
  1127. inline_message_id=None):
  1128. """Get data for high score tables.
  1129. Will return the score of the specified user and several of his
  1130. neighbors in a game.
  1131. On success, returns an Array of GameHighScore objects.
  1132. This method will currently return scores for the target user, plus two
  1133. of his closest neighbors on each side. Will also return the top
  1134. three users if the user and his neighbors are not among them.
  1135. Please note that this behavior is subject to change.
  1136. See https://core.telegram.org/bots/api#getgamehighscores for
  1137. details.
  1138. """
  1139. return await self.api_request(
  1140. 'getGameHighScores',
  1141. parameters=locals()
  1142. )