Queer European MD passionate about IT

api.py 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666
  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. import os.path
  12. from typing import Dict, Union, List, IO
  13. # Third party modules
  14. import aiohttp
  15. import aiohttp.web
  16. class TelegramError(Exception):
  17. """Telegram API exceptions class."""
  18. # noinspection PyUnusedLocal
  19. def __init__(self, error_code=0, description=None, ok=False,
  20. *args, **kwargs):
  21. """Get an error response and return corresponding Exception."""
  22. self._code = error_code
  23. if description is None:
  24. self._description = 'Generic error'
  25. else:
  26. self._description = description
  27. super().__init__(self.description)
  28. @property
  29. def code(self):
  30. """Telegram error code."""
  31. return self._code
  32. @property
  33. def description(self):
  34. """Human-readable description of error."""
  35. return f"Error {self.code}: {self._description}"
  36. class ChatPermissions(dict):
  37. """Actions that a non-administrator user is allowed to take in a chat.
  38. See https://core.telegram.org/bots/api#chatpermissions for details.
  39. """
  40. def __init__(self,
  41. can_send_messages: bool = True,
  42. can_send_media_messages: bool = True,
  43. can_send_polls: bool = True,
  44. can_send_other_messages: bool = True,
  45. can_add_web_page_previews: bool = True,
  46. can_change_info: bool = True,
  47. can_invite_users: bool = True,
  48. can_pin_messages: bool = True):
  49. super().__init__(self)
  50. self['can_send_messages'] = can_send_messages
  51. self['can_send_media_messages'] = can_send_media_messages
  52. self['can_send_polls'] = can_send_polls
  53. self['can_send_other_messages'] = can_send_other_messages
  54. self['can_add_web_page_previews'] = can_add_web_page_previews
  55. self['can_change_info'] = can_change_info
  56. self['can_invite_users'] = can_invite_users
  57. self['can_pin_messages'] = can_pin_messages
  58. class Command(dict):
  59. def __init__(self,
  60. command: str = None,
  61. description: str = None):
  62. super().__init__(self)
  63. self['command'] = command
  64. self['description'] = description
  65. class BotCommandScope(dict):
  66. """This object represents the scope to which bot commands are applied.
  67. See https://core.telegram.org/bots/api#botcommandscope for details.
  68. Currently, the following 7 scopes are supported:
  69. - BotCommandScopeDefault;
  70. - BotCommandScopeAllPrivateChats;
  71. - BotCommandScopeAllGroupChats;
  72. - BotCommandScopeAllChatAdministrators;
  73. - BotCommandScopeChat;
  74. - BotCommandScopeChatAdministrators;
  75. - BotCommandScopeChatMember.
  76. An algorithm described [here](https://core.telegram.org/bots/api#botcommandscope)
  77. is used to determine the list of commands for a particular user
  78. viewing the bot menu.
  79. """
  80. # noinspection PyShadowingBuiltins
  81. def __init__(self,
  82. type: str = 'default'):
  83. if type not in ('default', 'all_private_chats', 'all_group_chats',
  84. 'all_chat_administrators', 'chat', 'chat_administrators',
  85. 'chat_member'):
  86. raise TypeError(f"Unknown bot command scope type: `{type}`.")
  87. super().__init__(self)
  88. self['type'] = type
  89. class WebAppInfo(dict):
  90. """Describes a Web App.
  91. See https://core.telegram.org/bots/api#webappinfo for details."""
  92. def __init__(self,
  93. url: str = None):
  94. super().__init__(self)
  95. self['url'] = url
  96. class MenuButton(dict):
  97. # noinspection PyShadowingBuiltins
  98. def __init__(self,
  99. type: str = 'default',
  100. text: str = None,
  101. web_app: 'WebAppInfo' = None):
  102. if type not in ('default', 'commands', 'web_app'):
  103. raise TypeError(f"Unknown menu button type: `{type}`.")
  104. super().__init__(self)
  105. self['type'] = type
  106. if type == 'web_app':
  107. self['text'] = text
  108. self['web_app'] = web_app
  109. class ChatAdministratorRights(dict):
  110. """Represents the rights of an administrator in a chat."""
  111. def __init__(self,
  112. is_anonymous: bool = False,
  113. can_manage_chat: bool = False,
  114. can_delete_messages: bool = False,
  115. can_manage_video_chats: bool = False,
  116. can_restrict_members: bool = False,
  117. can_promote_members: bool = False,
  118. can_change_info: bool = False,
  119. can_invite_users: bool = False,
  120. can_post_messages: bool = False,
  121. can_edit_messages: bool = False,
  122. can_pin_messages: bool = False,
  123. can_manage_topics: bool = False):
  124. """Represents the rights of an administrator in a chat.
  125. @param is_anonymous: True, if the user's presence in the chat is hidden
  126. @param can_manage_chat: True, if the administrator can access the chat
  127. event log, chat statistics, message statistics in channels, see
  128. channel members, see anonymous administrators in supergroups and
  129. ignore slow mode. Implied by any other administrator privilege
  130. @param can_delete_messages: True, if the administrator can delete
  131. messages of other users
  132. @param can_manage_video_chats: True, if the administrator can manage
  133. video chats
  134. @param can_restrict_members: True, if the administrator can restrict,
  135. ban or unban chat members
  136. @param can_promote_members: True, if the administrator can add new
  137. administrators with a subset of their own privileges or demote
  138. administrators that he has promoted, directly or indirectly
  139. (promoted by administrators that were appointed by the user)
  140. @param can_change_info: True, if the user is allowed to change the
  141. chat title, photo and other settings
  142. @param can_invite_users: True, if the user is allowed to invite new
  143. users to the chat
  144. @param can_post_messages: Optional. True, if the administrator can
  145. post in the channel; channels only
  146. @param can_edit_messages: Optional. True, if the administrator can
  147. edit messages of other users and can pin messages; channels only
  148. @param can_pin_messages: Optional. True, if the user is allowed to
  149. pin messages; groups and supergroups only
  150. @param can_manage_topics: Optional. True, if the user is allowed to
  151. create, rename, close, and reopen forum topics; supergroups only
  152. """
  153. super().__init__(self)
  154. self['is_anonymous'] = is_anonymous
  155. self['can_manage_chat'] = can_manage_chat
  156. self['can_delete_messages'] = can_delete_messages
  157. self['can_manage_video_chats'] = can_manage_video_chats
  158. self['can_restrict_members'] = can_restrict_members
  159. self['can_promote_members'] = can_promote_members
  160. self['can_change_info'] = can_change_info
  161. self['can_invite_users'] = can_invite_users
  162. self['can_post_messages'] = can_post_messages
  163. self['can_edit_messages'] = can_edit_messages
  164. self['can_pin_messages'] = can_pin_messages
  165. self['can_manage_topics'] = can_manage_topics
  166. class LabeledPrice(dict):
  167. """This object represents a portion of the price for goods or services."""
  168. def __init__(self, label: str, amount: int):
  169. """This object represents a portion of the price for goods or services.
  170. @param label: Portion label.
  171. @param amount: Price of the product in the smallest units of the
  172. currency (integer, not float/double).
  173. For example, for a price of US$ 1.45 pass amount = 145.
  174. See the exp parameter in currencies.json, it shows the number of
  175. digits past the decimal point for each currency (2 for the majority
  176. of currencies).
  177. Reference (currencies.json): https://core.telegram.org/bots/payments/currencies.json
  178. """
  179. super().__init__(self)
  180. self['label'] = label
  181. self['amount'] = amount
  182. class InlineQueryResult(dict):
  183. """This object represents one result of an inline query.
  184. Telegram clients currently support results of the following 20 types:
  185. - InlineQueryResultCachedAudio;
  186. - InlineQueryResultCachedDocument;
  187. - InlineQueryResultCachedGif;
  188. - InlineQueryResultCachedMpeg4Gif;
  189. - InlineQueryResultCachedPhoto;
  190. - InlineQueryResultCachedSticker;
  191. - InlineQueryResultCachedVideo;
  192. - InlineQueryResultCachedVoice;
  193. - InlineQueryResultArticle;
  194. - InlineQueryResultAudio;
  195. - InlineQueryResultContact;
  196. - InlineQueryResultGame;
  197. - InlineQueryResultDocument;
  198. - InlineQueryResultGif;
  199. - InlineQueryResultLocation;
  200. - InlineQueryResultMpeg4Gif;
  201. - InlineQueryResultPhoto;
  202. - InlineQueryResultVenue;
  203. - InlineQueryResultVideo.
  204. Note: All URLs passed in inline query results will be available to end
  205. users and therefore must be assumed to be public.
  206. """
  207. # noinspection PyShadowingBuiltins
  208. def __init__(self,
  209. type: str = 'default',
  210. **kwargs):
  211. if type not in ('InlineQueryResultCachedAudio',
  212. 'InlineQueryResultCachedDocument',
  213. 'InlineQueryResultCachedGif',
  214. 'InlineQueryResultCachedMpeg4Gif',
  215. 'InlineQueryResultCachedPhoto',
  216. 'InlineQueryResultCachedSticker',
  217. 'InlineQueryResultCachedVideo',
  218. 'InlineQueryResultCachedVoice',
  219. 'InlineQueryResultArticle',
  220. 'InlineQueryResultAudio',
  221. 'InlineQueryResultContact',
  222. 'InlineQueryResultGame',
  223. 'InlineQueryResultDocument',
  224. 'InlineQueryResultGif',
  225. 'InlineQueryResultLocation',
  226. 'InlineQueryResultMpeg4Gif',
  227. 'InlineQueryResultPhoto',
  228. 'InlineQueryResultVenue',
  229. 'InlineQueryResultVideo'):
  230. raise TypeError(f"Unknown InlineQueryResult type: `{type}`.")
  231. super().__init__(self)
  232. self['type'] = type
  233. for key, value in kwargs.items():
  234. self[key] = value
  235. class MaskPosition(dict):
  236. """This object describes the position on faces where a mask should be placed by default."""
  237. def __init__(self, point: str, x_shift: float, y_shift: float, scale: float):
  238. """This object describes the position on faces where a mask should be placed by default.
  239. @param point: The part of the face relative to which the mask should
  240. be placed. One of “forehead”, “eyes”, “mouth”, or “chin”.
  241. @param x_shift: Shift by X-axis measured in widths of the mask scaled
  242. to the face size, from left to right. For example, choosing -1.0
  243. will place mask just to the left of the default mask position.
  244. @param y_shift: Shift by Y-axis measured in heights of the mask scaled
  245. to the face size, from top to bottom. For example, 1.0 will place
  246. the mask just below the default mask position.
  247. @param scale: Mask scaling coefficient.
  248. For example, 2.0 means double size.
  249. """
  250. super().__init__(self)
  251. self['point'] = point
  252. self['x_shift'] = x_shift
  253. self['y_shift'] = y_shift
  254. self['scale'] = scale
  255. class InputSticker(dict):
  256. """This object describes a sticker to be added to a sticker set."""
  257. def __init__(self, sticker: Union[str, dict, IO], emoji_list: List[str],
  258. mask_position: Union['MaskPosition', None] = None,
  259. keywords: Union[List[str], None] = None):
  260. """This object describes a sticker to be added to a sticker set.
  261. @param sticker: The added sticker. Pass a file_id as a String to send
  262. a file that already exists on the Telegram servers,
  263. pass an HTTP URL as a String for Telegram to get a file from the
  264. Internet, upload a new one using multipart/form-data,
  265. or pass “attach://<file_attach_name>” to upload a new one using
  266. multipart/form-data under <file_attach_name> name.
  267. Animated and video stickers can't be uploaded via HTTP URL.
  268. More information on Sending Files: https://core.telegram.org/bots/api#sending-files
  269. @param emoji_list: List of 1-20 emoji associated with the sticker
  270. @param mask_position: Optional. Position where the mask should be
  271. placed on faces. For “mask” stickers only.
  272. @param keywords: Optional. List of 0-20 search keywords for the sticker
  273. with total length of up to 64 characters.
  274. For “regular” and “custom_emoji” stickers only.
  275. """
  276. super().__init__(self)
  277. self['sticker'] = sticker
  278. self['emoji_list'] = emoji_list
  279. self['mask_position'] = mask_position
  280. self['keywords'] = keywords
  281. class InlineQueryResultsButton(dict):
  282. """Button to be shown above inline query results."""
  283. def __init__(self,
  284. text: str = None,
  285. web_app: 'WebAppInfo' = None,
  286. start_parameter: str = None):
  287. super().__init__(self)
  288. if sum(1 for e in (text, web_app, start_parameter) if e) != 1:
  289. logging.error("You must provide exactly one parameter (`text` "
  290. "or `web_app` or `start_parameter`).")
  291. return
  292. self['text'] = text
  293. self['web_app'] = web_app
  294. self['start_parameter'] = start_parameter
  295. return
  296. # This class needs to mirror Telegram API, so camelCase method are needed
  297. # noinspection PyPep8Naming
  298. class TelegramBot:
  299. """Provide python method having the same signature as Telegram API methods.
  300. All mirrored methods are camelCase.
  301. """
  302. _loop = None
  303. app = aiohttp.web.Application()
  304. sessions_timeouts = {
  305. 'getUpdates': dict(
  306. timeout=35,
  307. close=False
  308. ),
  309. 'sendMessage': dict(
  310. timeout=20,
  311. close=False
  312. )
  313. }
  314. _absolute_cooldown_timedelta = datetime.timedelta(seconds=1 / 30)
  315. _per_chat_cooldown_timedelta = datetime.timedelta(seconds=1)
  316. _allowed_messages_per_group_per_minute = 20
  317. def __init__(self, token):
  318. """Set bot token and store HTTP sessions."""
  319. if self.loop is None:
  320. self.__class__._loop = asyncio.new_event_loop()
  321. asyncio.set_event_loop(self.loop)
  322. self._token = token
  323. self.sessions = dict()
  324. self._flood_wait = 0
  325. # Each `telegram_id` key has a list of `datetime.datetime` as value
  326. self.last_sending_time = {
  327. 'absolute': (datetime.datetime.now()
  328. - self.absolute_cooldown_timedelta),
  329. 0: []
  330. }
  331. @property
  332. def loop(self):
  333. """Telegram API bot token."""
  334. return self.__class__._loop
  335. @property
  336. def token(self):
  337. """Telegram API bot token."""
  338. return self._token
  339. @property
  340. def flood_wait(self):
  341. """Seconds to wait before next API requests."""
  342. return self._flood_wait
  343. @property
  344. def absolute_cooldown_timedelta(self):
  345. """Return time delta to wait between messages (any chat).
  346. Return class value (all bots have the same limits).
  347. """
  348. return self.__class__._absolute_cooldown_timedelta
  349. @property
  350. def per_chat_cooldown_timedelta(self):
  351. """Return time delta to wait between messages in a chat.
  352. Return class value (all bots have the same limits).
  353. """
  354. return self.__class__._per_chat_cooldown_timedelta
  355. @property
  356. def longest_cooldown_timedelta(self):
  357. """Return the longest cooldown timedelta.
  358. Updates sent more than `longest_cooldown_timedelta` ago will be
  359. forgotten.
  360. """
  361. return datetime.timedelta(minutes=1)
  362. @property
  363. def allowed_messages_per_group_per_minute(self):
  364. """Return maximum number of messages allowed in a group per minute.
  365. Group, supergroup and channels are considered.
  366. Return class value (all bots have the same limits).
  367. """
  368. return self.__class__._allowed_messages_per_group_per_minute
  369. @staticmethod
  370. def check_telegram_api_json(response):
  371. """Take a json Telegram response, check it and return its content.
  372. Example of well-formed json Telegram responses:
  373. {
  374. "ok": False,
  375. "error_code": 401,
  376. "description": "Unauthorized"
  377. }
  378. {
  379. "ok": True,
  380. "result": ...
  381. }
  382. """
  383. assert 'ok' in response, (
  384. "All Telegram API responses have an `ok` field."
  385. )
  386. if not response['ok']:
  387. raise TelegramError(**response)
  388. return response['result']
  389. @staticmethod
  390. def adapt_parameters(parameters, exclude=None):
  391. """Build an aiohttp.FormData object from given `parameters`.
  392. Exclude `self`, empty values and parameters in `exclude` list.
  393. Cast integers to string to avoid TypeError during json serialization.
  394. """
  395. if exclude is None:
  396. exclude = []
  397. exclude += ['self', 'kwargs']
  398. # quote_fields=False, otherwise some file names cause troubles
  399. data = aiohttp.FormData(quote_fields=False)
  400. for key, value in parameters.items():
  401. if not (key in exclude or value is None):
  402. if (type(value) in (int, list,)
  403. or (type(value) is dict and 'file' not in value)):
  404. value = json.dumps(value, separators=(',', ':'))
  405. data.add_field(key, value)
  406. return data
  407. @staticmethod
  408. def prepare_file_object(file: Union[str, IO, dict, None]
  409. ) -> Union[str, Dict[str, IO], None]:
  410. """If `file` is a valid file path, return a dict for multipart/form-data.
  411. Other valid file identifiers are URLs and Telegram `file_id`s.
  412. """
  413. if type(file) is str and os.path.isfile(file):
  414. try:
  415. file = open(file, 'r')
  416. except FileNotFoundError as e:
  417. logging.error(f"{e}")
  418. file = None
  419. if isinstance(file, io.IOBase):
  420. file = dict(file=file)
  421. return file
  422. def get_session(self, api_method):
  423. """According to API method, return proper session and information.
  424. Return a tuple (session, session_must_be_closed)
  425. session : aiohttp.ClientSession
  426. Client session with proper timeout
  427. session_must_be_closed : bool
  428. True if session must be closed after being used once
  429. """
  430. cls = self.__class__
  431. if api_method in cls.sessions_timeouts:
  432. if api_method not in self.sessions:
  433. self.sessions[api_method] = aiohttp.ClientSession(
  434. timeout=aiohttp.ClientTimeout(
  435. total=cls.sessions_timeouts[api_method]['timeout']
  436. )
  437. )
  438. session = self.sessions[api_method]
  439. session_must_be_closed = cls.sessions_timeouts[api_method]['close']
  440. else:
  441. session = aiohttp.ClientSession(
  442. timeout=aiohttp.ClientTimeout(total=None)
  443. )
  444. session_must_be_closed = True
  445. return session, session_must_be_closed
  446. def set_flood_wait(self, flood_wait):
  447. """Wait `flood_wait` seconds before next request."""
  448. self._flood_wait = flood_wait
  449. def make_input_sticker(self,
  450. sticker: Union[dict, str, IO],
  451. emoji_list: Union[List[str], str],
  452. mask_position: Union[MaskPosition, None] = None,
  453. keywords: Union[List[str], None] = None) -> InputSticker:
  454. if isinstance(emoji_list, str):
  455. emoji_list = [c for c in emoji_list]
  456. if isinstance(keywords, str):
  457. keywords = [w for w in keywords]
  458. if isinstance(sticker, str) and os.path.isfile(sticker):
  459. sticker = self.prepare_file_object(sticker)
  460. return InputSticker(sticker=sticker, emoji_list=emoji_list,
  461. mask_position=mask_position, keywords=keywords)
  462. async def prevent_flooding(self, chat_id):
  463. """Await until request may be sent safely.
  464. Telegram flood control won't allow too many API requests in a small
  465. period.
  466. Exact limits are unknown, but less than 30 total private chat messages
  467. per second, less than 1 private message per chat and less than 20
  468. group chat messages per chat per minute should be safe.
  469. """
  470. now = datetime.datetime.now
  471. if type(chat_id) is int and chat_id > 0:
  472. while (
  473. now() < (
  474. self.last_sending_time['absolute']
  475. + self.absolute_cooldown_timedelta
  476. )
  477. ) or (
  478. chat_id in self.last_sending_time
  479. and (
  480. now() < (
  481. self.last_sending_time[chat_id]
  482. + self.per_chat_cooldown_timedelta
  483. )
  484. )
  485. ):
  486. await asyncio.sleep(
  487. self.absolute_cooldown_timedelta.seconds
  488. )
  489. self.last_sending_time[chat_id] = now()
  490. else:
  491. while (
  492. now() < (
  493. self.last_sending_time['absolute']
  494. + self.absolute_cooldown_timedelta
  495. )
  496. ) or (
  497. chat_id in self.last_sending_time
  498. and len(
  499. [
  500. sending_datetime
  501. for sending_datetime in self.last_sending_time[chat_id]
  502. if sending_datetime >= (
  503. now()
  504. - datetime.timedelta(minutes=1)
  505. )
  506. ]
  507. ) >= self.allowed_messages_per_group_per_minute
  508. ) or (
  509. chat_id in self.last_sending_time
  510. and len(self.last_sending_time[chat_id]) > 0
  511. and now() < (
  512. self.last_sending_time[chat_id][-1]
  513. + self.per_chat_cooldown_timedelta
  514. )
  515. ):
  516. await asyncio.sleep(0.5)
  517. if chat_id not in self.last_sending_time:
  518. self.last_sending_time[chat_id] = []
  519. self.last_sending_time[chat_id].append(now())
  520. self.last_sending_time[chat_id] = [
  521. sending_datetime
  522. for sending_datetime in self.last_sending_time[chat_id]
  523. if sending_datetime >= (now()
  524. - self.longest_cooldown_timedelta)
  525. ]
  526. self.last_sending_time['absolute'] = now()
  527. return
  528. async def api_request(self, method, parameters=None, exclude=None):
  529. """Return the result of a Telegram bot API request, or an Exception.
  530. Opened sessions will be used more than one time (if appropriate) and
  531. will be closed on `Bot.app.cleanup`.
  532. Result may be a Telegram API json response, None, or Exception.
  533. """
  534. if exclude is None:
  535. exclude = []
  536. if parameters is None:
  537. parameters = {}
  538. response_object = None
  539. session, session_must_be_closed = self.get_session(method)
  540. # Prevent Telegram flood control for all methods having a `chat_id`
  541. if 'chat_id' in parameters:
  542. await self.prevent_flooding(parameters['chat_id'])
  543. parameters = self.adapt_parameters(parameters, exclude=exclude)
  544. try:
  545. async with session.post("https://api.telegram.org/bot"
  546. f"{self.token}/{method}",
  547. data=parameters) as response:
  548. try:
  549. response_object = self.check_telegram_api_json(
  550. await response.json() # Telegram returns json objects
  551. )
  552. except TelegramError as e:
  553. logging.error(f"API error response - {e}")
  554. if e.code == 420: # Flood error!
  555. try:
  556. flood_wait = int(
  557. e.description.split('_')[-1]
  558. ) + 30
  559. except Exception as e:
  560. logging.error(f"{e}")
  561. flood_wait = 5 * 60
  562. logging.critical(
  563. "Telegram antiflood control triggered!\n"
  564. f"Wait {flood_wait} seconds before making another "
  565. "request"
  566. )
  567. self.set_flood_wait(flood_wait)
  568. response_object = e
  569. except Exception as e:
  570. logging.error(f"{e}", exc_info=True)
  571. response_object = e
  572. except asyncio.TimeoutError as e:
  573. logging.info(f"{e}: {method} API call timed out")
  574. except Exception as e:
  575. logging.info(f"Unexpected exception:\n{e}")
  576. response_object = e
  577. finally:
  578. if session_must_be_closed and not session.closed:
  579. await session.close()
  580. return response_object
  581. async def getMe(self):
  582. """Get basic information about the bot in form of a User object.
  583. Useful to test `self.token`.
  584. See https://core.telegram.org/bots/api#getme for details.
  585. """
  586. return await self.api_request(
  587. 'getMe',
  588. )
  589. async def getUpdates(self, offset: int = None,
  590. limit: int = None,
  591. timeout: int = None,
  592. allowed_updates: List[str] = None):
  593. """Get a list of updates starting from `offset`.
  594. If there are no updates, keep the request hanging until `timeout`.
  595. If there are more than `limit` updates, retrieve them in packs of
  596. `limit`.
  597. Allowed update types (empty list to allow all).
  598. See https://core.telegram.org/bots/api#getupdates for details.
  599. """
  600. return await self.api_request(
  601. method='getUpdates',
  602. parameters=locals()
  603. )
  604. async def setWebhook(self, url: str,
  605. certificate: Union[str, IO] = None,
  606. ip_address: str = None,
  607. max_connections: int = None,
  608. allowed_updates: List[str] = None,
  609. drop_pending_updates: bool = None,
  610. secret_token: str = None):
  611. """Set or remove a webhook. Telegram will post to `url` new updates.
  612. See https://core.telegram.org/bots/api#setwebhook for details.
  613. Notes:
  614. 1. You will not be able to receive updates using getUpdates for as
  615. long as an outgoing webhook is set up.
  616. 2. To use a self-signed certificate, you need to upload your public
  617. key certificate using certificate parameter.
  618. Please upload as InputFile, sending a String will not work.
  619. 3. Ports currently supported for webhooks: 443, 80, 88, 8443.
  620. """
  621. certificate = self.prepare_file_object(certificate)
  622. result = await self.api_request(
  623. 'setWebhook',
  624. parameters=locals()
  625. )
  626. if type(certificate) is dict: # Close certificate file, if it was open
  627. certificate['file'].close()
  628. return result
  629. async def deleteWebhook(self, drop_pending_updates: bool = None):
  630. """Remove webhook integration and switch back to getUpdate.
  631. See https://core.telegram.org/bots/api#deletewebhook for details.
  632. """
  633. return await self.api_request(
  634. 'deleteWebhook',
  635. parameters=locals()
  636. )
  637. async def getWebhookInfo(self):
  638. """Get current webhook status.
  639. See https://core.telegram.org/bots/api#getwebhookinfo for details.
  640. """
  641. return await self.api_request(
  642. 'getWebhookInfo',
  643. )
  644. async def sendMessage(self, chat_id: Union[int, str],
  645. text: str,
  646. message_thread_id: int = None,
  647. parse_mode: str = None,
  648. entities: List[dict] = None,
  649. disable_web_page_preview: bool = None,
  650. disable_notification: bool = None,
  651. protect_content: bool = None,
  652. reply_to_message_id: int = None,
  653. allow_sending_without_reply: bool = None,
  654. reply_markup=None):
  655. """Send a text message. On success, return it.
  656. See https://core.telegram.org/bots/api#sendmessage for details.
  657. """
  658. return await self.api_request(
  659. 'sendMessage',
  660. parameters=locals()
  661. )
  662. async def forwardMessage(self, chat_id: Union[int, str],
  663. from_chat_id: Union[int, str],
  664. message_id: int,
  665. message_thread_id: int = None,
  666. protect_content: bool = None,
  667. disable_notification: bool = None):
  668. """Forward a message.
  669. See https://core.telegram.org/bots/api#forwardmessage for details.
  670. """
  671. return await self.api_request(
  672. 'forwardMessage',
  673. parameters=locals()
  674. )
  675. async def sendPhoto(self, chat_id: Union[int, str], photo,
  676. caption: str = None,
  677. parse_mode: str = None,
  678. caption_entities: List[dict] = None,
  679. message_thread_id: int = None,
  680. protect_content: bool = None,
  681. disable_notification: bool = None,
  682. reply_to_message_id: int = None,
  683. allow_sending_without_reply: bool = None,
  684. has_spoiler: bool = None,
  685. reply_markup=None):
  686. """Send a photo from file_id, HTTP url or file.
  687. See https://core.telegram.org/bots/api#sendphoto for details.
  688. """
  689. return await self.api_request(
  690. 'sendPhoto',
  691. parameters=locals()
  692. )
  693. async def sendAudio(self, chat_id: Union[int, str], audio,
  694. caption: str = None,
  695. parse_mode: str = None,
  696. caption_entities: List[dict] = None,
  697. duration: int = None,
  698. performer: str = None,
  699. title: str = None,
  700. thumbnail=None,
  701. disable_notification: bool = None,
  702. reply_to_message_id: int = None,
  703. allow_sending_without_reply: bool = None,
  704. message_thread_id: int = None,
  705. protect_content: bool = None,
  706. reply_markup=None,
  707. **kwargs):
  708. """Send an audio file from file_id, HTTP url or file.
  709. See https://core.telegram.org/bots/api#sendaudio for details.
  710. """
  711. if 'thumb' in kwargs:
  712. thumbnail = kwargs['thumb']
  713. logging.error("DEPRECATION WARNING: `thumb` parameter of function"
  714. "`sendAudio` has been deprecated since Bot API 6.6. "
  715. "Use `thumbnail` instead.")
  716. return await self.api_request(
  717. 'sendAudio',
  718. parameters=locals()
  719. )
  720. async def sendDocument(self, chat_id: Union[int, str], document,
  721. thumbnail=None,
  722. caption: str = None,
  723. parse_mode: str = None,
  724. caption_entities: List[dict] = None,
  725. disable_content_type_detection: bool = None,
  726. disable_notification: bool = None,
  727. reply_to_message_id: int = None,
  728. allow_sending_without_reply: bool = None,
  729. message_thread_id: int = None,
  730. protect_content: bool = None,
  731. reply_markup=None,
  732. **kwargs):
  733. """Send a document from file_id, HTTP url or file.
  734. See https://core.telegram.org/bots/api#senddocument for details.
  735. """
  736. if 'thumb' in kwargs:
  737. thumbnail = kwargs['thumb']
  738. logging.error("DEPRECATION WARNING: `thumb` parameter of function"
  739. "`sendDocument` has been deprecated since Bot API 6.6. "
  740. "Use `thumbnail` instead.")
  741. return await self.api_request(
  742. 'sendDocument',
  743. parameters=locals()
  744. )
  745. async def sendVideo(self, chat_id: Union[int, str], video,
  746. duration: int = None,
  747. width: int = None,
  748. height: int = None,
  749. thumbnail=None,
  750. caption: str = None,
  751. parse_mode: str = None,
  752. caption_entities: List[dict] = None,
  753. supports_streaming: bool = None,
  754. disable_notification: bool = None,
  755. reply_to_message_id: int = None,
  756. allow_sending_without_reply: bool = None,
  757. message_thread_id: int = None,
  758. protect_content: bool = None,
  759. has_spoiler: bool = None,
  760. reply_markup=None,
  761. **kwargs):
  762. """Send a video from file_id, HTTP url or file.
  763. See https://core.telegram.org/bots/api#sendvideo for details.
  764. """
  765. if 'thumb' in kwargs:
  766. thumbnail = kwargs['thumb']
  767. logging.error("DEPRECATION WARNING: `thumb` parameter of function"
  768. "`sendVideo` has been deprecated since Bot API 6.6. "
  769. "Use `thumbnail` instead.")
  770. return await self.api_request(
  771. 'sendVideo',
  772. parameters=locals()
  773. )
  774. async def sendAnimation(self, chat_id: Union[int, str], animation,
  775. duration: int = None,
  776. width: int = None,
  777. height: int = None,
  778. thumbnail=None,
  779. caption: str = None,
  780. parse_mode: str = None,
  781. caption_entities: List[dict] = None,
  782. disable_notification: bool = None,
  783. reply_to_message_id: int = None,
  784. allow_sending_without_reply: bool = None,
  785. message_thread_id: int = None,
  786. protect_content: bool = None,
  787. has_spoiler: bool = None,
  788. reply_markup=None,
  789. **kwargs):
  790. """Send animation files (GIF or H.264/MPEG-4 AVC video without sound).
  791. See https://core.telegram.org/bots/api#sendanimation for details.
  792. """
  793. if 'thumb' in kwargs:
  794. thumbnail = kwargs['thumb']
  795. logging.error("DEPRECATION WARNING: `thumb` parameter of function"
  796. "`sendAnimation` has been deprecated since Bot API 6.6. "
  797. "Use `thumbnail` instead.")
  798. return await self.api_request(
  799. 'sendAnimation',
  800. parameters=locals()
  801. )
  802. async def sendVoice(self, chat_id: Union[int, str], voice,
  803. caption: str = None,
  804. parse_mode: str = None,
  805. caption_entities: List[dict] = None,
  806. duration: int = None,
  807. disable_notification: bool = None,
  808. reply_to_message_id: int = None,
  809. allow_sending_without_reply: bool = None,
  810. message_thread_id: int = None,
  811. protect_content: bool = None,
  812. reply_markup=None):
  813. """Send an audio file to be displayed as playable voice message.
  814. `voice` must be in an .ogg file encoded with OPUS.
  815. See https://core.telegram.org/bots/api#sendvoice for details.
  816. """
  817. return await self.api_request(
  818. 'sendVoice',
  819. parameters=locals()
  820. )
  821. async def sendVideoNote(self, chat_id: Union[int, str], video_note,
  822. duration: int = None,
  823. length: int = None,
  824. thumbnail=None,
  825. disable_notification: bool = None,
  826. reply_to_message_id: int = None,
  827. allow_sending_without_reply: bool = None,
  828. message_thread_id: int = None,
  829. protect_content: bool = None,
  830. reply_markup=None,
  831. **kwargs):
  832. """Send a rounded square mp4 video message of up to 1 minute long.
  833. See https://core.telegram.org/bots/api#sendvideonote for details.
  834. """
  835. if 'thumb' in kwargs:
  836. thumbnail = kwargs['thumb']
  837. logging.error("DEPRECATION WARNING: `thumb` parameter of function"
  838. "`sendVideoNote` has been deprecated since Bot API 6.6. "
  839. "Use `thumbnail` instead.")
  840. return await self.api_request(
  841. 'sendVideoNote',
  842. parameters=locals()
  843. )
  844. async def sendMediaGroup(self, chat_id: Union[int, str], media: list,
  845. disable_notification: bool = None,
  846. reply_to_message_id: int = None,
  847. message_thread_id: int = None,
  848. protect_content: bool = None,
  849. allow_sending_without_reply: bool = None):
  850. """Send a group of photos or videos as an album.
  851. `media` must be a list of `InputMediaPhoto` and/or `InputMediaVideo`
  852. objects.
  853. See https://core.telegram.org/bots/api#sendmediagroup for details.
  854. """
  855. return await self.api_request(
  856. 'sendMediaGroup',
  857. parameters=locals()
  858. )
  859. async def sendLocation(self, chat_id: Union[int, str],
  860. latitude: float, longitude: float,
  861. horizontal_accuracy: float = None,
  862. live_period=None,
  863. heading: int = None,
  864. proximity_alert_radius: int = None,
  865. disable_notification: bool = None,
  866. reply_to_message_id: int = None,
  867. allow_sending_without_reply: bool = None,
  868. message_thread_id: int = None,
  869. protect_content: bool = None,
  870. reply_markup=None):
  871. """Send a point on the map. May be kept updated for a `live_period`.
  872. See https://core.telegram.org/bots/api#sendlocation for details.
  873. """
  874. if horizontal_accuracy: # Horizontal accuracy: 0-1500 m [float].
  875. horizontal_accuracy = max(0.0, min(horizontal_accuracy, 1500.0))
  876. if live_period:
  877. live_period = max(60, min(live_period, 86400))
  878. if heading: # Direction in which the user is moving, 1-360°
  879. heading = max(1, min(heading, 360))
  880. if proximity_alert_radius: # Distance 1-100000 m
  881. proximity_alert_radius = max(1, min(proximity_alert_radius, 100000))
  882. return await self.api_request(
  883. 'sendLocation',
  884. parameters=locals()
  885. )
  886. async def editMessageLiveLocation(self, latitude: float, longitude: float,
  887. chat_id: Union[int, str] = None,
  888. message_id: int = None,
  889. inline_message_id: str = None,
  890. horizontal_accuracy: float = None,
  891. heading: int = None,
  892. proximity_alert_radius: int = None,
  893. reply_markup=None):
  894. """Edit live location messages.
  895. A location can be edited until its live_period expires or editing is
  896. explicitly disabled by a call to stopMessageLiveLocation.
  897. The message to be edited may be identified through `inline_message_id`
  898. OR the couple (`chat_id`, `message_id`).
  899. See https://core.telegram.org/bots/api#editmessagelivelocation
  900. for details.
  901. """
  902. if inline_message_id is None and (chat_id is None or message_id is None):
  903. logging.error("Invalid target chat!")
  904. if horizontal_accuracy: # Horizontal accuracy: 0-1500 m [float].
  905. horizontal_accuracy = max(0.0, min(horizontal_accuracy, 1500.0))
  906. if heading: # Direction in which the user is moving, 1-360°
  907. heading = max(1, min(heading, 360))
  908. if proximity_alert_radius: # Distance 1-100000 m
  909. proximity_alert_radius = max(1, min(proximity_alert_radius, 100000))
  910. return await self.api_request(
  911. 'editMessageLiveLocation',
  912. parameters=locals()
  913. )
  914. async def stopMessageLiveLocation(self,
  915. chat_id: Union[int, str] = None,
  916. message_id: int = None,
  917. inline_message_id: int = None,
  918. reply_markup=None):
  919. """Stop updating a live location message before live_period expires.
  920. The position to be stopped may be identified through
  921. `inline_message_id` OR the couple (`chat_id`, `message_id`).
  922. `reply_markup` type may be only `InlineKeyboardMarkup`.
  923. See https://core.telegram.org/bots/api#stopmessagelivelocation
  924. for details.
  925. """
  926. return await self.api_request(
  927. 'stopMessageLiveLocation',
  928. parameters=locals()
  929. )
  930. async def sendVenue(self, chat_id: Union[int, str],
  931. latitude: float, longitude: float,
  932. title: str, address: str,
  933. foursquare_id: str = None,
  934. foursquare_type: str = None,
  935. google_place_id: str = None,
  936. google_place_type: str = None,
  937. disable_notification: bool = None,
  938. reply_to_message_id: int = None,
  939. allow_sending_without_reply: bool = None,
  940. message_thread_id: int = None,
  941. protect_content: bool = None,
  942. reply_markup=None):
  943. """Send information about a venue.
  944. Integrated with FourSquare.
  945. See https://core.telegram.org/bots/api#sendvenue for details.
  946. """
  947. return await self.api_request(
  948. 'sendVenue',
  949. parameters=locals()
  950. )
  951. async def sendContact(self, chat_id: Union[int, str],
  952. phone_number: str,
  953. first_name: str,
  954. last_name: str = None,
  955. vcard: str = None,
  956. disable_notification: bool = None,
  957. reply_to_message_id: int = None,
  958. allow_sending_without_reply: bool = None,
  959. message_thread_id: int = None,
  960. protect_content: bool = None,
  961. reply_markup=None):
  962. """Send a phone contact.
  963. See https://core.telegram.org/bots/api#sendcontact for details.
  964. """
  965. return await self.api_request(
  966. 'sendContact',
  967. parameters=locals()
  968. )
  969. async def sendPoll(self,
  970. chat_id: Union[int, str],
  971. question: str,
  972. options: List[str],
  973. is_anonymous: bool = True,
  974. type_: str = 'regular',
  975. allows_multiple_answers: bool = False,
  976. correct_option_id: int = None,
  977. explanation: str = None,
  978. explanation_parse_mode: str = None,
  979. explanation_entities: List[dict] = None,
  980. open_period: int = None,
  981. close_date: Union[int, datetime.datetime] = None,
  982. is_closed: bool = None,
  983. disable_notification: bool = None,
  984. allow_sending_without_reply: bool = None,
  985. reply_to_message_id: int = None,
  986. message_thread_id: int = None,
  987. protect_content: bool = None,
  988. reply_markup=None):
  989. """Send a native poll in a group, a supergroup or channel.
  990. See https://core.telegram.org/bots/api#sendpoll for details.
  991. close_date: Unix timestamp; 5-600 seconds from now.
  992. open_period (overwrites close_date): seconds (integer), 5-600.
  993. """
  994. if open_period is not None:
  995. close_date = None
  996. open_period = min(max(5, open_period), 600)
  997. elif isinstance(close_date, datetime.datetime):
  998. now = datetime.datetime.now()
  999. close_date = min(
  1000. max(
  1001. now + datetime.timedelta(seconds=5),
  1002. close_date
  1003. ), now + datetime.timedelta(seconds=600)
  1004. )
  1005. close_date = int(close_date.timestamp())
  1006. # To avoid shadowing `type`, this workaround is required
  1007. parameters = locals().copy()
  1008. parameters['type'] = parameters['type_']
  1009. del parameters['type_']
  1010. return await self.api_request(
  1011. 'sendPoll',
  1012. parameters=parameters
  1013. )
  1014. async def sendChatAction(self, chat_id: Union[int, str], action,
  1015. message_thread_id: int = None):
  1016. """Fake a typing status or similar.
  1017. See https://core.telegram.org/bots/api#sendchataction for details.
  1018. """
  1019. return await self.api_request(
  1020. 'sendChatAction',
  1021. parameters=locals()
  1022. )
  1023. async def getUserProfilePhotos(self, user_id,
  1024. offset=None,
  1025. limit=None):
  1026. """Get a list of profile pictures for a user.
  1027. See https://core.telegram.org/bots/api#getuserprofilephotos
  1028. for details.
  1029. """
  1030. return await self.api_request(
  1031. 'getUserProfilePhotos',
  1032. parameters=locals()
  1033. )
  1034. async def getFile(self, file_id):
  1035. """Get basic info about a file and prepare it for downloading.
  1036. For the moment, bots can download files of up to
  1037. 20MB in size.
  1038. On success, a File object is returned. The file can then be downloaded
  1039. via the link https://api.telegram.org/file/bot<token>/<file_path>,
  1040. where <file_path> is taken from the response.
  1041. See https://core.telegram.org/bots/api#getfile for details.
  1042. """
  1043. return await self.api_request(
  1044. 'getFile',
  1045. parameters=locals()
  1046. )
  1047. async def kickChatMember(self, chat_id: Union[int, str], user_id,
  1048. until_date=None):
  1049. """Kick a user from a group, a supergroup or a channel.
  1050. In the case of supergroups and channels, the user will not be able to
  1051. return to the group on their own using invite links, etc., unless
  1052. unbanned first.
  1053. Note: In regular groups (non-supergroups), this method will only work
  1054. if the ‘All Members Are Admins’ setting is off in the target group.
  1055. Otherwise, members may only be removed by the group's creator or by
  1056. the member that added them.
  1057. See https://core.telegram.org/bots/api#kickchatmember for details.
  1058. """
  1059. return await self.api_request(
  1060. 'kickChatMember',
  1061. parameters=locals()
  1062. )
  1063. async def unbanChatMember(self, chat_id: Union[int, str], user_id: int,
  1064. only_if_banned: bool = True):
  1065. """Unban a previously kicked user in a supergroup or channel.
  1066. The user will not return to the group or channel automatically, but
  1067. will be able to join via link, etc.
  1068. The bot must be an administrator for this to work.
  1069. Return True on success.
  1070. See https://core.telegram.org/bots/api#unbanchatmember for details.
  1071. If `only_if_banned` is set to False, regular users will be kicked from
  1072. chat upon call of this method on them.
  1073. """
  1074. return await self.api_request(
  1075. 'unbanChatMember',
  1076. parameters=locals()
  1077. )
  1078. async def restrictChatMember(self, chat_id: Union[int, str], user_id: int,
  1079. permissions: Dict[str, bool],
  1080. use_independent_chat_permissions: bool = None,
  1081. until_date: Union[datetime.datetime, int] = None):
  1082. """Restrict a user in a supergroup.
  1083. The bot must be an administrator in the supergroup for this to work
  1084. and must have the appropriate admin rights.
  1085. Pass True for all boolean parameters to lift restrictions from a
  1086. user.
  1087. Return True on success.
  1088. See https://core.telegram.org/bots/api#restrictchatmember for details.
  1089. until_date must be a Unix timestamp.
  1090. """
  1091. if isinstance(until_date, datetime.datetime):
  1092. until_date = int(until_date.timestamp())
  1093. return await self.api_request(
  1094. 'restrictChatMember',
  1095. parameters=locals()
  1096. )
  1097. async def promoteChatMember(self, chat_id: Union[int, str], user_id: int,
  1098. is_anonymous: bool = None,
  1099. can_change_info: bool = None,
  1100. can_post_messages: bool = None,
  1101. can_edit_messages: bool = None,
  1102. can_delete_messages: bool = None,
  1103. can_invite_users: bool = None,
  1104. can_restrict_members: bool = None,
  1105. can_pin_messages: bool = None,
  1106. can_promote_members: bool = None,
  1107. can_manage_topics: bool = None,
  1108. can_manage_chat: bool = None,
  1109. can_manage_video_chats: bool = None):
  1110. """Promote or demote a user in a supergroup or a channel.
  1111. The bot must be an administrator in the chat for this to work and must
  1112. have the appropriate admin rights.
  1113. Pass False for all boolean parameters to demote a user.
  1114. Return True on success.
  1115. See https://core.telegram.org/bots/api#promotechatmember for details.
  1116. """
  1117. return await self.api_request(
  1118. 'promoteChatMember',
  1119. parameters=locals()
  1120. )
  1121. async def exportChatInviteLink(self, chat_id: Union[int, str]):
  1122. """Generate a new invite link for a chat and revoke any active link.
  1123. The bot must be an administrator in the chat for this to work and must
  1124. have the appropriate admin rights.
  1125. Return the new invite link as String on success.
  1126. NOTE: to get the current invite link, use `getChat` method.
  1127. See https://core.telegram.org/bots/api#exportchatinvitelink
  1128. for details.
  1129. """
  1130. return await self.api_request(
  1131. 'exportChatInviteLink',
  1132. parameters=locals()
  1133. )
  1134. async def setChatPhoto(self, chat_id: Union[int, str], photo):
  1135. """Set a new profile photo for the chat.
  1136. Photos can't be changed for private chats.
  1137. `photo` must be an input file (file_id and urls are not allowed).
  1138. The bot must be an administrator in the chat for this to work and must
  1139. have the appropriate admin rights.
  1140. Return True on success.
  1141. See https://core.telegram.org/bots/api#setchatphoto for details.
  1142. """
  1143. return await self.api_request(
  1144. 'setChatPhoto',
  1145. parameters=locals()
  1146. )
  1147. async def deleteChatPhoto(self, chat_id: Union[int, str]):
  1148. """Delete a chat photo.
  1149. Photos can't be changed for private chats.
  1150. The bot must be an administrator in the chat for this to work and must
  1151. have the appropriate admin rights.
  1152. Return True on success.
  1153. See https://core.telegram.org/bots/api#deletechatphoto for details.
  1154. """
  1155. return await self.api_request(
  1156. 'deleteChatPhoto',
  1157. parameters=locals()
  1158. )
  1159. async def setChatTitle(self, chat_id: Union[int, str], title):
  1160. """Change the title of a chat.
  1161. Titles can't be changed for private chats.
  1162. The bot must be an administrator in the chat for this to work and must
  1163. have the appropriate admin rights.
  1164. Return True on success.
  1165. See https://core.telegram.org/bots/api#setchattitle for details.
  1166. """
  1167. return await self.api_request(
  1168. 'setChatTitle',
  1169. parameters=locals()
  1170. )
  1171. async def setChatDescription(self, chat_id: Union[int, str], description):
  1172. """Change the description of a supergroup or a channel.
  1173. The bot must be an administrator in the chat for this to work and must
  1174. have the appropriate admin rights.
  1175. Return True on success.
  1176. See https://core.telegram.org/bots/api#setchatdescription for details.
  1177. """
  1178. return await self.api_request(
  1179. 'setChatDescription',
  1180. parameters=locals()
  1181. )
  1182. async def pinChatMessage(self, chat_id: Union[int, str], message_id,
  1183. disable_notification: bool = None):
  1184. """Pin a message in a group, a supergroup, or a channel.
  1185. The bot must be an administrator in the chat for this to work and must
  1186. have the ‘can_pin_messages’ admin right in the supergroup or
  1187. ‘can_edit_messages’ admin right in the channel.
  1188. Return True on success.
  1189. See https://core.telegram.org/bots/api#pinchatmessage for details.
  1190. """
  1191. return await self.api_request(
  1192. 'pinChatMessage',
  1193. parameters=locals()
  1194. )
  1195. async def unpinChatMessage(self, chat_id: Union[int, str],
  1196. message_id: int = None):
  1197. """Unpin a message in a group, a supergroup, or a channel.
  1198. The bot must be an administrator in the chat for this to work and must
  1199. have the ‘can_pin_messages’ admin right in the supergroup or
  1200. ‘can_edit_messages’ admin right in the channel.
  1201. Return True on success.
  1202. See https://core.telegram.org/bots/api#unpinchatmessage for details.
  1203. """
  1204. return await self.api_request(
  1205. 'unpinChatMessage',
  1206. parameters=locals()
  1207. )
  1208. async def leaveChat(self, chat_id: Union[int, str]):
  1209. """Make the bot leave a group, supergroup or channel.
  1210. Return True on success.
  1211. See https://core.telegram.org/bots/api#leavechat for details.
  1212. """
  1213. return await self.api_request(
  1214. 'leaveChat',
  1215. parameters=locals()
  1216. )
  1217. async def getChat(self, chat_id: Union[int, str]):
  1218. """Get up-to-date information about the chat.
  1219. Return a Chat object on success.
  1220. See https://core.telegram.org/bots/api#getchat for details.
  1221. """
  1222. return await self.api_request(
  1223. 'getChat',
  1224. parameters=locals()
  1225. )
  1226. async def getChatAdministrators(self, chat_id: Union[int, str]):
  1227. """Get a list of administrators in a chat.
  1228. On success, return an Array of ChatMember objects that contains
  1229. information about all chat administrators except other bots.
  1230. If the chat is a group or a supergroup and no administrators were
  1231. appointed, only the creator will be returned.
  1232. See https://core.telegram.org/bots/api#getchatadministrators
  1233. for details.
  1234. """
  1235. return await self.api_request(
  1236. 'getChatAdministrators',
  1237. parameters=locals()
  1238. )
  1239. async def getChatMembersCount(self, chat_id: Union[int, str]):
  1240. """Get the number of members in a chat.
  1241. Returns Int on success.
  1242. See https://core.telegram.org/bots/api#getchatmemberscount for details.
  1243. """
  1244. return await self.api_request(
  1245. 'getChatMembersCount',
  1246. parameters=locals()
  1247. )
  1248. async def getChatMember(self, chat_id: Union[int, str], user_id):
  1249. """Get information about a member of a chat.
  1250. Returns a ChatMember object on success.
  1251. See https://core.telegram.org/bots/api#getchatmember for details.
  1252. """
  1253. return await self.api_request(
  1254. 'getChatMember',
  1255. parameters=locals()
  1256. )
  1257. async def setChatStickerSet(self, chat_id: Union[int, str], sticker_set_name):
  1258. """Set a new group sticker set for a supergroup.
  1259. The bot must be an administrator in the chat for this to work and must
  1260. have the appropriate admin rights.
  1261. Use the field `can_set_sticker_set` optionally returned in getChat
  1262. requests to check if the bot can use this method.
  1263. Returns True on success.
  1264. See https://core.telegram.org/bots/api#setchatstickerset for details.
  1265. """
  1266. return await self.api_request(
  1267. 'setChatStickerSet',
  1268. parameters=locals()
  1269. )
  1270. async def deleteChatStickerSet(self, chat_id: Union[int, str]):
  1271. """Delete a group sticker set from a supergroup.
  1272. The bot must be an administrator in the chat for this to work and must
  1273. have the appropriate admin rights.
  1274. Use the field `can_set_sticker_set` optionally returned in getChat
  1275. requests to check if the bot can use this method.
  1276. Returns True on success.
  1277. See https://core.telegram.org/bots/api#deletechatstickerset for
  1278. details.
  1279. """
  1280. return await self.api_request(
  1281. 'deleteChatStickerSet',
  1282. parameters=locals()
  1283. )
  1284. async def answerCallbackQuery(self, callback_query_id,
  1285. text=None,
  1286. show_alert=None,
  1287. url=None,
  1288. cache_time=None):
  1289. """Send answers to callback queries sent from inline keyboards.
  1290. The answer will be displayed to the user as a notification at the top
  1291. of the chat screen or as an alert.
  1292. On success, True is returned.
  1293. See https://core.telegram.org/bots/api#answercallbackquery for details.
  1294. """
  1295. return await self.api_request(
  1296. 'answerCallbackQuery',
  1297. parameters=locals()
  1298. )
  1299. async def editMessageText(self, text: str,
  1300. chat_id: Union[int, str] = None,
  1301. message_id: int = None,
  1302. inline_message_id: str = None,
  1303. parse_mode: str = None,
  1304. entities: List[dict] = None,
  1305. disable_web_page_preview: bool = None,
  1306. reply_markup=None):
  1307. """Edit text and game messages.
  1308. On success, if edited message is sent by the bot, the edited Message
  1309. is returned, otherwise True is returned.
  1310. See https://core.telegram.org/bots/api#editmessagetext for details.
  1311. """
  1312. return await self.api_request(
  1313. 'editMessageText',
  1314. parameters=locals()
  1315. )
  1316. async def editMessageCaption(self,
  1317. chat_id: Union[int, str] = None,
  1318. message_id: int = None,
  1319. inline_message_id: str = None,
  1320. caption: str = None,
  1321. parse_mode: str = None,
  1322. caption_entities: List[dict] = None,
  1323. reply_markup=None):
  1324. """Edit captions of messages.
  1325. On success, if edited message is sent by the bot, the edited Message is
  1326. returned, otherwise True is returned.
  1327. See https://core.telegram.org/bots/api#editmessagecaption for details.
  1328. """
  1329. return await self.api_request(
  1330. 'editMessageCaption',
  1331. parameters=locals()
  1332. )
  1333. async def editMessageMedia(self,
  1334. chat_id: Union[int, str] = None,
  1335. message_id: int = None,
  1336. inline_message_id: str = None,
  1337. media=None,
  1338. reply_markup=None):
  1339. """Edit animation, audio, document, photo, or video messages.
  1340. If a message is a part of a message album, then it can be edited only
  1341. to a photo or a video. Otherwise, message type can be changed
  1342. arbitrarily.
  1343. When inline message is edited, new file can't be uploaded.
  1344. Use previously uploaded file via its file_id or specify a URL.
  1345. On success, if the edited message was sent by the bot, the edited
  1346. Message is returned, otherwise True is returned.
  1347. See https://core.telegram.org/bots/api#editmessagemedia for details.
  1348. """
  1349. return await self.api_request(
  1350. 'editMessageMedia',
  1351. parameters=locals()
  1352. )
  1353. async def editMessageReplyMarkup(self,
  1354. chat_id: Union[int, str] = None,
  1355. message_id: int = None,
  1356. inline_message_id: str = None,
  1357. reply_markup=None):
  1358. """Edit only the reply markup of messages.
  1359. On success, if edited message is sent by the bot, the edited Message is
  1360. returned, otherwise True is returned.
  1361. See https://core.telegram.org/bots/api#editmessagereplymarkup for
  1362. details.
  1363. """
  1364. return await self.api_request(
  1365. 'editMessageReplyMarkup',
  1366. parameters=locals()
  1367. )
  1368. async def stopPoll(self, chat_id: Union[int, str], message_id,
  1369. reply_markup=None):
  1370. """Stop a poll which was sent by the bot.
  1371. On success, the stopped Poll with the final results is returned.
  1372. `reply_markup` type may be only `InlineKeyboardMarkup`.
  1373. See https://core.telegram.org/bots/api#stoppoll for details.
  1374. """
  1375. return await self.api_request(
  1376. 'stopPoll',
  1377. parameters=locals()
  1378. )
  1379. async def deleteMessage(self, chat_id: Union[int, str], message_id):
  1380. """Delete a message, including service messages.
  1381. - A message can only be deleted if it was sent less than 48 hours
  1382. ago.
  1383. - Bots can delete outgoing messages in private chats, groups, and
  1384. supergroups.
  1385. - Bots can delete incoming messages in private chats.
  1386. - Bots granted can_post_messages permissions can delete outgoing
  1387. messages in channels.
  1388. - If the bot is an administrator of a group, it can delete any
  1389. message there.
  1390. - If the bot has can_delete_messages permission in a supergroup or
  1391. a channel, it can delete any message there.
  1392. Returns True on success.
  1393. See https://core.telegram.org/bots/api#deletemessage for details.
  1394. """
  1395. return await self.api_request(
  1396. 'deleteMessage',
  1397. parameters=locals()
  1398. )
  1399. async def sendSticker(self, chat_id: Union[int, str],
  1400. sticker: Union[str, dict, IO],
  1401. disable_notification: bool = None,
  1402. reply_to_message_id: int = None,
  1403. allow_sending_without_reply: bool = None,
  1404. message_thread_id: int = None,
  1405. protect_content: bool = None,
  1406. emoji: str = None,
  1407. reply_markup=None):
  1408. """Send `.webp` stickers.
  1409. `sticker` must be a file path, a URL, a file handle or a dict
  1410. {"file": io_file_handle}, to allow multipart/form-data encoding.
  1411. On success, the sent Message is returned.
  1412. See https://core.telegram.org/bots/api#sendsticker for details.
  1413. """
  1414. sticker = self.prepare_file_object(sticker)
  1415. if sticker is None:
  1416. logging.error("Invalid sticker provided!")
  1417. return
  1418. result = await self.api_request(
  1419. 'sendSticker',
  1420. parameters=locals()
  1421. )
  1422. if type(sticker) is dict: # Close sticker file, if it was open
  1423. sticker['file'].close()
  1424. return result
  1425. async def getStickerSet(self, name):
  1426. """Get a sticker set.
  1427. On success, a StickerSet object is returned.
  1428. See https://core.telegram.org/bots/api#getstickerset for details.
  1429. """
  1430. return await self.api_request(
  1431. 'getStickerSet',
  1432. parameters=locals()
  1433. )
  1434. async def uploadStickerFile(self, user_id: int, sticker: Union[str, dict, IO],
  1435. sticker_format: str, **kwargs):
  1436. """Upload an image file for later use in sticker packs.
  1437. Use this method to upload a file with a sticker for later use in the
  1438. createNewStickerSet and addStickerToSet methods
  1439. (the file can be used multiple times).
  1440. `sticker` must be a file path, a file handle or a dict
  1441. {"file": io_file_handle}, to allow multipart/form-data encoding.
  1442. Returns the uploaded File on success.
  1443. See https://core.telegram.org/bots/api#uploadstickerfile for details.
  1444. """
  1445. if 'png_sticker' in kwargs:
  1446. sticker = kwargs['png_sticker']
  1447. logging.error("DEPRECATION WARNING: `png_sticker` parameter of function"
  1448. "`uploadStickerFile` has been deprecated since Bot API 6.6. "
  1449. "Use `sticker` instead.")
  1450. if sticker_format not in ("static", "animated", "video"):
  1451. logging.error(f"Unknown sticker format `{sticker_format}`.")
  1452. sticker = self.prepare_file_object(sticker)
  1453. if sticker is None:
  1454. logging.error("Invalid sticker provided!")
  1455. return
  1456. result = await self.api_request(
  1457. 'uploadStickerFile',
  1458. parameters=locals()
  1459. )
  1460. if type(sticker) is dict: # Close sticker file, if it was open
  1461. sticker['file'].close()
  1462. return result
  1463. async def createNewStickerSet(self, user_id: int, name: str, title: str,
  1464. stickers: List['InputSticker'],
  1465. sticker_format: str = 'static',
  1466. sticker_type: str = 'regular',
  1467. needs_repainting: bool = False,
  1468. **kwargs):
  1469. """Create new sticker set owned by a user.
  1470. The bot will be able to edit the created sticker set.
  1471. Returns True on success.
  1472. See https://core.telegram.org/bots/api#createnewstickerset for details.
  1473. """
  1474. if stickers is None:
  1475. stickers = []
  1476. if 'contains_masks' in kwargs:
  1477. logging.error("Parameter `contains_masks` of method "
  1478. "`createNewStickerSet` has been deprecated. "
  1479. "Use `sticker_type = 'mask'` instead.")
  1480. sticker_type = 'mask' if kwargs['contains_masks'] else 'regular'
  1481. for old_sticker_format in ('png_sticker', 'tgs_sticker', 'webm_sticker'):
  1482. if old_sticker_format in kwargs:
  1483. if 'emojis' not in kwargs:
  1484. logging.error(f"No `emojis` provided together with "
  1485. f"`{old_sticker_format}`. To create new "
  1486. f"sticker set with some stickers in it, use "
  1487. f"the new `stickers` parameter.")
  1488. return
  1489. logging.error(f"Parameter `{old_sticker_format}` of method "
  1490. "`createNewStickerSet` has been deprecated since"
  1491. "Bot API 6.6. "
  1492. "Use `stickers` instead.")
  1493. stickers.append(
  1494. self.make_input_sticker(
  1495. sticker=kwargs[old_sticker_format],
  1496. emoji_list=kwargs['emojis']
  1497. )
  1498. )
  1499. if sticker_type not in ('regular', 'mask', 'custom_emoji'):
  1500. raise TypeError(f"Unknown sticker type `{sticker_type}`.")
  1501. result = await self.api_request(
  1502. 'createNewStickerSet',
  1503. parameters=locals(),
  1504. exclude=['old_sticker_format']
  1505. )
  1506. return result
  1507. async def addStickerToSet(self, user_id: int, name: str,
  1508. sticker: InputSticker = None,
  1509. **kwargs):
  1510. """Add a new sticker to a set created by the bot.
  1511. Returns True on success.
  1512. See https://core.telegram.org/bots/api#addstickertoset for details.
  1513. """
  1514. for old_sticker_format in ('png_sticker', 'tgs_sticker', 'webm_sticker'):
  1515. if old_sticker_format in kwargs:
  1516. if 'emojis' not in kwargs:
  1517. logging.error(f"No `emojis` provided together with "
  1518. f"`{old_sticker_format}`.")
  1519. return
  1520. logging.error(f"Parameter `{old_sticker_format}` of method "
  1521. "`addStickerToSet` has been deprecated since"
  1522. "Bot API 6.6. "
  1523. "Use `sticker` instead.")
  1524. sticker = self.make_input_sticker(
  1525. sticker=kwargs[old_sticker_format],
  1526. emoji_list=kwargs['emojis'],
  1527. mask_position=kwargs['mask_position'] if 'mask_position' in kwargs else None
  1528. )
  1529. if sticker is None:
  1530. logging.error("Must provide a sticker of type `InputSticker` to "
  1531. "`addStickerToSet` method.")
  1532. return
  1533. result = await self.api_request(
  1534. 'addStickerToSet',
  1535. parameters=locals(),
  1536. exclude=['old_sticker_format']
  1537. )
  1538. return result
  1539. async def setStickerPositionInSet(self, sticker, position):
  1540. """Move a sticker in a set created by the bot to a specific position .
  1541. Position is 0-based.
  1542. Returns True on success.
  1543. See https://core.telegram.org/bots/api#setstickerpositioninset for
  1544. details.
  1545. """
  1546. return await self.api_request(
  1547. 'setStickerPositionInSet',
  1548. parameters=locals()
  1549. )
  1550. async def deleteStickerFromSet(self, sticker):
  1551. """Delete a sticker from a set created by the bot.
  1552. Returns True on success.
  1553. See https://core.telegram.org/bots/api#deletestickerfromset for
  1554. details.
  1555. """
  1556. return await self.api_request(
  1557. 'deleteStickerFromSet',
  1558. parameters=locals()
  1559. )
  1560. async def answerInlineQuery(self, inline_query_id, results,
  1561. cache_time=None,
  1562. is_personal=None,
  1563. next_offset=None,
  1564. button: Union['InlineQueryResultsButton', None] = None,
  1565. **kwargs):
  1566. """Send answers to an inline query.
  1567. On success, True is returned.
  1568. No more than 50 results per query are allowed.
  1569. See https://core.telegram.org/bots/api#answerinlinequery for details.
  1570. """
  1571. if 'switch_pm_text' in kwargs and kwargs['switch_pm_text']:
  1572. button = InlineQueryResultsButton(text=kwargs['switch_pm_text'])
  1573. if 'switch_pm_parameter' in kwargs and kwargs['switch_pm_parameter']:
  1574. button = InlineQueryResultsButton(start_parameter=kwargs['switch_pm_parameter'])
  1575. return await self.api_request(
  1576. 'answerInlineQuery',
  1577. parameters=locals()
  1578. )
  1579. async def sendInvoice(self, chat_id: int, title: str, description: str,
  1580. payload: str, provider_token: str,
  1581. start_parameter: str,
  1582. currency: str, prices: List[dict],
  1583. message_thread_id: int = None,
  1584. protect_content: bool = None,
  1585. max_tip_amount: int = None,
  1586. suggested_tip_amounts: List[int] = None,
  1587. provider_data: str = None,
  1588. photo_url: str = None,
  1589. photo_size: int = None,
  1590. photo_width: int = None,
  1591. photo_height: int = None,
  1592. need_name: bool = None,
  1593. need_phone_number: bool = None,
  1594. need_email: bool = None,
  1595. need_shipping_address: bool = None,
  1596. send_phone_number_to_provider: bool = None,
  1597. send_email_to_provider: bool = None,
  1598. is_flexible: bool = None,
  1599. disable_notification: bool = None,
  1600. reply_to_message_id: int = None,
  1601. allow_sending_without_reply: bool = None,
  1602. reply_markup=None):
  1603. """Send an invoice.
  1604. On success, the sent Message is returned.
  1605. See https://core.telegram.org/bots/api#sendinvoice for details.
  1606. """
  1607. return await self.api_request(
  1608. 'sendInvoice',
  1609. parameters=locals()
  1610. )
  1611. async def answerShippingQuery(self, shipping_query_id, ok,
  1612. shipping_options=None,
  1613. error_message=None):
  1614. """Reply to shipping queries.
  1615. On success, True is returned.
  1616. If you sent an invoice requesting a shipping address and the parameter
  1617. is_flexible was specified, the Bot API will send an Update with a
  1618. shipping_query field to the bot.
  1619. See https://core.telegram.org/bots/api#answershippingquery for details.
  1620. """
  1621. return await self.api_request(
  1622. 'answerShippingQuery',
  1623. parameters=locals()
  1624. )
  1625. async def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
  1626. error_message=None):
  1627. """Respond to pre-checkout queries.
  1628. Once the user has confirmed their payment and shipping details, the Bot
  1629. API sends the final confirmation in the form of an Update with the
  1630. field pre_checkout_query.
  1631. On success, True is returned.
  1632. Note: The Bot API must receive an answer within 10 seconds after the
  1633. pre-checkout query was sent.
  1634. See https://core.telegram.org/bots/api#answerprecheckoutquery for
  1635. details.
  1636. """
  1637. return await self.api_request(
  1638. 'answerPreCheckoutQuery',
  1639. parameters=locals()
  1640. )
  1641. async def setPassportDataErrors(self, user_id, errors):
  1642. """Refuse a Telegram Passport element with `errors`.
  1643. Inform a user that some of the Telegram Passport elements they provided
  1644. contains errors.
  1645. The user will not be able to re-submit their Passport to you until the
  1646. errors are fixed (the contents of the field for which you returned
  1647. the error must change).
  1648. Returns True on success.
  1649. Use this if the data submitted by the user doesn't satisfy the
  1650. standards your service requires for any reason.
  1651. For example, if a birthday date seems invalid, a submitted document
  1652. is blurry, a scan shows evidence of tampering, etc.
  1653. Supply some details in the error message to make sure the user knows
  1654. how to correct the issues.
  1655. See https://core.telegram.org/bots/api#setpassportdataerrors for
  1656. details.
  1657. """
  1658. return await self.api_request(
  1659. 'setPassportDataErrors',
  1660. parameters=locals()
  1661. )
  1662. async def sendGame(self, chat_id: Union[int, str], game_short_name,
  1663. message_thread_id: int = None,
  1664. protect_content: bool = None,
  1665. disable_notification: bool = None,
  1666. reply_to_message_id: int = None,
  1667. reply_markup=None,
  1668. allow_sending_without_reply: bool = None):
  1669. """Send a game.
  1670. On success, the sent Message is returned.
  1671. See https://core.telegram.org/bots/api#sendgame for
  1672. details.
  1673. """
  1674. return await self.api_request(
  1675. 'sendGame',
  1676. parameters=locals()
  1677. )
  1678. async def setGameScore(self, user_id: int, score: int,
  1679. force: bool = None,
  1680. disable_edit_message: bool = None,
  1681. chat_id: Union[int, str] = None,
  1682. message_id: int = None,
  1683. inline_message_id: str = None):
  1684. """Set the score of the specified user in a game.
  1685. On success, if the message was sent by the bot, returns the edited
  1686. Message, otherwise returns True.
  1687. Returns an error, if the new score is not greater than the user's
  1688. current score in the chat and force is False.
  1689. See https://core.telegram.org/bots/api#setgamescore for
  1690. details.
  1691. """
  1692. return await self.api_request(
  1693. 'setGameScore',
  1694. parameters=locals()
  1695. )
  1696. async def getGameHighScores(self, user_id,
  1697. chat_id: Union[int, str] = None,
  1698. message_id: int = None,
  1699. inline_message_id: str = None):
  1700. """Get data for high score tables.
  1701. Will return the score of the specified user and several of his
  1702. neighbors in a game.
  1703. On success, returns an Array of GameHighScore objects.
  1704. This method will currently return scores for the target user, plus two
  1705. of his closest neighbors on each side. Will also return the top
  1706. three users if the user and his neighbors are not among them.
  1707. Please note that this behavior is subject to change.
  1708. See https://core.telegram.org/bots/api#getgamehighscores for
  1709. details.
  1710. """
  1711. return await self.api_request(
  1712. 'getGameHighScores',
  1713. parameters=locals()
  1714. )
  1715. async def sendDice(self,
  1716. chat_id: Union[int, str] = None,
  1717. emoji: str = None,
  1718. disable_notification: bool = None,
  1719. reply_to_message_id: int = None,
  1720. allow_sending_without_reply: bool = None,
  1721. message_thread_id: int = None,
  1722. protect_content: bool = None,
  1723. reply_markup=None):
  1724. """Send a dice.
  1725. Use this method to send a dice, which will have a random value from 1
  1726. to 6.
  1727. On success, the sent Message is returned.
  1728. (Yes, we're aware of the “proper” singular of die. But it's awkward,
  1729. and we decided to help it change. One dice at a time!)
  1730. See https://core.telegram.org/bots/api#senddice for
  1731. details.
  1732. """
  1733. return await self.api_request(
  1734. 'sendDice',
  1735. parameters=locals()
  1736. )
  1737. async def setChatAdministratorCustomTitle(self,
  1738. chat_id: Union[int, str] = None,
  1739. user_id: int = None,
  1740. custom_title: str = None):
  1741. """Set a custom title for an administrator.
  1742. Use this method to set a custom title for an administrator in a
  1743. supergroup promoted by the bot.
  1744. Returns True on success.
  1745. See https://core.telegram.org/bots/api#setchatadministratorcustomtitle
  1746. for details.
  1747. """
  1748. return await self.api_request(
  1749. 'setChatAdministratorCustomTitle',
  1750. parameters=locals()
  1751. )
  1752. async def setChatPermissions(self,
  1753. chat_id: Union[int, str] = None,
  1754. permissions: Union[ChatPermissions,
  1755. dict] = None,
  1756. use_independent_chat_permissions: bool = None):
  1757. """Set default chat permissions for all members.
  1758. Use this method to set default chat permissions for all members.
  1759. The bot must be an administrator in the group or a supergroup for this
  1760. to work and must have the can_restrict_members admin rights.
  1761. Returns True on success.
  1762. See https://core.telegram.org/bots/api#setchatpermissions for details.
  1763. """
  1764. return await self.api_request(
  1765. 'setChatPermissions',
  1766. parameters=locals()
  1767. )
  1768. async def setMyCommands(self,
  1769. commands: List[Union[Command, dict]],
  1770. scope: 'BotCommandScope' = None,
  1771. language_code: str = None):
  1772. """Change the list of the bot's commands.
  1773. Use this method to change the list of the bot's commands.
  1774. Returns True on success.
  1775. See https://core.telegram.org/bots/api#setmycommands for details.
  1776. """
  1777. return await self.api_request(
  1778. 'setMyCommands',
  1779. parameters=locals()
  1780. )
  1781. async def getMyCommands(self,
  1782. scope: 'BotCommandScope' = None,
  1783. language_code: str = None):
  1784. """Get the current list of the bot's commands.
  1785. Use this method to get the current list of the bot's commands for
  1786. the given scope and user language.
  1787. Returns an Array of BotCommand objects.
  1788. If commands aren't set, an empty list is returned.
  1789. See https://core.telegram.org/bots/api#getmycommands for details.
  1790. """
  1791. return await self.api_request(
  1792. 'getMyCommands',
  1793. parameters=locals()
  1794. )
  1795. async def setStickerSetThumb(self,
  1796. name: str = None,
  1797. user_id: int = None,
  1798. thumb=None):
  1799. """Set the thumbnail of a sticker set.
  1800. Use this method to set the thumbnail of a sticker set.
  1801. Animated thumbnails can be set for animated sticker sets only.
  1802. Returns True on success.
  1803. See https://core.telegram.org/bots/api#setstickersetthumb for details.
  1804. """
  1805. return await self.api_request(
  1806. 'setStickerSetThumb',
  1807. parameters=locals()
  1808. )
  1809. async def logOut(self):
  1810. """Log out from the cloud Bot API server.
  1811. Use this method to log out from the cloud Bot API server
  1812. before launching the bot locally.
  1813. You must log out the bot before running it locally, otherwise there
  1814. is no guarantee that the bot will receive updates.
  1815. After a successful call, you can immediately log in on a local server,
  1816. but will not be able to log in back to the cloud Bot API server
  1817. for 10 minutes.
  1818. Returns True on success. Requires no parameters.
  1819. See https://core.telegram.org/bots/api#logout for details.
  1820. """
  1821. return await self.api_request(
  1822. 'logOut',
  1823. parameters=locals()
  1824. )
  1825. async def close(self):
  1826. """Close bot instance in local server.
  1827. Use this method to close the bot instance before moving it from one
  1828. local server to another.
  1829. You need to delete the webhook before calling this method to ensure
  1830. that the bot isn't launched again after server restart.
  1831. The method will return error 429 in the first 10 minutes after the
  1832. bot is launched. Returns True on success.
  1833. Requires no parameters.
  1834. See https://core.telegram.org/bots/api#close for details.
  1835. """
  1836. return await self.api_request(
  1837. 'close',
  1838. parameters=locals()
  1839. )
  1840. async def copyMessage(self, chat_id: Union[int, str],
  1841. from_chat_id: Union[int, str],
  1842. message_id: int,
  1843. message_thread_id: int = None,
  1844. protect_content: bool = None,
  1845. caption: str = None,
  1846. parse_mode: str = None,
  1847. caption_entities: list = None,
  1848. disable_notification: bool = None,
  1849. reply_to_message_id: int = None,
  1850. allow_sending_without_reply: bool = None,
  1851. reply_markup=None):
  1852. """Use this method to copy messages of any kind.
  1853. The method is analogous to the method forwardMessages, but the copied
  1854. message doesn't have a link to the original message.
  1855. Returns the MessageId of the sent message on success.
  1856. See https://core.telegram.org/bots/api#copymessage for details.
  1857. """
  1858. return await self.api_request(
  1859. 'copyMessage',
  1860. parameters=locals()
  1861. )
  1862. async def unpinAllChatMessages(self, chat_id: Union[int, str]):
  1863. """Use this method to clear the list of pinned messages in a chat.
  1864. If the chat is not a private chat, the bot must be an administrator
  1865. in the chat for this to work and must have the 'can_pin_messages'
  1866. admin right in a supergroup or 'can_edit_messages' admin right in a
  1867. channel.
  1868. Returns True on success.
  1869. See https://core.telegram.org/bots/api#unpinallchatmessages for details.
  1870. """
  1871. return await self.api_request(
  1872. 'unpinAllChatMessages',
  1873. parameters=locals()
  1874. )
  1875. async def banChatMember(self, chat_id: Union[int, str],
  1876. user_id: int, until_date: int,
  1877. revoke_messages: bool):
  1878. """Use this method to ban a user in a group, a supergroup or a channel.
  1879. In the case of supergroups and channels, the user will not be able to
  1880. return to the chat on their own using invite links, etc., unless
  1881. unbanned first.
  1882. The bot must be an administrator in the chat for this to work and must
  1883. have the appropriate administrator rights.
  1884. Returns True on success.
  1885. See https://core.telegram.org/bots/api#banchatmember for details.
  1886. """
  1887. return await self.api_request(
  1888. 'banChatMember',
  1889. parameters=locals()
  1890. )
  1891. async def banChatSenderChat(self, chat_id: Union[int, str], sender_chat_id: int):
  1892. """Use this method to ban a channel chat in a supergroup or a channel.
  1893. Until the chat is unbanned, the owner of the banned chat won't be able
  1894. to send messages on behalf of any of their channels.
  1895. The bot must be an administrator in the supergroup or channel for this
  1896. to work and must have the appropriate administrator rights.
  1897. Returns True on success.
  1898. See https://core.telegram.org/bots/api#banchatsenderchat for details.
  1899. """
  1900. return await self.api_request(
  1901. 'banChatSenderChat',
  1902. parameters=locals()
  1903. )
  1904. async def unbanChatSenderChat(self, chat_id: Union[int, str], sender_chat_id: int):
  1905. """Use this method to unban a previously banned channel chat in a supergroup or channel.
  1906. The bot must be an administrator for this to work and must have the
  1907. appropriate administrator rights.
  1908. Returns True on success.
  1909. See https://core.telegram.org/bots/api#unbanchatsenderchat for details.
  1910. """
  1911. return await self.api_request(
  1912. 'unbanChatSenderChat',
  1913. parameters=locals()
  1914. )
  1915. async def createChatInviteLink(self, chat_id: Union[int, str], name: str,
  1916. expire_date: int, member_limit: int,
  1917. creates_join_request: bool):
  1918. """Use this method to create an additional invite link for a chat.
  1919. The bot must be an administrator in the chat for this to work and must
  1920. have the appropriate administrator rights.
  1921. The link can be revoked using the method revokeChatInviteLink.
  1922. Returns the new invite link as ChatInviteLink object.
  1923. See https://core.telegram.org/bots/api#createchatinvitelink for details.
  1924. """
  1925. return await self.api_request(
  1926. 'createChatInviteLink',
  1927. parameters=locals()
  1928. )
  1929. async def editChatInviteLink(self, chat_id: Union[int, str],
  1930. invite_link: str, name: str, expire_date: int,
  1931. member_limit: int, creates_join_request: bool):
  1932. """Use this method to edit a non-primary invite link created by the bot.
  1933. The bot must be an administrator in the chat for this to work and must
  1934. have the appropriate administrator rights.
  1935. Returns the edited invite link as a ChatInviteLink object.
  1936. See https://core.telegram.org/bots/api#editchatinvitelink for details.
  1937. """
  1938. return await self.api_request(
  1939. 'editChatInviteLink',
  1940. parameters=locals()
  1941. )
  1942. async def revokeChatInviteLink(self, chat_id: Union[int, str], invite_link: str):
  1943. """Use this method to revoke an invite link created by the bot.
  1944. If the primary link is revoked, a new link is automatically generated.
  1945. The bot must be an administrator in the chat for this to work and must
  1946. have the appropriate administrator rights.
  1947. Returns the revoked invite link as ChatInviteLink object.
  1948. See https://core.telegram.org/bots/api#revokechatinvitelink for details.
  1949. """
  1950. return await self.api_request(
  1951. 'revokeChatInviteLink',
  1952. parameters=locals()
  1953. )
  1954. async def approveChatJoinRequest(self, chat_id: Union[int, str], user_id: int):
  1955. """Use this method to approve a chat join request.
  1956. The bot must be an administrator in the chat for this to work and must
  1957. have the can_invite_users administrator right.
  1958. Returns True on success.
  1959. See https://core.telegram.org/bots/api#approvechatjoinrequest for details.
  1960. """
  1961. return await self.api_request(
  1962. 'approveChatJoinRequest',
  1963. parameters=locals()
  1964. )
  1965. async def declineChatJoinRequest(self, chat_id: Union[int, str], user_id: int):
  1966. """Use this method to decline a chat join request.
  1967. The bot must be an administrator in the chat for this to work and must
  1968. have the can_invite_users administrator right.
  1969. Returns True on success.
  1970. See https://core.telegram.org/bots/api#declinechatjoinrequest for details.
  1971. """
  1972. return await self.api_request(
  1973. 'declineChatJoinRequest',
  1974. parameters=locals()
  1975. )
  1976. async def getChatMemberCount(self, chat_id: Union[int, str]):
  1977. """Use this method to get the number of members in a chat. Returns Int on success.
  1978. See https://core.telegram.org/bots/api#getchatmembercount for details.
  1979. """
  1980. return await self.api_request(
  1981. 'getChatMemberCount',
  1982. parameters=locals()
  1983. )
  1984. async def getForumTopicIconStickers(self):
  1985. """Use this method to get custom emoji stickers.
  1986. They can be used as a forum topic icon by any user.
  1987. Requires no parameters. Returns an Array of Sticker objects.
  1988. See https://core.telegram.org/bots/api#getforumtopiciconstickers for details.
  1989. """
  1990. return await self.api_request(
  1991. 'getForumTopicIconStickers',
  1992. parameters=locals()
  1993. )
  1994. async def createForumTopic(self, chat_id: Union[int, str], name: str,
  1995. icon_color: int, icon_custom_emoji_id: str):
  1996. """Use this method to create a topic in a forum supergroup chat.
  1997. The bot must be an administrator in the chat for this to work and must
  1998. have the can_manage_topics administrator rights.
  1999. Returns information about the created topic as a ForumTopic object.
  2000. See https://core.telegram.org/bots/api#createforumtopic for details.
  2001. """
  2002. return await self.api_request(
  2003. 'createForumTopic',
  2004. parameters=locals()
  2005. )
  2006. async def editForumTopic(self, chat_id: Union[int, str],
  2007. message_thread_id: int, name: str,
  2008. icon_custom_emoji_id: str):
  2009. """Use this method to edit name and icon of a topic in a forum supergroup chat.
  2010. The bot must be an administrator in the chat for this to work and must
  2011. have can_manage_topics administrator rights, unless it is the
  2012. creator of the topic.
  2013. Returns True on success.
  2014. See https://core.telegram.org/bots/api#editforumtopic for details.
  2015. """
  2016. return await self.api_request(
  2017. 'editForumTopic',
  2018. parameters=locals()
  2019. )
  2020. async def closeForumTopic(self, chat_id: Union[int, str],
  2021. message_thread_id: int):
  2022. """Use this method to close an open topic in a forum supergroup chat.
  2023. The bot must be an administrator in the chat for this to work and must
  2024. have the can_manage_topics administrator rights, unless it is the
  2025. creator of the topic.
  2026. Returns True on success.
  2027. See https://core.telegram.org/bots/api#closeforumtopic for details.
  2028. """
  2029. return await self.api_request(
  2030. 'closeForumTopic',
  2031. parameters=locals()
  2032. )
  2033. async def reopenForumTopic(self, chat_id: Union[int, str],
  2034. message_thread_id: int):
  2035. """Use this method to reopen a closed topic in a forum supergroup chat.
  2036. The bot must be an administrator in the chat for this to work and must
  2037. have the can_manage_topics administrator rights, unless it is the
  2038. creator of the topic.
  2039. Returns True on success.
  2040. See https://core.telegram.org/bots/api#reopenforumtopic for details.
  2041. """
  2042. return await self.api_request(
  2043. 'reopenForumTopic',
  2044. parameters=locals()
  2045. )
  2046. async def deleteForumTopic(self, chat_id: Union[int, str],
  2047. message_thread_id: int):
  2048. """Use this method to delete a forum topic.
  2049. This method deletes a forum topic along with all its messages in a
  2050. forum supergroup chat.
  2051. The bot must be an administrator in the chat for this to work and must
  2052. have the can_delete_messages administrator rights.
  2053. Returns True on success.
  2054. See https://core.telegram.org/bots/api#deleteforumtopic for details.
  2055. """
  2056. return await self.api_request(
  2057. 'deleteForumTopic',
  2058. parameters=locals()
  2059. )
  2060. async def unpinAllForumTopicMessages(self, chat_id: Union[int, str],
  2061. message_thread_id: int):
  2062. """Use this method to clear the list of pinned messages in a forum topic.
  2063. The bot must be an administrator in the chat for this to work and must
  2064. have the can_pin_messages administrator right in the supergroup.
  2065. Returns True on success.
  2066. See https://core.telegram.org/bots/api#unpinallforumtopicmessages for details.
  2067. """
  2068. return await self.api_request(
  2069. 'unpinAllForumTopicMessages',
  2070. parameters=locals()
  2071. )
  2072. async def deleteMyCommands(self, scope: 'BotCommandScope', language_code: str):
  2073. """Use this method to delete the list of the bot's commands for the given scope and user language.
  2074. After deletion, higher level commands will be shown to affected users.
  2075. Returns True on success.
  2076. See https://core.telegram.org/bots/api#deletemycommands for details.
  2077. """
  2078. return await self.api_request(
  2079. 'deleteMyCommands',
  2080. parameters=locals()
  2081. )
  2082. async def setChatMenuButton(self, chat_id: int, menu_button: 'MenuButton'):
  2083. """Use this method to change the bot's menu button in a private chat, or the default menu button.
  2084. Returns True on success.
  2085. See https://core.telegram.org/bots/api#setchatmenubutton for details.
  2086. """
  2087. return await self.api_request(
  2088. 'setChatMenuButton',
  2089. parameters=locals()
  2090. )
  2091. async def getChatMenuButton(self, chat_id: int):
  2092. """Use this method to get the current value of the bot's menu button.
  2093. Use this method to get the current value of the bot's menu button in a
  2094. private chat, or the default menu button.
  2095. Returns MenuButton on success.
  2096. See https://core.telegram.org/bots/api#getchatmenubutton for details.
  2097. """
  2098. return await self.api_request(
  2099. 'getChatMenuButton',
  2100. parameters=locals()
  2101. )
  2102. async def setMyDefaultAdministratorRights(self,
  2103. rights: 'ChatAdministratorRights',
  2104. for_channels: bool):
  2105. """Use this method to change the default administrator rights.
  2106. Use this method to change the default administrator rights requested by
  2107. the bot when it's added as an administrator to groups or channels.
  2108. These rights will be suggested to users, but they are free to modify
  2109. the list before adding the bot.
  2110. Returns True on success.
  2111. See https://core.telegram.org/bots/api#setmydefaultadministratorrights for details.
  2112. """
  2113. return await self.api_request(
  2114. 'setMyDefaultAdministratorRights',
  2115. parameters=locals()
  2116. )
  2117. async def getMyDefaultAdministratorRights(self, for_channels: bool):
  2118. """Use this method to get the current default administrator rights of
  2119. the bot.
  2120. Returns ChatAdministratorRights on success.
  2121. See https://core.telegram.org/bots/api#getmydefaultadministratorrights for details.
  2122. """
  2123. return await self.api_request(
  2124. 'getMyDefaultAdministratorRights',
  2125. parameters=locals()
  2126. )
  2127. async def getCustomEmojiStickers(self, custom_emoji_ids: List[str]):
  2128. """Use this method to get information about custom emoji stickers by their identifiers.
  2129. Returns an Array of Sticker objects.
  2130. See https://core.telegram.org/bots/api#getcustomemojistickers for details.
  2131. """
  2132. return await self.api_request(
  2133. 'getCustomEmojiStickers',
  2134. parameters=locals()
  2135. )
  2136. async def answerWebAppQuery(self, web_app_query_id: str,
  2137. result: 'InlineQueryResult'):
  2138. """Use this method to set the result of an interaction with a Web App.
  2139. Use this method to set the result of an interaction with a Web App and
  2140. send a corresponding message on behalf of the user to the chat from
  2141. which the query originated.
  2142. On success, a SentWebAppMessage object is returned.
  2143. See https://core.telegram.org/bots/api#answerwebappquery for details.
  2144. """
  2145. return await self.api_request(
  2146. 'answerWebAppQuery',
  2147. parameters=locals()
  2148. )
  2149. async def createInvoiceLink(self, title: str, description: str,
  2150. payload: str, provider_token: str,
  2151. currency: str, prices: List['LabeledPrice'],
  2152. max_tip_amount: int,
  2153. suggested_tip_amounts: List[int],
  2154. provider_data: str, photo_url: str,
  2155. photo_size: int, photo_width: int,
  2156. photo_height: int, need_name: bool,
  2157. need_phone_number: bool, need_email: bool,
  2158. need_shipping_address: bool,
  2159. send_phone_number_to_provider: bool,
  2160. send_email_to_provider: bool,
  2161. is_flexible: bool):
  2162. """Use this method to create a link for an invoice.
  2163. Returns the created invoice link as String on success.
  2164. See https://core.telegram.org/bots/api#createinvoicelink for details.
  2165. """
  2166. return await self.api_request(
  2167. 'createInvoiceLink',
  2168. parameters=locals()
  2169. )
  2170. async def editGeneralForumTopic(self, chat_id: Union[int, str], name: str):
  2171. """Edit the name of the 'General' topic in a forum supergroup chat.
  2172. The bot must be an administrator in the chat for this to work and must
  2173. have can_manage_topics administrator rights.
  2174. Returns True on success.
  2175. See https://core.telegram.org/bots/api#editgeneralforumtopic for details.
  2176. """
  2177. return await self.api_request(
  2178. 'editGeneralForumTopic',
  2179. parameters=locals()
  2180. )
  2181. async def closeGeneralForumTopic(self, chat_id: Union[int, str]):
  2182. """Close an open 'General' topic in a forum supergroup chat.
  2183. The bot must be an administrator in the chat for this to work and must
  2184. have the can_manage_topics administrator rights.
  2185. Returns True on success.
  2186. See https://core.telegram.org/bots/api#closegeneralforumtopic for details.
  2187. """
  2188. return await self.api_request(
  2189. 'closeGeneralForumTopic',
  2190. parameters=locals()
  2191. )
  2192. async def reopenGeneralForumTopic(self, chat_id: Union[int, str]):
  2193. """Reopen a closed 'General' topic in a forum supergroup chat.
  2194. The bot must be an administrator in the chat for this to work and must
  2195. have the can_manage_topics administrator rights.
  2196. The topic will be automatically unhidden if it was hidden.
  2197. Returns True on success.
  2198. See https://core.telegram.org/bots/api#reopengeneralforumtopic for details.
  2199. """
  2200. return await self.api_request(
  2201. 'reopenGeneralForumTopic',
  2202. parameters=locals()
  2203. )
  2204. async def hideGeneralForumTopic(self, chat_id: Union[int, str]):
  2205. """Hide the 'General' topic in a forum supergroup chat.
  2206. The bot must be an administrator in the chat for this to work and
  2207. must have the can_manage_topics administrator rights.
  2208. The topic will be automatically closed if it was open.
  2209. Returns True on success.
  2210. See https://core.telegram.org/bots/api#hidegeneralforumtopic for details.
  2211. """
  2212. return await self.api_request(
  2213. 'hideGeneralForumTopic',
  2214. parameters=locals()
  2215. )
  2216. async def unhideGeneralForumTopic(self, chat_id: Union[int, str]):
  2217. """Unhide the 'General' topic in a forum supergroup chat.
  2218. The bot must be an administrator in the chat for this to work and must
  2219. have the can_manage_topics administrator rights.
  2220. Returns True on success.
  2221. See https://core.telegram.org/bots/api#unhidegeneralforumtopic for details.
  2222. """
  2223. return await self.api_request(
  2224. 'unhideGeneralForumTopic',
  2225. parameters=locals()
  2226. )
  2227. async def setMyName(self, name: str, language_code: str):
  2228. """Change the bot's name.
  2229. Returns True on success.
  2230. See https://core.telegram.org/bots/api#setmyname for details.
  2231. """
  2232. return await self.api_request(
  2233. 'setMyName',
  2234. parameters=locals()
  2235. )
  2236. async def getMyName(self, language_code: str):
  2237. """Get the current bot name for the given user language.
  2238. Returns BotName on success.
  2239. See https://core.telegram.org/bots/api#getmyname for details.
  2240. """
  2241. return await self.api_request(
  2242. 'getMyName',
  2243. parameters=locals()
  2244. )
  2245. async def setMyDescription(self, description: str, language_code: str):
  2246. """Change the bot's description, which is shown in the chat with the bot if
  2247. the chat is empty.
  2248. Returns True on success.
  2249. See https://core.telegram.org/bots/api#setmydescription for details.
  2250. """
  2251. return await self.api_request(
  2252. 'setMyDescription',
  2253. parameters=locals()
  2254. )
  2255. async def getMyDescription(self, language_code: str):
  2256. """Get the current bot description for the given user language.
  2257. Returns BotDescription on success.
  2258. See https://core.telegram.org/bots/api#getmydescription for details.
  2259. """
  2260. return await self.api_request(
  2261. 'getMyDescription',
  2262. parameters=locals()
  2263. )
  2264. async def setMyShortDescription(self, short_description: str, language_code: str):
  2265. """Change the bot's short description, which is shown on the bot's profile
  2266. page and is sent together with the link when users share the bot.
  2267. Returns True on success.
  2268. See https://core.telegram.org/bots/api#setmyshortdescription for details.
  2269. """
  2270. return await self.api_request(
  2271. 'setMyShortDescription',
  2272. parameters=locals()
  2273. )
  2274. async def getMyShortDescription(self, language_code: str):
  2275. """Get the current bot short description for the given user language.
  2276. Returns BotShortDescription on success.
  2277. See https://core.telegram.org/bots/api#getmyshortdescription for details.
  2278. """
  2279. return await self.api_request(
  2280. 'getMyShortDescription',
  2281. parameters=locals()
  2282. )
  2283. async def setStickerEmojiList(self, sticker: str, emoji_list: List[str]):
  2284. """Change the list of emoji assigned to a regular or custom emoji sticker.
  2285. The sticker must belong to a sticker set created by the bot.
  2286. Returns True on success.
  2287. See https://core.telegram.org/bots/api#setstickeremojilist for details.
  2288. """
  2289. return await self.api_request(
  2290. 'setStickerEmojiList',
  2291. parameters=locals()
  2292. )
  2293. async def setStickerKeywords(self, sticker: str, keywords: List[str]):
  2294. """Change search keywords assigned to a regular or custom emoji sticker.
  2295. The sticker must belong to a sticker set created by the bot.
  2296. Returns True on success.
  2297. See https://core.telegram.org/bots/api#setstickerkeywords for details.
  2298. """
  2299. return await self.api_request(
  2300. 'setStickerKeywords',
  2301. parameters=locals()
  2302. )
  2303. async def setStickerMaskPosition(self, sticker: str, mask_position: 'MaskPosition'):
  2304. """Change the mask position of a mask sticker.
  2305. The sticker must belong to a sticker set that was created by the bot.
  2306. Returns True on success.
  2307. See https://core.telegram.org/bots/api#setstickermaskposition for details.
  2308. """
  2309. return await self.api_request(
  2310. 'setStickerMaskPosition',
  2311. parameters=locals()
  2312. )
  2313. async def setStickerSetTitle(self, name: str, title: str):
  2314. """Set the title of a created sticker set.
  2315. Returns True on success.
  2316. See https://core.telegram.org/bots/api#setstickersettitle for details.
  2317. """
  2318. return await self.api_request(
  2319. 'setStickerSetTitle',
  2320. parameters=locals()
  2321. )
  2322. async def setStickerSetThumbnail(self, name: str, user_id: int, thumbnail: 'InputFile or String'):
  2323. """Set the thumbnail of a regular or mask sticker set.
  2324. The format of the thumbnail file must match the format of the stickers
  2325. in the set.
  2326. Returns True on success.
  2327. See https://core.telegram.org/bots/api#setstickersetthumbnail for details.
  2328. """
  2329. return await self.api_request(
  2330. 'setStickerSetThumbnail',
  2331. parameters=locals()
  2332. )
  2333. async def setCustomEmojiStickerSetThumbnail(self, name: str, custom_emoji_id: str):
  2334. """Set the thumbnail of a custom emoji sticker set.
  2335. Returns True on success.
  2336. See https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail for details.
  2337. """
  2338. return await self.api_request(
  2339. 'setCustomEmojiStickerSetThumbnail',
  2340. parameters=locals()
  2341. )
  2342. async def deleteStickerSet(self, name: str):
  2343. """Delete a sticker set that was created by the bot.
  2344. Returns True on success.
  2345. See https://core.telegram.org/bots/api#deletestickerset for details.
  2346. """
  2347. return await self.api_request(
  2348. 'deleteStickerSet',
  2349. parameters=locals()
  2350. )