Queer European MD passionate about IT

api.py 129 KB

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