Queer European MD passionate about IT

api.py 49 KB

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