Queer European MD passionate about IT

api.py 124 KB

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