Queer European MD passionate about IT

api.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  1. """This module provides a python mirror for Telegram bot API.
  2. All methods and parameters are the same as the original json API.
  3. A simple aiohttp asynchronous web client is used to make requests.
  4. """
  5. # Standard library modules
  6. import asyncio
  7. import datetime
  8. import io
  9. import json
  10. import logging
  11. from typing import Dict, Union, List, IO
  12. # Third party modules
  13. import aiohttp
  14. import aiohttp.web
  15. class TelegramError(Exception):
  16. """Telegram API exceptions class."""
  17. # noinspection PyUnusedLocal
  18. def __init__(self, error_code=0, description=None, ok=False,
  19. *args, **kwargs):
  20. """Get an error response and return corresponding Exception."""
  21. self._code = error_code
  22. if description is None:
  23. self._description = 'Generic error'
  24. else:
  25. self._description = description
  26. super().__init__(self.description)
  27. @property
  28. def code(self):
  29. """Telegram error code."""
  30. return self._code
  31. @property
  32. def description(self):
  33. """Human-readable description of error."""
  34. return f"Error {self.code}: {self._description}"
  35. class ChatPermissions(dict):
  36. """Actions that a non-administrator user is allowed to take in a chat."""
  37. def __init__(self,
  38. can_send_messages: bool = True,
  39. can_send_media_messages: bool = True,
  40. can_send_polls: bool = True,
  41. can_send_other_messages: bool = True,
  42. can_add_web_page_previews: bool = True,
  43. can_change_info: bool = True,
  44. can_invite_users: bool = True,
  45. can_pin_messages: bool = True):
  46. super().__init__(self)
  47. self['can_send_messages'] = can_send_messages
  48. self['can_send_media_messages'] = can_send_media_messages
  49. self['can_send_polls'] = can_send_polls
  50. self['can_send_other_messages'] = can_send_other_messages
  51. self['can_add_web_page_previews'] = can_add_web_page_previews
  52. self['can_change_info'] = can_change_info
  53. self['can_invite_users'] = can_invite_users
  54. self['can_pin_messages'] = can_pin_messages
  55. class Command(dict):
  56. def __init__(self,
  57. command: str = None,
  58. description: str = None):
  59. super().__init__(self)
  60. self['command'] = command
  61. self['description'] = description
  62. # This class needs to mirror Telegram API, so camelCase method are needed
  63. # noinspection PyPep8Naming
  64. class TelegramBot:
  65. """Provide python method having the same signature as Telegram API methods.
  66. All mirrored methods are camelCase.
  67. """
  68. app = aiohttp.web.Application()
  69. sessions_timeouts = {
  70. 'getUpdates': dict(
  71. timeout=35,
  72. close=False
  73. ),
  74. 'sendMessage': dict(
  75. timeout=20,
  76. close=False
  77. )
  78. }
  79. _absolute_cooldown_timedelta = datetime.timedelta(seconds=1/30)
  80. _per_chat_cooldown_timedelta = datetime.timedelta(seconds=1)
  81. _allowed_messages_per_group_per_minute = 20
  82. def __init__(self, token):
  83. """Set bot token and store HTTP sessions."""
  84. self._token = token
  85. self.sessions = dict()
  86. self._flood_wait = 0
  87. # Each `telegram_id` key has a list of `datetime.datetime` as value
  88. self.last_sending_time = {
  89. 'absolute': (
  90. datetime.datetime.now()
  91. - self.absolute_cooldown_timedelta
  92. ),
  93. 0: []
  94. }
  95. @property
  96. def token(self):
  97. """Telegram API bot token."""
  98. return self._token
  99. @property
  100. def flood_wait(self):
  101. """Seconds to wait before next API requests."""
  102. return self._flood_wait
  103. @property
  104. def absolute_cooldown_timedelta(self):
  105. """Return time delta to wait between messages (any chat).
  106. Return class value (all bots have the same limits).
  107. """
  108. return self.__class__._absolute_cooldown_timedelta
  109. @property
  110. def per_chat_cooldown_timedelta(self):
  111. """Return time delta to wait between messages in a chat.
  112. Return class value (all bots have the same limits).
  113. """
  114. return self.__class__._per_chat_cooldown_timedelta
  115. @property
  116. def longest_cooldown_timedelta(self):
  117. """Return the longest cooldown timedelta.
  118. Updates sent more than `longest_cooldown_timedelta` ago will be
  119. forgotten.
  120. """
  121. return datetime.timedelta(minutes=1)
  122. @property
  123. def allowed_messages_per_group_per_minute(self):
  124. """Return maximum number of messages allowed in a group per minute.
  125. Group, supergroup and channels are considered.
  126. Return class value (all bots have the same limits).
  127. """
  128. return self.__class__._allowed_messages_per_group_per_minute
  129. @staticmethod
  130. def check_telegram_api_json(response):
  131. """Take a json Telegram response, check it and return its content.
  132. Example of well-formed json Telegram responses:
  133. {
  134. "ok": False,
  135. "error_code": 401,
  136. "description": "Unauthorized"
  137. }
  138. {
  139. "ok": True,
  140. "result": ...
  141. }
  142. """
  143. assert 'ok' in response, (
  144. "All Telegram API responses have an `ok` field."
  145. )
  146. if not response['ok']:
  147. raise TelegramError(**response)
  148. return response['result']
  149. @staticmethod
  150. def adapt_parameters(parameters, exclude=None):
  151. """Build a aiohttp.FormData object from given `parameters`.
  152. Exclude `self`, empty values and parameters in `exclude` list.
  153. Cast integers to string to avoid TypeError during json serialization.
  154. """
  155. if exclude is None:
  156. exclude = []
  157. exclude.append('self')
  158. # quote_fields=False, otherwise some file names cause troubles
  159. data = aiohttp.FormData(quote_fields=False)
  160. for key, value in parameters.items():
  161. if not (key in exclude or value is None):
  162. if (
  163. type(value) in (int, list,)
  164. or (type(value) is dict and 'file' not in value)
  165. ):
  166. value = json.dumps(value, separators=(',', ':'))
  167. data.add_field(key, value)
  168. return data
  169. @staticmethod
  170. def prepare_file_object(file: Union[str, IO, dict, None]
  171. ) -> Union[Dict[str, IO], None]:
  172. if type(file) is str:
  173. try:
  174. file = open(file, 'r')
  175. except FileNotFoundError as e:
  176. logging.error(f"{e}")
  177. file = None
  178. if isinstance(file, io.IOBase):
  179. file = dict(file=file)
  180. return file
  181. def get_session(self, api_method):
  182. """According to API method, return proper session and information.
  183. Return a tuple (session, session_must_be_closed)
  184. session : aiohttp.ClientSession
  185. Client session with proper timeout
  186. session_must_be_closed : bool
  187. True if session must be closed after being used once
  188. """
  189. cls = self.__class__
  190. if api_method in cls.sessions_timeouts:
  191. if api_method not in self.sessions:
  192. self.sessions[api_method] = aiohttp.ClientSession(
  193. timeout=aiohttp.ClientTimeout(
  194. total=cls.sessions_timeouts[api_method]['timeout']
  195. )
  196. )
  197. session = self.sessions[api_method]
  198. session_must_be_closed = cls.sessions_timeouts[api_method]['close']
  199. else:
  200. session = aiohttp.ClientSession(
  201. timeout=aiohttp.ClientTimeout(total=None)
  202. )
  203. session_must_be_closed = True
  204. return session, session_must_be_closed
  205. def set_flood_wait(self, flood_wait):
  206. """Wait `flood_wait` seconds before next request."""
  207. self._flood_wait = flood_wait
  208. async def prevent_flooding(self, chat_id):
  209. """Await until request may be sent safely.
  210. Telegram flood control won't allow too many API requests in a small
  211. period.
  212. Exact limits are unknown, but less than 30 total private chat messages
  213. per second, less than 1 private message per chat and less than 20
  214. group chat messages per chat per minute should be safe.
  215. """
  216. now = datetime.datetime.now
  217. if type(chat_id) is int and chat_id > 0:
  218. while (
  219. now() < (
  220. self.last_sending_time['absolute']
  221. + self.absolute_cooldown_timedelta
  222. )
  223. ) or (
  224. chat_id in self.last_sending_time
  225. and (
  226. now() < (
  227. self.last_sending_time[chat_id]
  228. + self.per_chat_cooldown_timedelta
  229. )
  230. )
  231. ):
  232. await asyncio.sleep(
  233. self.absolute_cooldown_timedelta.seconds
  234. )
  235. self.last_sending_time[chat_id] = now()
  236. else:
  237. while (
  238. now() < (
  239. self.last_sending_time['absolute']
  240. + self.absolute_cooldown_timedelta
  241. )
  242. ) or (
  243. chat_id in self.last_sending_time
  244. and len(
  245. [
  246. sending_datetime
  247. for sending_datetime in self.last_sending_time[chat_id]
  248. if sending_datetime >= (
  249. now()
  250. - datetime.timedelta(minutes=1)
  251. )
  252. ]
  253. ) >= self.allowed_messages_per_group_per_minute
  254. ) or (
  255. chat_id in self.last_sending_time
  256. and len(self.last_sending_time[chat_id]) > 0
  257. and now() < (
  258. self.last_sending_time[chat_id][-1]
  259. + self.per_chat_cooldown_timedelta
  260. )
  261. ):
  262. await asyncio.sleep(0.5)
  263. if chat_id not in self.last_sending_time:
  264. self.last_sending_time[chat_id] = []
  265. self.last_sending_time[chat_id].append(now())
  266. self.last_sending_time[chat_id] = [
  267. sending_datetime
  268. for sending_datetime in self.last_sending_time[chat_id]
  269. if sending_datetime >= (
  270. now()
  271. - self.longest_cooldown_timedelta
  272. )
  273. ]
  274. self.last_sending_time['absolute'] = now()
  275. return
  276. async def api_request(self, method, parameters=None, exclude=None):
  277. """Return the result of a Telegram bot API request, or an Exception.
  278. Opened sessions will be used more than one time (if appropriate) and
  279. will be closed on `Bot.app.cleanup`.
  280. Result may be a Telegram API json response, None, or Exception.
  281. """
  282. if exclude is None:
  283. exclude = []
  284. if parameters is None:
  285. parameters = {}
  286. response_object = None
  287. session, session_must_be_closed = self.get_session(method)
  288. # Prevent Telegram flood control for all methods having a `chat_id`
  289. if 'chat_id' in parameters:
  290. await self.prevent_flooding(parameters['chat_id'])
  291. parameters = self.adapt_parameters(parameters, exclude=exclude)
  292. try:
  293. async with session.post(
  294. "https://api.telegram.org/bot"
  295. f"{self.token}/{method}",
  296. data=parameters
  297. ) as response:
  298. try:
  299. response_object = self.check_telegram_api_json(
  300. await response.json() # Telegram returns json objects
  301. )
  302. except TelegramError as e:
  303. logging.error(f"API error response - {e}")
  304. if e.code == 420: # Flood error!
  305. try:
  306. flood_wait = int(
  307. e.description.split('_')[-1]
  308. ) + 30
  309. except Exception as e:
  310. logging.error(f"{e}")
  311. flood_wait = 5*60
  312. logging.critical(
  313. "Telegram antiflood control triggered!\n"
  314. f"Wait {flood_wait} seconds before making another "
  315. "request"
  316. )
  317. self.set_flood_wait(flood_wait)
  318. response_object = e
  319. except Exception as e:
  320. logging.error(f"{e}", exc_info=True)
  321. response_object = e
  322. except asyncio.TimeoutError as e:
  323. logging.info(f"{e}: {method} API call timed out")
  324. except Exception as e:
  325. logging.info(f"Unexpected exception:\n{e}")
  326. response_object = e
  327. finally:
  328. if session_must_be_closed and not session.closed:
  329. await session.close()
  330. return response_object
  331. async def getMe(self):
  332. """Get basic information about the bot in form of a User object.
  333. Useful to test `self.token`.
  334. See https://core.telegram.org/bots/api#getme for details.
  335. """
  336. return await self.api_request(
  337. 'getMe',
  338. )
  339. async def getUpdates(self, offset: int = None,
  340. limit: int = None,
  341. timeout: int = None,
  342. allowed_updates: List[str] = None):
  343. """Get a list of updates starting from `offset`.
  344. If there are no updates, keep the request hanging until `timeout`.
  345. If there are more than `limit` updates, retrieve them in packs of
  346. `limit`.
  347. Allowed update types (empty list to allow all).
  348. See https://core.telegram.org/bots/api#getupdates for details.
  349. """
  350. return await self.api_request(
  351. method='getUpdates',
  352. parameters=locals()
  353. )
  354. async def setWebhook(self, url: str,
  355. certificate: Union[str, IO] = None,
  356. ip_address: str = None,
  357. max_connections: int = None,
  358. allowed_updates: List[str] = None,
  359. drop_pending_updates: bool = None):
  360. """Set or remove a webhook. Telegram will post to `url` new updates.
  361. See https://core.telegram.org/bots/api#setwebhook for details.
  362. """
  363. certificate = self.prepare_file_object(certificate)
  364. result = await self.api_request(
  365. 'setWebhook',
  366. parameters=locals()
  367. )
  368. if type(certificate) is dict: # Close certificate file, if it was open
  369. certificate['file'].close()
  370. return result
  371. async def deleteWebhook(self, drop_pending_updates: bool = None):
  372. """Remove webhook integration and switch back to getUpdate.
  373. See https://core.telegram.org/bots/api#deletewebhook for details.
  374. """
  375. return await self.api_request(
  376. 'deleteWebhook',
  377. parameters=locals()
  378. )
  379. async def getWebhookInfo(self):
  380. """Get current webhook status.
  381. See https://core.telegram.org/bots/api#getwebhookinfo for details.
  382. """
  383. return await self.api_request(
  384. 'getWebhookInfo',
  385. )
  386. async def sendMessage(self, chat_id: Union[int, str], text: str,
  387. parse_mode: str = None,
  388. entities: List[dict] = None,
  389. disable_web_page_preview: bool = None,
  390. disable_notification: bool = None,
  391. reply_to_message_id: int = None,
  392. allow_sending_without_reply: bool = None,
  393. reply_markup=None):
  394. """Send a text message. On success, return it.
  395. See https://core.telegram.org/bots/api#sendmessage for details.
  396. """
  397. return await self.api_request(
  398. 'sendMessage',
  399. parameters=locals()
  400. )
  401. async def forwardMessage(self, chat_id: Union[int, str],
  402. from_chat_id: Union[int, str],
  403. message_id: int,
  404. disable_notification: bool = None):
  405. """Forward a message.
  406. See https://core.telegram.org/bots/api#forwardmessage for details.
  407. """
  408. return await self.api_request(
  409. 'forwardMessage',
  410. parameters=locals()
  411. )
  412. async def sendPhoto(self, chat_id: Union[int, str], photo,
  413. caption: str = None,
  414. parse_mode: str = None,
  415. caption_entities: List[dict] = None,
  416. disable_notification: bool = None,
  417. reply_to_message_id: int = None,
  418. allow_sending_without_reply: bool = None,
  419. reply_markup=None):
  420. """Send a photo from file_id, HTTP url or file.
  421. See https://core.telegram.org/bots/api#sendphoto for details.
  422. """
  423. return await self.api_request(
  424. 'sendPhoto',
  425. parameters=locals()
  426. )
  427. async def sendAudio(self, chat_id: Union[int, str], audio,
  428. caption: str = None,
  429. parse_mode: str = None,
  430. caption_entities: List[dict] = None,
  431. duration: int = None,
  432. performer: str = None,
  433. title: str = None,
  434. thumb=None,
  435. disable_notification: bool = None,
  436. reply_to_message_id: int = None,
  437. allow_sending_without_reply: bool = None,
  438. reply_markup=None):
  439. """Send an audio file from file_id, HTTP url or file.
  440. See https://core.telegram.org/bots/api#sendaudio for details.
  441. """
  442. return await self.api_request(
  443. 'sendAudio',
  444. parameters=locals()
  445. )
  446. async def sendDocument(self, chat_id: Union[int, str], document,
  447. thumb=None,
  448. caption: str = None,
  449. parse_mode: str = None,
  450. caption_entities: List[dict] = None,
  451. disable_content_type_detection: bool = None,
  452. disable_notification: bool = None,
  453. reply_to_message_id: int = None,
  454. allow_sending_without_reply: bool = None,
  455. reply_markup=None):
  456. """Send a document from file_id, HTTP url or file.
  457. See https://core.telegram.org/bots/api#senddocument for details.
  458. """
  459. return await self.api_request(
  460. 'sendDocument',
  461. parameters=locals()
  462. )
  463. async def sendVideo(self, chat_id: Union[int, str], video,
  464. duration: int = None,
  465. width: int = None,
  466. height: int = None,
  467. thumb=None,
  468. caption: str = None,
  469. parse_mode: str = None,
  470. caption_entities: List[dict] = None,
  471. supports_streaming: bool = None,
  472. disable_notification: bool = None,
  473. reply_to_message_id: int = None,
  474. allow_sending_without_reply: bool = None,
  475. reply_markup=None):
  476. """Send a video from file_id, HTTP url or file.
  477. See https://core.telegram.org/bots/api#sendvideo for details.
  478. """
  479. return await self.api_request(
  480. 'sendVideo',
  481. parameters=locals()
  482. )
  483. async def sendAnimation(self, chat_id: Union[int, str], animation,
  484. duration: int = None,
  485. width: int = None,
  486. height: int = None,
  487. thumb=None,
  488. caption: str = None,
  489. parse_mode: str = None,
  490. caption_entities: List[dict] = None,
  491. disable_notification: bool = None,
  492. reply_to_message_id: int = None,
  493. allow_sending_without_reply: bool = None,
  494. reply_markup=None):
  495. """Send animation files (GIF or H.264/MPEG-4 AVC video without sound).
  496. See https://core.telegram.org/bots/api#sendanimation for details.
  497. """
  498. return await self.api_request(
  499. 'sendAnimation',
  500. parameters=locals()
  501. )
  502. async def sendVoice(self, chat_id: Union[int, str], voice,
  503. caption: str = None,
  504. parse_mode: str = None,
  505. caption_entities: List[dict] = None,
  506. duration: int = None,
  507. disable_notification: bool = None,
  508. reply_to_message_id: int = None,
  509. allow_sending_without_reply: bool = None,
  510. reply_markup=None):
  511. """Send an audio file to be displayed as playable voice message.
  512. `voice` must be in an .ogg file encoded with OPUS.
  513. See https://core.telegram.org/bots/api#sendvoice for details.
  514. """
  515. return await self.api_request(
  516. 'sendVoice',
  517. parameters=locals()
  518. )
  519. async def sendVideoNote(self, chat_id: Union[int, str], video_note,
  520. duration: int = None,
  521. length: int = None,
  522. thumb=None,
  523. disable_notification: bool = None,
  524. reply_to_message_id: int = None,
  525. allow_sending_without_reply: bool = None,
  526. reply_markup=None):
  527. """Send a rounded square mp4 video message of up to 1 minute long.
  528. See https://core.telegram.org/bots/api#sendvideonote for details.
  529. """
  530. return await self.api_request(
  531. 'sendVideoNote',
  532. parameters=locals()
  533. )
  534. async def sendMediaGroup(self, chat_id: Union[int, str], media: list,
  535. disable_notification: bool = None,
  536. reply_to_message_id: int = None,
  537. allow_sending_without_reply: bool = None):
  538. """Send a group of photos or videos as an album.
  539. `media` must be a list of `InputMediaPhoto` and/or `InputMediaVideo`
  540. objects.
  541. See https://core.telegram.org/bots/api#sendmediagroup for details.
  542. """
  543. return await self.api_request(
  544. 'sendMediaGroup',
  545. parameters=locals()
  546. )
  547. async def sendLocation(self, chat_id: Union[int, str],
  548. latitude: float, longitude: float,
  549. horizontal_accuracy: float = None,
  550. live_period=None,
  551. heading: int = None,
  552. proximity_alert_radius: int = None,
  553. disable_notification: bool = None,
  554. reply_to_message_id: int = None,
  555. allow_sending_without_reply: bool = None,
  556. reply_markup=None):
  557. """Send a point on the map. May be kept updated for a `live_period`.
  558. See https://core.telegram.org/bots/api#sendlocation for details.
  559. """
  560. if horizontal_accuracy: # Horizontal accuracy: 0-1500 m [float].
  561. horizontal_accuracy = max(0.0, min(horizontal_accuracy, 1500.0))
  562. if live_period:
  563. live_period = max(60, min(live_period, 86400))
  564. if heading: # Direction in which the user is moving, 1-360°
  565. heading = max(1, min(heading, 360))
  566. if proximity_alert_radius: # Distance 1-100000 m
  567. proximity_alert_radius = max(1, min(proximity_alert_radius, 100000))
  568. return await self.api_request(
  569. 'sendLocation',
  570. parameters=locals()
  571. )
  572. async def editMessageLiveLocation(self, latitude: float, longitude: float,
  573. chat_id: Union[int, str] = None,
  574. message_id: int = None,
  575. inline_message_id: str = None,
  576. horizontal_accuracy: float = None,
  577. heading: int = None,
  578. proximity_alert_radius: int = None,
  579. reply_markup=None):
  580. """Edit live location messages.
  581. A location can be edited until its live_period expires or editing is
  582. explicitly disabled by a call to stopMessageLiveLocation.
  583. The message to be edited may be identified through `inline_message_id`
  584. OR the couple (`chat_id`, `message_id`).
  585. See https://core.telegram.org/bots/api#editmessagelivelocation
  586. for details.
  587. """
  588. if inline_message_id is None and (chat_id is None or message_id is None):
  589. logging.error("Invalid target chat!")
  590. if horizontal_accuracy: # Horizontal accuracy: 0-1500 m [float].
  591. horizontal_accuracy = max(0.0, min(horizontal_accuracy, 1500.0))
  592. if heading: # Direction in which the user is moving, 1-360°
  593. heading = max(1, min(heading, 360))
  594. if proximity_alert_radius: # Distance 1-100000 m
  595. proximity_alert_radius = max(1, min(proximity_alert_radius, 100000))
  596. return await self.api_request(
  597. 'editMessageLiveLocation',
  598. parameters=locals()
  599. )
  600. async def stopMessageLiveLocation(self,
  601. chat_id: Union[int, str] = None,
  602. message_id: int = None,
  603. inline_message_id: int = None,
  604. reply_markup=None):
  605. """Stop updating a live location message before live_period expires.
  606. The position to be stopped may be identified through
  607. `inline_message_id` OR the couple (`chat_id`, `message_id`).
  608. `reply_markup` type may be only `InlineKeyboardMarkup`.
  609. See https://core.telegram.org/bots/api#stopmessagelivelocation
  610. for details.
  611. """
  612. return await self.api_request(
  613. 'stopMessageLiveLocation',
  614. parameters=locals()
  615. )
  616. async def sendVenue(self, chat_id: Union[int, str],
  617. latitude: float, longitude: float,
  618. title: str, address: str,
  619. foursquare_id: str = None,
  620. foursquare_type: str = None,
  621. google_place_id: str = None,
  622. google_place_type: str = None,
  623. disable_notification: bool = None,
  624. reply_to_message_id: int = None,
  625. allow_sending_without_reply: bool = None,
  626. reply_markup=None):
  627. """Send information about a venue.
  628. Integrated with FourSquare.
  629. See https://core.telegram.org/bots/api#sendvenue for details.
  630. """
  631. return await self.api_request(
  632. 'sendVenue',
  633. parameters=locals()
  634. )
  635. async def sendContact(self, chat_id: Union[int, str],
  636. phone_number: str,
  637. first_name: str,
  638. last_name: str = None,
  639. vcard: str = None,
  640. disable_notification: bool = None,
  641. reply_to_message_id: int = None,
  642. allow_sending_without_reply: bool = None,
  643. reply_markup=None):
  644. """Send a phone contact.
  645. See https://core.telegram.org/bots/api#sendcontact for details.
  646. """
  647. return await self.api_request(
  648. 'sendContact',
  649. parameters=locals()
  650. )
  651. async def sendPoll(self,
  652. chat_id: Union[int, str],
  653. question: str,
  654. options: List[str],
  655. is_anonymous: bool = True,
  656. type_: str = 'regular',
  657. allows_multiple_answers: bool = False,
  658. correct_option_id: int = None,
  659. explanation: str = None,
  660. explanation_parse_mode: str = None,
  661. explanation_entities: List[dict] = None,
  662. open_period: int = None,
  663. close_date: Union[int, datetime.datetime] = None,
  664. is_closed: bool = None,
  665. disable_notification: bool = None,
  666. allow_sending_without_reply: bool = None,
  667. reply_to_message_id: int = None,
  668. reply_markup=None):
  669. """Send a native poll in a group, a supergroup or channel.
  670. See https://core.telegram.org/bots/api#sendpoll for details.
  671. close_date: Unix timestamp; 5-600 seconds from now.
  672. open_period (overwrites close_date): seconds (integer), 5-600.
  673. """
  674. if open_period is not None:
  675. close_date = None
  676. open_period = min(max(5, open_period), 600)
  677. elif isinstance(close_date, datetime.datetime):
  678. now = datetime.datetime.now()
  679. close_date = min(
  680. max(
  681. now + datetime.timedelta(seconds=5),
  682. close_date
  683. ), now + datetime.timedelta(seconds=600)
  684. )
  685. close_date = int(close_date.timestamp())
  686. # To avoid shadowing `type`, this workaround is required
  687. parameters = locals().copy()
  688. parameters['type'] = parameters['type_']
  689. del parameters['type_']
  690. return await self.api_request(
  691. 'sendPoll',
  692. parameters=parameters
  693. )
  694. async def sendChatAction(self, chat_id: Union[int, str], action):
  695. """Fake a typing status or similar.
  696. See https://core.telegram.org/bots/api#sendchataction for details.
  697. """
  698. return await self.api_request(
  699. 'sendChatAction',
  700. parameters=locals()
  701. )
  702. async def getUserProfilePhotos(self, user_id,
  703. offset=None,
  704. limit=None,):
  705. """Get a list of profile pictures for a user.
  706. See https://core.telegram.org/bots/api#getuserprofilephotos
  707. for details.
  708. """
  709. return await self.api_request(
  710. 'getUserProfilePhotos',
  711. parameters=locals()
  712. )
  713. async def getFile(self, file_id):
  714. """Get basic info about a file and prepare it for downloading.
  715. For the moment, bots can download files of up to
  716. 20MB in size.
  717. On success, a File object is returned. The file can then be downloaded
  718. via the link https://api.telegram.org/file/bot<token>/<file_path>,
  719. where <file_path> is taken from the response.
  720. See https://core.telegram.org/bots/api#getfile for details.
  721. """
  722. return await self.api_request(
  723. 'getFile',
  724. parameters=locals()
  725. )
  726. async def kickChatMember(self, chat_id: Union[int, str], user_id,
  727. until_date=None):
  728. """Kick a user from a group, a supergroup or a channel.
  729. In the case of supergroups and channels, the user will not be able to
  730. return to the group on their own using invite links, etc., unless
  731. unbanned first.
  732. Note: In regular groups (non-supergroups), this method will only work
  733. if the ‘All Members Are Admins’ setting is off in the target group.
  734. Otherwise members may only be removed by the group's creator or by
  735. the member that added them.
  736. See https://core.telegram.org/bots/api#kickchatmember for details.
  737. """
  738. return await self.api_request(
  739. 'kickChatMember',
  740. parameters=locals()
  741. )
  742. async def unbanChatMember(self, chat_id: Union[int, str], user_id: int,
  743. only_if_banned: bool = True):
  744. """Unban a previously kicked user in a supergroup or channel.
  745. The user will not return to the group or channel automatically, but
  746. will be able to join via link, etc.
  747. The bot must be an administrator for this to work.
  748. Return True on success.
  749. See https://core.telegram.org/bots/api#unbanchatmember for details.
  750. If `only_if_banned` is set to False, regular users will be kicked from
  751. chat upon call of this method on them.
  752. """
  753. return await self.api_request(
  754. 'unbanChatMember',
  755. parameters=locals()
  756. )
  757. async def restrictChatMember(self, chat_id: Union[int, str], user_id: int,
  758. permissions: Dict[str, bool],
  759. until_date: Union[datetime.datetime, int] = None):
  760. """Restrict a user in a supergroup.
  761. The bot must be an administrator in the supergroup for this to work
  762. and must have the appropriate admin rights.
  763. Pass True for all boolean parameters to lift restrictions from a
  764. user.
  765. Return True on success.
  766. See https://core.telegram.org/bots/api#restrictchatmember for details.
  767. until_date must be a Unix timestamp.
  768. """
  769. if isinstance(until_date, datetime.datetime):
  770. until_date = int(until_date.timestamp())
  771. return await self.api_request(
  772. 'restrictChatMember',
  773. parameters=locals()
  774. )
  775. async def promoteChatMember(self, chat_id: Union[int, str], user_id: int,
  776. is_anonymous: bool = None,
  777. can_change_info: bool = None,
  778. can_post_messages: bool = None,
  779. can_edit_messages: bool = None,
  780. can_delete_messages: bool = None,
  781. can_invite_users: bool = None,
  782. can_restrict_members: bool = None,
  783. can_pin_messages: bool = None,
  784. can_promote_members: bool = None):
  785. """Promote or demote a user in a supergroup or a channel.
  786. The bot must be an administrator in the chat for this to work and must
  787. have the appropriate admin rights.
  788. Pass False for all boolean parameters to demote a user.
  789. Return True on success.
  790. See https://core.telegram.org/bots/api#promotechatmember for details.
  791. """
  792. return await self.api_request(
  793. 'promoteChatMember',
  794. parameters=locals()
  795. )
  796. async def exportChatInviteLink(self, chat_id: Union[int, str]):
  797. """Generate a new invite link for a chat and revoke any active link.
  798. The bot must be an administrator in the chat for this to work and must
  799. have the appropriate admin rights.
  800. Return the new invite link as String on success.
  801. NOTE: to get the current invite link, use `getChat` method.
  802. See https://core.telegram.org/bots/api#exportchatinvitelink
  803. for details.
  804. """
  805. return await self.api_request(
  806. 'exportChatInviteLink',
  807. parameters=locals()
  808. )
  809. async def setChatPhoto(self, chat_id: Union[int, str], photo):
  810. """Set a new profile photo for the chat.
  811. Photos can't be changed for private chats.
  812. `photo` must be an input file (file_id and urls are not allowed).
  813. The bot must be an administrator in the chat for this to work and must
  814. have the appropriate admin rights.
  815. Return True on success.
  816. See https://core.telegram.org/bots/api#setchatphoto for details.
  817. """
  818. return await self.api_request(
  819. 'setChatPhoto',
  820. parameters=locals()
  821. )
  822. async def deleteChatPhoto(self, chat_id: Union[int, str]):
  823. """Delete a chat photo.
  824. Photos can't be changed for private chats.
  825. The bot must be an administrator in the chat for this to work and must
  826. have the appropriate admin rights.
  827. Return True on success.
  828. See https://core.telegram.org/bots/api#deletechatphoto for details.
  829. """
  830. return await self.api_request(
  831. 'deleteChatPhoto',
  832. parameters=locals()
  833. )
  834. async def setChatTitle(self, chat_id: Union[int, str], title):
  835. """Change the title of a chat.
  836. Titles can't be changed for private chats.
  837. The bot must be an administrator in the chat for this to work and must
  838. have the appropriate admin rights.
  839. Return True on success.
  840. See https://core.telegram.org/bots/api#setchattitle for details.
  841. """
  842. return await self.api_request(
  843. 'setChatTitle',
  844. parameters=locals()
  845. )
  846. async def setChatDescription(self, chat_id: Union[int, str], description):
  847. """Change the description of a supergroup or a channel.
  848. The bot must be an administrator in the chat for this to work and must
  849. have the appropriate admin rights.
  850. Return True on success.
  851. See https://core.telegram.org/bots/api#setchatdescription for details.
  852. """
  853. return await self.api_request(
  854. 'setChatDescription',
  855. parameters=locals()
  856. )
  857. async def pinChatMessage(self, chat_id: Union[int, str], message_id,
  858. disable_notification: bool = None):
  859. """Pin a message in a group, a supergroup, or a channel.
  860. The bot must be an administrator in the chat for this to work and must
  861. have the ‘can_pin_messages’ admin right in the supergroup or
  862. ‘can_edit_messages’ admin right in the channel.
  863. Return True on success.
  864. See https://core.telegram.org/bots/api#pinchatmessage for details.
  865. """
  866. return await self.api_request(
  867. 'pinChatMessage',
  868. parameters=locals()
  869. )
  870. async def unpinChatMessage(self, chat_id: Union[int, str],
  871. message_id: int = None):
  872. """Unpin a message in a group, a supergroup, or a channel.
  873. The bot must be an administrator in the chat for this to work and must
  874. have the ‘can_pin_messages’ admin right in the supergroup or
  875. ‘can_edit_messages’ admin right in the channel.
  876. Return True on success.
  877. See https://core.telegram.org/bots/api#unpinchatmessage for details.
  878. """
  879. return await self.api_request(
  880. 'unpinChatMessage',
  881. parameters=locals()
  882. )
  883. async def leaveChat(self, chat_id: Union[int, str]):
  884. """Make the bot leave a group, supergroup or channel.
  885. Return True on success.
  886. See https://core.telegram.org/bots/api#leavechat for details.
  887. """
  888. return await self.api_request(
  889. 'leaveChat',
  890. parameters=locals()
  891. )
  892. async def getChat(self, chat_id: Union[int, str]):
  893. """Get up to date information about the chat.
  894. Return a Chat object on success.
  895. See https://core.telegram.org/bots/api#getchat for details.
  896. """
  897. return await self.api_request(
  898. 'getChat',
  899. parameters=locals()
  900. )
  901. async def getChatAdministrators(self, chat_id: Union[int, str]):
  902. """Get a list of administrators in a chat.
  903. On success, return an Array of ChatMember objects that contains
  904. information about all chat administrators except other bots.
  905. If the chat is a group or a supergroup and no administrators were
  906. appointed, only the creator will be returned.
  907. See https://core.telegram.org/bots/api#getchatadministrators
  908. for details.
  909. """
  910. return await self.api_request(
  911. 'getChatAdministrators',
  912. parameters=locals()
  913. )
  914. async def getChatMembersCount(self, chat_id: Union[int, str]):
  915. """Get the number of members in a chat.
  916. Returns Int on success.
  917. See https://core.telegram.org/bots/api#getchatmemberscount for details.
  918. """
  919. return await self.api_request(
  920. 'getChatMembersCount',
  921. parameters=locals()
  922. )
  923. async def getChatMember(self, chat_id: Union[int, str], user_id):
  924. """Get information about a member of a chat.
  925. Returns a ChatMember object on success.
  926. See https://core.telegram.org/bots/api#getchatmember for details.
  927. """
  928. return await self.api_request(
  929. 'getChatMember',
  930. parameters=locals()
  931. )
  932. async def setChatStickerSet(self, chat_id: Union[int, str], sticker_set_name):
  933. """Set a new group sticker set for a supergroup.
  934. The bot must be an administrator in the chat for this to work and must
  935. have the appropriate admin rights.
  936. Use the field `can_set_sticker_set` optionally returned in getChat
  937. requests to check if the bot can use this method.
  938. Returns True on success.
  939. See https://core.telegram.org/bots/api#setchatstickerset for details.
  940. """
  941. return await self.api_request(
  942. 'setChatStickerSet',
  943. parameters=locals()
  944. )
  945. async def deleteChatStickerSet(self, chat_id: Union[int, str]):
  946. """Delete a group sticker set from a supergroup.
  947. The bot must be an administrator in the chat for this to work and must
  948. have the appropriate admin rights.
  949. Use the field `can_set_sticker_set` optionally returned in getChat
  950. requests to check if the bot can use this method.
  951. Returns True on success.
  952. See https://core.telegram.org/bots/api#deletechatstickerset for
  953. details.
  954. """
  955. return await self.api_request(
  956. 'deleteChatStickerSet',
  957. parameters=locals()
  958. )
  959. async def answerCallbackQuery(self, callback_query_id,
  960. text=None,
  961. show_alert=None,
  962. url=None,
  963. cache_time=None):
  964. """Send answers to callback queries sent from inline keyboards.
  965. The answer will be displayed to the user as a notification at the top
  966. of the chat screen or as an alert.
  967. On success, True is returned.
  968. See https://core.telegram.org/bots/api#answercallbackquery for details.
  969. """
  970. return await self.api_request(
  971. 'answerCallbackQuery',
  972. parameters=locals()
  973. )
  974. async def editMessageText(self, text: str,
  975. chat_id: Union[int, str] = None,
  976. message_id: int = None,
  977. inline_message_id: str = None,
  978. parse_mode: str = None,
  979. entities: List[dict] = None,
  980. disable_web_page_preview: bool = None,
  981. reply_markup=None):
  982. """Edit text and game messages.
  983. On success, if edited message is sent by the bot, the edited Message
  984. is returned, otherwise True is returned.
  985. See https://core.telegram.org/bots/api#editmessagetext for details.
  986. """
  987. return await self.api_request(
  988. 'editMessageText',
  989. parameters=locals()
  990. )
  991. async def editMessageCaption(self,
  992. chat_id: Union[int, str] = None,
  993. message_id: int = None,
  994. inline_message_id: str = None,
  995. caption: str = None,
  996. parse_mode: str = None,
  997. caption_entities: List[dict] = None,
  998. reply_markup=None):
  999. """Edit captions of messages.
  1000. On success, if edited message is sent by the bot, the edited Message is
  1001. returned, otherwise True is returned.
  1002. See https://core.telegram.org/bots/api#editmessagecaption for details.
  1003. """
  1004. return await self.api_request(
  1005. 'editMessageCaption',
  1006. parameters=locals()
  1007. )
  1008. async def editMessageMedia(self,
  1009. chat_id: Union[int, str] = None,
  1010. message_id: int = None,
  1011. inline_message_id: str = None,
  1012. media=None,
  1013. reply_markup=None):
  1014. """Edit animation, audio, document, photo, or video messages.
  1015. If a message is a part of a message album, then it can be edited only
  1016. to a photo or a video. Otherwise, message type can be changed
  1017. arbitrarily.
  1018. When inline message is edited, new file can't be uploaded.
  1019. Use previously uploaded file via its file_id or specify a URL.
  1020. On success, if the edited message was sent by the bot, the edited
  1021. Message is returned, otherwise True is returned.
  1022. See https://core.telegram.org/bots/api#editmessagemedia for details.
  1023. """
  1024. return await self.api_request(
  1025. 'editMessageMedia',
  1026. parameters=locals()
  1027. )
  1028. async def editMessageReplyMarkup(self,
  1029. chat_id: Union[int, str] = None,
  1030. message_id: int = None,
  1031. inline_message_id: str = None,
  1032. reply_markup=None):
  1033. """Edit only the reply markup of messages.
  1034. On success, if edited message is sent by the bot, the edited Message is
  1035. returned, otherwise True is returned.
  1036. See https://core.telegram.org/bots/api#editmessagereplymarkup for
  1037. details.
  1038. """
  1039. return await self.api_request(
  1040. 'editMessageReplyMarkup',
  1041. parameters=locals()
  1042. )
  1043. async def stopPoll(self, chat_id: Union[int, str], message_id,
  1044. reply_markup=None):
  1045. """Stop a poll which was sent by the bot.
  1046. On success, the stopped Poll with the final results is returned.
  1047. `reply_markup` type may be only `InlineKeyboardMarkup`.
  1048. See https://core.telegram.org/bots/api#stoppoll for details.
  1049. """
  1050. return await self.api_request(
  1051. 'stopPoll',
  1052. parameters=locals()
  1053. )
  1054. async def deleteMessage(self, chat_id: Union[int, str], message_id):
  1055. """Delete a message, including service messages.
  1056. - A message can only be deleted if it was sent less than 48 hours
  1057. ago.
  1058. - Bots can delete outgoing messages in private chats, groups, and
  1059. supergroups.
  1060. - Bots can delete incoming messages in private chats.
  1061. - Bots granted can_post_messages permissions can delete outgoing
  1062. messages in channels.
  1063. - If the bot is an administrator of a group, it can delete any
  1064. message there.
  1065. - If the bot has can_delete_messages permission in a supergroup or
  1066. a channel, it can delete any message there.
  1067. Returns True on success.
  1068. See https://core.telegram.org/bots/api#deletemessage for details.
  1069. """
  1070. return await self.api_request(
  1071. 'deleteMessage',
  1072. parameters=locals()
  1073. )
  1074. async def sendSticker(self, chat_id: Union[int, str],
  1075. sticker: Union[str, dict, IO],
  1076. disable_notification: bool = None,
  1077. reply_to_message_id: int = None,
  1078. allow_sending_without_reply: bool = None,
  1079. reply_markup=None):
  1080. """Send `.webp` stickers.
  1081. On success, the sent Message is returned.
  1082. See https://core.telegram.org/bots/api#sendsticker for details.
  1083. """
  1084. sticker = self.prepare_file_object(sticker)
  1085. if sticker is None:
  1086. logging.error("Invalid sticker provided!")
  1087. return
  1088. result = await self.api_request(
  1089. 'sendSticker',
  1090. parameters=locals()
  1091. )
  1092. if type(sticker) is dict: # Close sticker file, if it was open
  1093. sticker['file'].close()
  1094. return result
  1095. async def getStickerSet(self, name):
  1096. """Get a sticker set.
  1097. On success, a StickerSet object is returned.
  1098. See https://core.telegram.org/bots/api#getstickerset for details.
  1099. """
  1100. return await self.api_request(
  1101. 'getStickerSet',
  1102. parameters=locals()
  1103. )
  1104. async def uploadStickerFile(self, user_id, png_sticker):
  1105. """Upload a .png file as a sticker.
  1106. Use it later via `createNewStickerSet` and `addStickerToSet` methods
  1107. (can be used multiple times).
  1108. Return the uploaded File on success.
  1109. `png_sticker` must be a *.png image up to 512 kilobytes in size,
  1110. dimensions must not exceed 512px, and either width or height must
  1111. be exactly 512px.
  1112. See https://core.telegram.org/bots/api#uploadstickerfile for details.
  1113. """
  1114. return await self.api_request(
  1115. 'uploadStickerFile',
  1116. parameters=locals()
  1117. )
  1118. async def createNewStickerSet(self, user_id: int, name: str, title: str,
  1119. emojis: str,
  1120. png_sticker: Union[str, dict, IO] = None,
  1121. tgs_sticker: Union[str, dict, IO] = None,
  1122. contains_masks: bool = None,
  1123. mask_position: dict = None):
  1124. """Create new sticker set owned by a user.
  1125. The bot will be able to edit the created sticker set.
  1126. Returns True on success.
  1127. See https://core.telegram.org/bots/api#createnewstickerset for details.
  1128. """
  1129. png_sticker = self.prepare_file_object(png_sticker)
  1130. tgs_sticker = self.prepare_file_object(tgs_sticker)
  1131. if png_sticker is None and tgs_sticker is None:
  1132. logging.error("Invalid sticker provided!")
  1133. return
  1134. result = await self.api_request(
  1135. 'createNewStickerSet',
  1136. parameters=locals()
  1137. )
  1138. if type(png_sticker) is dict: # Close png_sticker file, if it was open
  1139. png_sticker['file'].close()
  1140. if type(tgs_sticker) is dict: # Close tgs_sticker file, if it was open
  1141. tgs_sticker['file'].close()
  1142. return result
  1143. async def addStickerToSet(self, user_id: int, name: str,
  1144. emojis: str,
  1145. png_sticker: Union[str, dict, IO] = None,
  1146. tgs_sticker: Union[str, dict, IO] = None,
  1147. mask_position: dict = None):
  1148. """Add a new sticker to a set created by the bot.
  1149. Returns True on success.
  1150. See https://core.telegram.org/bots/api#addstickertoset for details.
  1151. """
  1152. png_sticker = self.prepare_file_object(png_sticker)
  1153. tgs_sticker = self.prepare_file_object(tgs_sticker)
  1154. if png_sticker is None and tgs_sticker is None:
  1155. logging.error("Invalid sticker provided!")
  1156. return
  1157. result = await self.api_request(
  1158. 'addStickerToSet',
  1159. parameters=locals()
  1160. )
  1161. if type(png_sticker) is dict: # Close png_sticker file, if it was open
  1162. png_sticker['file'].close()
  1163. if type(tgs_sticker) is dict: # Close tgs_sticker file, if it was open
  1164. tgs_sticker['file'].close()
  1165. return result
  1166. async def setStickerPositionInSet(self, sticker, position):
  1167. """Move a sticker in a set created by the bot to a specific position .
  1168. Position is 0-based.
  1169. Returns True on success.
  1170. See https://core.telegram.org/bots/api#setstickerpositioninset for
  1171. details.
  1172. """
  1173. return await self.api_request(
  1174. 'setStickerPositionInSet',
  1175. parameters=locals()
  1176. )
  1177. async def deleteStickerFromSet(self, sticker):
  1178. """Delete a sticker from a set created by the bot.
  1179. Returns True on success.
  1180. See https://core.telegram.org/bots/api#deletestickerfromset for
  1181. details.
  1182. """
  1183. return await self.api_request(
  1184. 'deleteStickerFromSet',
  1185. parameters=locals()
  1186. )
  1187. async def answerInlineQuery(self, inline_query_id, results,
  1188. cache_time=None,
  1189. is_personal=None,
  1190. next_offset=None,
  1191. switch_pm_text=None,
  1192. switch_pm_parameter=None):
  1193. """Send answers to an inline query.
  1194. On success, True is returned.
  1195. No more than 50 results per query are allowed.
  1196. See https://core.telegram.org/bots/api#answerinlinequery for details.
  1197. """
  1198. return await self.api_request(
  1199. 'answerInlineQuery',
  1200. parameters=locals()
  1201. )
  1202. async def sendInvoice(self, chat_id: int, title: str, description: str,
  1203. payload: str, provider_token: str,
  1204. start_parameter: str, currency: str, prices: List[dict],
  1205. provider_data: str = None,
  1206. photo_url: str = None,
  1207. photo_size: int = None,
  1208. photo_width: int = None,
  1209. photo_height: int = None,
  1210. need_name: bool = None,
  1211. need_phone_number: bool = None,
  1212. need_email: bool = None,
  1213. need_shipping_address: bool = None,
  1214. send_phone_number_to_provider: bool = None,
  1215. send_email_to_provider: bool = None,
  1216. is_flexible: bool = None,
  1217. disable_notification: bool = None,
  1218. reply_to_message_id: int = None,
  1219. allow_sending_without_reply: bool = None,
  1220. reply_markup=None):
  1221. """Send an invoice.
  1222. On success, the sent Message is returned.
  1223. See https://core.telegram.org/bots/api#sendinvoice for details.
  1224. """
  1225. return await self.api_request(
  1226. 'sendInvoice',
  1227. parameters=locals()
  1228. )
  1229. async def answerShippingQuery(self, shipping_query_id, ok,
  1230. shipping_options=None,
  1231. error_message=None):
  1232. """Reply to shipping queries.
  1233. On success, True is returned.
  1234. If you sent an invoice requesting a shipping address and the parameter
  1235. is_flexible was specified, the Bot API will send an Update with a
  1236. shipping_query field to the bot.
  1237. See https://core.telegram.org/bots/api#answershippingquery for details.
  1238. """
  1239. return await self.api_request(
  1240. 'answerShippingQuery',
  1241. parameters=locals()
  1242. )
  1243. async def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
  1244. error_message=None):
  1245. """Respond to pre-checkout queries.
  1246. Once the user has confirmed their payment and shipping details, the Bot
  1247. API sends the final confirmation in the form of an Update with the
  1248. field pre_checkout_query.
  1249. On success, True is returned.
  1250. Note: The Bot API must receive an answer within 10 seconds after the
  1251. pre-checkout query was sent.
  1252. See https://core.telegram.org/bots/api#answerprecheckoutquery for
  1253. details.
  1254. """
  1255. return await self.api_request(
  1256. 'answerPreCheckoutQuery',
  1257. parameters=locals()
  1258. )
  1259. async def setPassportDataErrors(self, user_id, errors):
  1260. """Refuse a Telegram Passport element with `errors`.
  1261. Inform a user that some of the Telegram Passport elements they provided
  1262. contains errors.
  1263. The user will not be able to re-submit their Passport to you until the
  1264. errors are fixed (the contents of the field for which you returned
  1265. the error must change).
  1266. Returns True on success.
  1267. Use this if the data submitted by the user doesn't satisfy the
  1268. standards your service requires for any reason.
  1269. For example, if a birthday date seems invalid, a submitted document
  1270. is blurry, a scan shows evidence of tampering, etc.
  1271. Supply some details in the error message to make sure the user knows
  1272. how to correct the issues.
  1273. See https://core.telegram.org/bots/api#setpassportdataerrors for
  1274. details.
  1275. """
  1276. return await self.api_request(
  1277. 'setPassportDataErrors',
  1278. parameters=locals()
  1279. )
  1280. async def sendGame(self, chat_id: Union[int, str], game_short_name,
  1281. disable_notification: bool = None,
  1282. reply_to_message_id: int = None,
  1283. reply_markup=None,
  1284. allow_sending_without_reply: bool = None):
  1285. """Send a game.
  1286. On success, the sent Message is returned.
  1287. See https://core.telegram.org/bots/api#sendgame for
  1288. details.
  1289. """
  1290. return await self.api_request(
  1291. 'sendGame',
  1292. parameters=locals()
  1293. )
  1294. async def setGameScore(self, user_id: int, score: int,
  1295. force: bool = None,
  1296. disable_edit_message: bool = None,
  1297. chat_id: Union[int, str] = None,
  1298. message_id: int = None,
  1299. inline_message_id: str = None):
  1300. """Set the score of the specified user in a game.
  1301. On success, if the message was sent by the bot, returns the edited
  1302. Message, otherwise returns True.
  1303. Returns an error, if the new score is not greater than the user's
  1304. current score in the chat and force is False.
  1305. See https://core.telegram.org/bots/api#setgamescore for
  1306. details.
  1307. """
  1308. return await self.api_request(
  1309. 'setGameScore',
  1310. parameters=locals()
  1311. )
  1312. async def getGameHighScores(self, user_id,
  1313. chat_id: Union[int, str] = None,
  1314. message_id: int = None,
  1315. inline_message_id: str = None):
  1316. """Get data for high score tables.
  1317. Will return the score of the specified user and several of his
  1318. neighbors in a game.
  1319. On success, returns an Array of GameHighScore objects.
  1320. This method will currently return scores for the target user, plus two
  1321. of his closest neighbors on each side. Will also return the top
  1322. three users if the user and his neighbors are not among them.
  1323. Please note that this behavior is subject to change.
  1324. See https://core.telegram.org/bots/api#getgamehighscores for
  1325. details.
  1326. """
  1327. return await self.api_request(
  1328. 'getGameHighScores',
  1329. parameters=locals()
  1330. )
  1331. async def sendDice(self,
  1332. chat_id: Union[int, str] = None,
  1333. emoji: str = None,
  1334. disable_notification: bool = None,
  1335. reply_to_message_id: int = None,
  1336. allow_sending_without_reply: bool = None,
  1337. reply_markup=None):
  1338. """Send a dice.
  1339. Use this method to send a dice, which will have a random value from 1
  1340. to 6.
  1341. On success, the sent Message is returned.
  1342. (Yes, we're aware of the “proper” singular of die. But it's awkward,
  1343. and we decided to help it change. One dice at a time!)
  1344. See https://core.telegram.org/bots/api#senddice for
  1345. details.
  1346. """
  1347. return await self.api_request(
  1348. 'sendDice',
  1349. parameters=locals()
  1350. )
  1351. async def setChatAdministratorCustomTitle(self,
  1352. chat_id: Union[int, str] = None,
  1353. user_id: int = None,
  1354. custom_title: str = None):
  1355. """Set a custom title for an administrator.
  1356. Use this method to set a custom title for an administrator in a
  1357. supergroup promoted by the bot.
  1358. Returns True on success.
  1359. See https://core.telegram.org/bots/api#setchatadministratorcustomtitle
  1360. for details.
  1361. """
  1362. return await self.api_request(
  1363. 'setChatAdministratorCustomTitle',
  1364. parameters=locals()
  1365. )
  1366. async def setChatPermissions(self,
  1367. chat_id: Union[int, str] = None,
  1368. permissions: Union[ChatPermissions,
  1369. dict] = None):
  1370. """Set default chat permissions for all members.
  1371. Use this method to set default chat permissions for all members.
  1372. The bot must be an administrator in the group or a supergroup for this
  1373. to work and must have the can_restrict_members admin rights.
  1374. Returns True on success.
  1375. See https://core.telegram.org/bots/api#setchatpermissions for details.
  1376. """
  1377. return await self.api_request(
  1378. 'setChatPermissions',
  1379. parameters=locals()
  1380. )
  1381. async def setMyCommands(self, commands: List[Union[Command, dict]]):
  1382. """Change the list of the bot's commands.
  1383. Use this method to change the list of the bot's commands.
  1384. Returns True on success.
  1385. See https://core.telegram.org/bots/api#setmycommands for details.
  1386. """
  1387. return await self.api_request(
  1388. 'setMyCommands',
  1389. parameters=locals()
  1390. )
  1391. async def getMyCommands(self):
  1392. """Get the current list of the bot's commands.
  1393. Use this method to get the current list of the bot's commands.
  1394. Requires no parameters.
  1395. Returns Array of BotCommand on success.
  1396. See https://core.telegram.org/bots/api#getmycommands for details.
  1397. """
  1398. return await self.api_request(
  1399. 'getMyCommands',
  1400. parameters=locals()
  1401. )
  1402. async def setStickerSetThumb(self,
  1403. name: str = None,
  1404. user_id: int = None,
  1405. thumb=None):
  1406. """Set the thumbnail of a sticker set.
  1407. Use this method to set the thumbnail of a sticker set.
  1408. Animated thumbnails can be set for animated sticker sets only.
  1409. Returns True on success.
  1410. See https://core.telegram.org/bots/api#setstickersetthumb for details.
  1411. """
  1412. return await self.api_request(
  1413. 'setStickerSetThumb',
  1414. parameters=locals()
  1415. )
  1416. async def logOut(self):
  1417. """Log out from the cloud Bot API server.
  1418. Use this method to log out from the cloud Bot API server
  1419. before launching the bot locally.
  1420. You must log out the bot before running it locally, otherwise there
  1421. is no guarantee that the bot will receive updates.
  1422. After a successful call, you can immediately log in on a local server,
  1423. but will not be able to log in back to the cloud Bot API server
  1424. for 10 minutes.
  1425. Returns True on success. Requires no parameters.
  1426. See https://core.telegram.org/bots/api#logout for details.
  1427. """
  1428. return await self.api_request(
  1429. 'logOut',
  1430. parameters=locals()
  1431. )
  1432. async def close(self):
  1433. """Close bot instance in local server.
  1434. Use this method to close the bot instance before moving it from one
  1435. local server to another.
  1436. You need to delete the webhook before calling this method to ensure
  1437. that the bot isn't launched again after server restart.
  1438. The method will return error 429 in the first 10 minutes after the
  1439. bot is launched. Returns True on success.
  1440. Requires no parameters.
  1441. See https://core.telegram.org/bots/api#close for details.
  1442. """
  1443. return await self.api_request(
  1444. 'close',
  1445. parameters=locals()
  1446. )
  1447. async def copyMessage(self, chat_id: Union[int, str],
  1448. from_chat_id: Union[int, str],
  1449. message_id: int,
  1450. caption: str = None,
  1451. parse_mode: str = None,
  1452. caption_entities: list = None,
  1453. disable_notification: bool = None,
  1454. reply_to_message_id: int = None,
  1455. allow_sending_without_reply: bool = None,
  1456. reply_markup=None):
  1457. """Use this method to copy messages of any kind.
  1458. The method is analogous to the method forwardMessages, but the copied
  1459. message doesn't have a link to the original message.
  1460. Returns the MessageId of the sent message on success.
  1461. See https://core.telegram.org/bots/api#copymessage for details.
  1462. """
  1463. return await self.api_request(
  1464. 'copyMessage',
  1465. parameters=locals()
  1466. )
  1467. async def unpinAllChatMessages(self, chat_id: Union[int, str]):
  1468. """Use this method to clear the list of pinned messages in a chat.
  1469. If the chat is not a private chat, the bot must be an administrator
  1470. in the chat for this to work and must have the 'can_pin_messages'
  1471. admin right in a supergroup or 'can_edit_messages' admin right in a
  1472. channel.
  1473. Returns True on success.
  1474. See https://core.telegram.org/bots/api#unpinallchatmessages for details.
  1475. """
  1476. return await self.api_request(
  1477. 'unpinAllChatMessages',
  1478. parameters=locals()
  1479. )