Queer European MD passionate about IT

api.py 160 KB

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