Queer European MD passionate about IT

api.py 49 KB

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