Queer European MD passionate about IT

api.py 66 KB

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