Queer European MD passionate about IT

api.py 120 KB

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