Queer European MD passionate about IT

api.py 96 KB

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