Queer European MD passionate about IT

api.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287
  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. reply_markup=None):
  607. """Send a photo from file_id, HTTP url or file.
  608. See https://core.telegram.org/bots/api#sendphoto for details.
  609. """
  610. return await self.api_request(
  611. 'sendPhoto',
  612. parameters=locals()
  613. )
  614. async def sendAudio(self, chat_id: Union[int, str], audio,
  615. caption: str = None,
  616. parse_mode: str = None,
  617. caption_entities: List[dict] = None,
  618. duration: int = None,
  619. performer: str = None,
  620. title: str = None,
  621. thumb=None,
  622. disable_notification: bool = None,
  623. reply_to_message_id: int = None,
  624. allow_sending_without_reply: bool = None,
  625. message_thread_id: int = None,
  626. protect_content: bool = None,
  627. reply_markup=None):
  628. """Send an audio file from file_id, HTTP url or file.
  629. See https://core.telegram.org/bots/api#sendaudio for details.
  630. """
  631. return await self.api_request(
  632. 'sendAudio',
  633. parameters=locals()
  634. )
  635. async def sendDocument(self, chat_id: Union[int, str], document,
  636. thumb=None,
  637. caption: str = None,
  638. parse_mode: str = None,
  639. caption_entities: List[dict] = None,
  640. disable_content_type_detection: bool = None,
  641. disable_notification: bool = None,
  642. reply_to_message_id: int = None,
  643. allow_sending_without_reply: bool = None,
  644. message_thread_id: int = None,
  645. protect_content: bool = None,
  646. reply_markup=None):
  647. """Send a document from file_id, HTTP url or file.
  648. See https://core.telegram.org/bots/api#senddocument for details.
  649. """
  650. return await self.api_request(
  651. 'sendDocument',
  652. parameters=locals()
  653. )
  654. async def sendVideo(self, chat_id: Union[int, str], video,
  655. duration: int = None,
  656. width: int = None,
  657. height: int = None,
  658. thumb=None,
  659. caption: str = None,
  660. parse_mode: str = None,
  661. caption_entities: List[dict] = None,
  662. supports_streaming: bool = None,
  663. disable_notification: bool = None,
  664. reply_to_message_id: int = None,
  665. allow_sending_without_reply: bool = None,
  666. message_thread_id: int = None,
  667. protect_content: bool = None,
  668. reply_markup=None):
  669. """Send a video from file_id, HTTP url or file.
  670. See https://core.telegram.org/bots/api#sendvideo for details.
  671. """
  672. return await self.api_request(
  673. 'sendVideo',
  674. parameters=locals()
  675. )
  676. async def sendAnimation(self, chat_id: Union[int, str], animation,
  677. duration: int = None,
  678. width: int = None,
  679. height: int = None,
  680. thumb=None,
  681. caption: str = None,
  682. parse_mode: str = None,
  683. caption_entities: List[dict] = None,
  684. disable_notification: bool = None,
  685. reply_to_message_id: int = None,
  686. allow_sending_without_reply: bool = None,
  687. message_thread_id: int = None,
  688. protect_content: bool = None,
  689. reply_markup=None):
  690. """Send animation files (GIF or H.264/MPEG-4 AVC video without sound).
  691. See https://core.telegram.org/bots/api#sendanimation for details.
  692. """
  693. return await self.api_request(
  694. 'sendAnimation',
  695. parameters=locals()
  696. )
  697. async def sendVoice(self, chat_id: Union[int, str], voice,
  698. caption: str = None,
  699. parse_mode: str = None,
  700. caption_entities: List[dict] = None,
  701. duration: int = None,
  702. disable_notification: bool = None,
  703. reply_to_message_id: int = None,
  704. allow_sending_without_reply: bool = None,
  705. message_thread_id: int = None,
  706. protect_content: bool = None,
  707. reply_markup=None):
  708. """Send an audio file to be displayed as playable voice message.
  709. `voice` must be in an .ogg file encoded with OPUS.
  710. See https://core.telegram.org/bots/api#sendvoice for details.
  711. """
  712. return await self.api_request(
  713. 'sendVoice',
  714. parameters=locals()
  715. )
  716. async def sendVideoNote(self, chat_id: Union[int, str], video_note,
  717. duration: int = None,
  718. length: int = None,
  719. thumb=None,
  720. disable_notification: bool = None,
  721. reply_to_message_id: int = None,
  722. allow_sending_without_reply: bool = None,
  723. message_thread_id: int = None,
  724. protect_content: bool = None,
  725. reply_markup=None):
  726. """Send a rounded square mp4 video message of up to 1 minute long.
  727. See https://core.telegram.org/bots/api#sendvideonote for details.
  728. """
  729. return await self.api_request(
  730. 'sendVideoNote',
  731. parameters=locals()
  732. )
  733. async def sendMediaGroup(self, chat_id: Union[int, str], media: list,
  734. disable_notification: bool = None,
  735. reply_to_message_id: int = None,
  736. message_thread_id: int = None,
  737. protect_content: bool = None,
  738. allow_sending_without_reply: bool = None):
  739. """Send a group of photos or videos as an album.
  740. `media` must be a list of `InputMediaPhoto` and/or `InputMediaVideo`
  741. objects.
  742. See https://core.telegram.org/bots/api#sendmediagroup for details.
  743. """
  744. return await self.api_request(
  745. 'sendMediaGroup',
  746. parameters=locals()
  747. )
  748. async def sendLocation(self, chat_id: Union[int, str],
  749. latitude: float, longitude: float,
  750. horizontal_accuracy: float = None,
  751. live_period=None,
  752. heading: int = None,
  753. proximity_alert_radius: int = None,
  754. disable_notification: bool = None,
  755. reply_to_message_id: int = None,
  756. allow_sending_without_reply: bool = None,
  757. message_thread_id: int = None,
  758. protect_content: bool = None,
  759. reply_markup=None):
  760. """Send a point on the map. May be kept updated for a `live_period`.
  761. See https://core.telegram.org/bots/api#sendlocation for details.
  762. """
  763. if horizontal_accuracy: # Horizontal accuracy: 0-1500 m [float].
  764. horizontal_accuracy = max(0.0, min(horizontal_accuracy, 1500.0))
  765. if live_period:
  766. live_period = max(60, min(live_period, 86400))
  767. if heading: # Direction in which the user is moving, 1-360°
  768. heading = max(1, min(heading, 360))
  769. if proximity_alert_radius: # Distance 1-100000 m
  770. proximity_alert_radius = max(1, min(proximity_alert_radius, 100000))
  771. return await self.api_request(
  772. 'sendLocation',
  773. parameters=locals()
  774. )
  775. async def editMessageLiveLocation(self, latitude: float, longitude: float,
  776. chat_id: Union[int, str] = None,
  777. message_id: int = None,
  778. inline_message_id: str = None,
  779. horizontal_accuracy: float = None,
  780. heading: int = None,
  781. proximity_alert_radius: int = None,
  782. reply_markup=None):
  783. """Edit live location messages.
  784. A location can be edited until its live_period expires or editing is
  785. explicitly disabled by a call to stopMessageLiveLocation.
  786. The message to be edited may be identified through `inline_message_id`
  787. OR the couple (`chat_id`, `message_id`).
  788. See https://core.telegram.org/bots/api#editmessagelivelocation
  789. for details.
  790. """
  791. if inline_message_id is None and (chat_id is None or message_id is None):
  792. logging.error("Invalid target chat!")
  793. if horizontal_accuracy: # Horizontal accuracy: 0-1500 m [float].
  794. horizontal_accuracy = max(0.0, min(horizontal_accuracy, 1500.0))
  795. if heading: # Direction in which the user is moving, 1-360°
  796. heading = max(1, min(heading, 360))
  797. if proximity_alert_radius: # Distance 1-100000 m
  798. proximity_alert_radius = max(1, min(proximity_alert_radius, 100000))
  799. return await self.api_request(
  800. 'editMessageLiveLocation',
  801. parameters=locals()
  802. )
  803. async def stopMessageLiveLocation(self,
  804. chat_id: Union[int, str] = None,
  805. message_id: int = None,
  806. inline_message_id: int = None,
  807. reply_markup=None):
  808. """Stop updating a live location message before live_period expires.
  809. The position to be stopped may be identified through
  810. `inline_message_id` OR the couple (`chat_id`, `message_id`).
  811. `reply_markup` type may be only `InlineKeyboardMarkup`.
  812. See https://core.telegram.org/bots/api#stopmessagelivelocation
  813. for details.
  814. """
  815. return await self.api_request(
  816. 'stopMessageLiveLocation',
  817. parameters=locals()
  818. )
  819. async def sendVenue(self, chat_id: Union[int, str],
  820. latitude: float, longitude: float,
  821. title: str, address: str,
  822. foursquare_id: str = None,
  823. foursquare_type: str = None,
  824. google_place_id: str = None,
  825. google_place_type: str = None,
  826. disable_notification: bool = None,
  827. reply_to_message_id: int = None,
  828. allow_sending_without_reply: bool = None,
  829. message_thread_id: int = None,
  830. protect_content: bool = None,
  831. reply_markup=None):
  832. """Send information about a venue.
  833. Integrated with FourSquare.
  834. See https://core.telegram.org/bots/api#sendvenue for details.
  835. """
  836. return await self.api_request(
  837. 'sendVenue',
  838. parameters=locals()
  839. )
  840. async def sendContact(self, chat_id: Union[int, str],
  841. phone_number: str,
  842. first_name: str,
  843. last_name: str = None,
  844. vcard: str = None,
  845. disable_notification: bool = None,
  846. reply_to_message_id: int = None,
  847. allow_sending_without_reply: bool = None,
  848. message_thread_id: int = None,
  849. protect_content: bool = None,
  850. reply_markup=None):
  851. """Send a phone contact.
  852. See https://core.telegram.org/bots/api#sendcontact for details.
  853. """
  854. return await self.api_request(
  855. 'sendContact',
  856. parameters=locals()
  857. )
  858. async def sendPoll(self,
  859. chat_id: Union[int, str],
  860. question: str,
  861. options: List[str],
  862. is_anonymous: bool = True,
  863. type_: str = 'regular',
  864. allows_multiple_answers: bool = False,
  865. correct_option_id: int = None,
  866. explanation: str = None,
  867. explanation_parse_mode: str = None,
  868. explanation_entities: List[dict] = None,
  869. open_period: int = None,
  870. close_date: Union[int, datetime.datetime] = None,
  871. is_closed: bool = None,
  872. disable_notification: bool = None,
  873. allow_sending_without_reply: bool = None,
  874. reply_to_message_id: int = None,
  875. message_thread_id: int = None,
  876. protect_content: bool = None,
  877. reply_markup=None):
  878. """Send a native poll in a group, a supergroup or channel.
  879. See https://core.telegram.org/bots/api#sendpoll for details.
  880. close_date: Unix timestamp; 5-600 seconds from now.
  881. open_period (overwrites close_date): seconds (integer), 5-600.
  882. """
  883. if open_period is not None:
  884. close_date = None
  885. open_period = min(max(5, open_period), 600)
  886. elif isinstance(close_date, datetime.datetime):
  887. now = datetime.datetime.now()
  888. close_date = min(
  889. max(
  890. now + datetime.timedelta(seconds=5),
  891. close_date
  892. ), now + datetime.timedelta(seconds=600)
  893. )
  894. close_date = int(close_date.timestamp())
  895. # To avoid shadowing `type`, this workaround is required
  896. parameters = locals().copy()
  897. parameters['type'] = parameters['type_']
  898. del parameters['type_']
  899. return await self.api_request(
  900. 'sendPoll',
  901. parameters=parameters
  902. )
  903. async def sendChatAction(self, chat_id: Union[int, str], action):
  904. """Fake a typing status or similar.
  905. See https://core.telegram.org/bots/api#sendchataction for details.
  906. """
  907. return await self.api_request(
  908. 'sendChatAction',
  909. parameters=locals()
  910. )
  911. async def getUserProfilePhotos(self, user_id,
  912. offset=None,
  913. limit=None):
  914. """Get a list of profile pictures for a user.
  915. See https://core.telegram.org/bots/api#getuserprofilephotos
  916. for details.
  917. """
  918. return await self.api_request(
  919. 'getUserProfilePhotos',
  920. parameters=locals()
  921. )
  922. async def getFile(self, file_id):
  923. """Get basic info about a file and prepare it for downloading.
  924. For the moment, bots can download files of up to
  925. 20MB in size.
  926. On success, a File object is returned. The file can then be downloaded
  927. via the link https://api.telegram.org/file/bot<token>/<file_path>,
  928. where <file_path> is taken from the response.
  929. See https://core.telegram.org/bots/api#getfile for details.
  930. """
  931. return await self.api_request(
  932. 'getFile',
  933. parameters=locals()
  934. )
  935. async def kickChatMember(self, chat_id: Union[int, str], user_id,
  936. until_date=None):
  937. """Kick a user from a group, a supergroup or a channel.
  938. In the case of supergroups and channels, the user will not be able to
  939. return to the group on their own using invite links, etc., unless
  940. unbanned first.
  941. Note: In regular groups (non-supergroups), this method will only work
  942. if the ‘All Members Are Admins’ setting is off in the target group.
  943. Otherwise, members may only be removed by the group's creator or by
  944. the member that added them.
  945. See https://core.telegram.org/bots/api#kickchatmember for details.
  946. """
  947. return await self.api_request(
  948. 'kickChatMember',
  949. parameters=locals()
  950. )
  951. async def unbanChatMember(self, chat_id: Union[int, str], user_id: int,
  952. only_if_banned: bool = True):
  953. """Unban a previously kicked user in a supergroup or channel.
  954. The user will not return to the group or channel automatically, but
  955. will be able to join via link, etc.
  956. The bot must be an administrator for this to work.
  957. Return True on success.
  958. See https://core.telegram.org/bots/api#unbanchatmember for details.
  959. If `only_if_banned` is set to False, regular users will be kicked from
  960. chat upon call of this method on them.
  961. """
  962. return await self.api_request(
  963. 'unbanChatMember',
  964. parameters=locals()
  965. )
  966. async def restrictChatMember(self, chat_id: Union[int, str], user_id: int,
  967. permissions: Dict[str, bool],
  968. until_date: Union[datetime.datetime, int] = None):
  969. """Restrict a user in a supergroup.
  970. The bot must be an administrator in the supergroup for this to work
  971. and must have the appropriate admin rights.
  972. Pass True for all boolean parameters to lift restrictions from a
  973. user.
  974. Return True on success.
  975. See https://core.telegram.org/bots/api#restrictchatmember for details.
  976. until_date must be a Unix timestamp.
  977. """
  978. if isinstance(until_date, datetime.datetime):
  979. until_date = int(until_date.timestamp())
  980. return await self.api_request(
  981. 'restrictChatMember',
  982. parameters=locals()
  983. )
  984. async def promoteChatMember(self, chat_id: Union[int, str], user_id: int,
  985. is_anonymous: bool = None,
  986. can_change_info: bool = None,
  987. can_post_messages: bool = None,
  988. can_edit_messages: bool = None,
  989. can_delete_messages: bool = None,
  990. can_invite_users: bool = None,
  991. can_restrict_members: bool = None,
  992. can_pin_messages: bool = None,
  993. can_promote_members: bool = None,
  994. can_manage_topics: bool = None,
  995. can_manage_chat: bool = None,
  996. can_manage_video_chats: bool = None):
  997. """Promote or demote a user in a supergroup or a channel.
  998. The bot must be an administrator in the chat for this to work and must
  999. have the appropriate admin rights.
  1000. Pass False for all boolean parameters to demote a user.
  1001. Return True on success.
  1002. See https://core.telegram.org/bots/api#promotechatmember for details.
  1003. """
  1004. return await self.api_request(
  1005. 'promoteChatMember',
  1006. parameters=locals()
  1007. )
  1008. async def exportChatInviteLink(self, chat_id: Union[int, str]):
  1009. """Generate a new invite link for a chat and revoke any active link.
  1010. The bot must be an administrator in the chat for this to work and must
  1011. have the appropriate admin rights.
  1012. Return the new invite link as String on success.
  1013. NOTE: to get the current invite link, use `getChat` method.
  1014. See https://core.telegram.org/bots/api#exportchatinvitelink
  1015. for details.
  1016. """
  1017. return await self.api_request(
  1018. 'exportChatInviteLink',
  1019. parameters=locals()
  1020. )
  1021. async def setChatPhoto(self, chat_id: Union[int, str], photo):
  1022. """Set a new profile photo for the chat.
  1023. Photos can't be changed for private chats.
  1024. `photo` must be an input file (file_id and urls are not allowed).
  1025. The bot must be an administrator in the chat for this to work and must
  1026. have the appropriate admin rights.
  1027. Return True on success.
  1028. See https://core.telegram.org/bots/api#setchatphoto for details.
  1029. """
  1030. return await self.api_request(
  1031. 'setChatPhoto',
  1032. parameters=locals()
  1033. )
  1034. async def deleteChatPhoto(self, chat_id: Union[int, str]):
  1035. """Delete a chat photo.
  1036. Photos can't be changed for private chats.
  1037. The bot must be an administrator in the chat for this to work and must
  1038. have the appropriate admin rights.
  1039. Return True on success.
  1040. See https://core.telegram.org/bots/api#deletechatphoto for details.
  1041. """
  1042. return await self.api_request(
  1043. 'deleteChatPhoto',
  1044. parameters=locals()
  1045. )
  1046. async def setChatTitle(self, chat_id: Union[int, str], title):
  1047. """Change the title of a chat.
  1048. Titles can't be changed for private chats.
  1049. The bot must be an administrator in the chat for this to work and must
  1050. have the appropriate admin rights.
  1051. Return True on success.
  1052. See https://core.telegram.org/bots/api#setchattitle for details.
  1053. """
  1054. return await self.api_request(
  1055. 'setChatTitle',
  1056. parameters=locals()
  1057. )
  1058. async def setChatDescription(self, chat_id: Union[int, str], description):
  1059. """Change the description of a supergroup or a channel.
  1060. The bot must be an administrator in the chat for this to work and must
  1061. have the appropriate admin rights.
  1062. Return True on success.
  1063. See https://core.telegram.org/bots/api#setchatdescription for details.
  1064. """
  1065. return await self.api_request(
  1066. 'setChatDescription',
  1067. parameters=locals()
  1068. )
  1069. async def pinChatMessage(self, chat_id: Union[int, str], message_id,
  1070. disable_notification: bool = None):
  1071. """Pin a message in a group, a supergroup, or a channel.
  1072. The bot must be an administrator in the chat for this to work and must
  1073. have the ‘can_pin_messages’ admin right in the supergroup or
  1074. ‘can_edit_messages’ admin right in the channel.
  1075. Return True on success.
  1076. See https://core.telegram.org/bots/api#pinchatmessage for details.
  1077. """
  1078. return await self.api_request(
  1079. 'pinChatMessage',
  1080. parameters=locals()
  1081. )
  1082. async def unpinChatMessage(self, chat_id: Union[int, str],
  1083. message_id: int = None):
  1084. """Unpin a message in a group, a supergroup, or a channel.
  1085. The bot must be an administrator in the chat for this to work and must
  1086. have the ‘can_pin_messages’ admin right in the supergroup or
  1087. ‘can_edit_messages’ admin right in the channel.
  1088. Return True on success.
  1089. See https://core.telegram.org/bots/api#unpinchatmessage for details.
  1090. """
  1091. return await self.api_request(
  1092. 'unpinChatMessage',
  1093. parameters=locals()
  1094. )
  1095. async def leaveChat(self, chat_id: Union[int, str]):
  1096. """Make the bot leave a group, supergroup or channel.
  1097. Return True on success.
  1098. See https://core.telegram.org/bots/api#leavechat for details.
  1099. """
  1100. return await self.api_request(
  1101. 'leaveChat',
  1102. parameters=locals()
  1103. )
  1104. async def getChat(self, chat_id: Union[int, str]):
  1105. """Get up-to-date information about the chat.
  1106. Return a Chat object on success.
  1107. See https://core.telegram.org/bots/api#getchat for details.
  1108. """
  1109. return await self.api_request(
  1110. 'getChat',
  1111. parameters=locals()
  1112. )
  1113. async def getChatAdministrators(self, chat_id: Union[int, str]):
  1114. """Get a list of administrators in a chat.
  1115. On success, return an Array of ChatMember objects that contains
  1116. information about all chat administrators except other bots.
  1117. If the chat is a group or a supergroup and no administrators were
  1118. appointed, only the creator will be returned.
  1119. See https://core.telegram.org/bots/api#getchatadministrators
  1120. for details.
  1121. """
  1122. return await self.api_request(
  1123. 'getChatAdministrators',
  1124. parameters=locals()
  1125. )
  1126. async def getChatMembersCount(self, chat_id: Union[int, str]):
  1127. """Get the number of members in a chat.
  1128. Returns Int on success.
  1129. See https://core.telegram.org/bots/api#getchatmemberscount for details.
  1130. """
  1131. return await self.api_request(
  1132. 'getChatMembersCount',
  1133. parameters=locals()
  1134. )
  1135. async def getChatMember(self, chat_id: Union[int, str], user_id):
  1136. """Get information about a member of a chat.
  1137. Returns a ChatMember object on success.
  1138. See https://core.telegram.org/bots/api#getchatmember for details.
  1139. """
  1140. return await self.api_request(
  1141. 'getChatMember',
  1142. parameters=locals()
  1143. )
  1144. async def setChatStickerSet(self, chat_id: Union[int, str], sticker_set_name):
  1145. """Set a new group sticker set for a supergroup.
  1146. The bot must be an administrator in the chat for this to work and must
  1147. have the appropriate admin rights.
  1148. Use the field `can_set_sticker_set` optionally returned in getChat
  1149. requests to check if the bot can use this method.
  1150. Returns True on success.
  1151. See https://core.telegram.org/bots/api#setchatstickerset for details.
  1152. """
  1153. return await self.api_request(
  1154. 'setChatStickerSet',
  1155. parameters=locals()
  1156. )
  1157. async def deleteChatStickerSet(self, chat_id: Union[int, str]):
  1158. """Delete a group sticker set from a supergroup.
  1159. The bot must be an administrator in the chat for this to work and must
  1160. have the appropriate admin rights.
  1161. Use the field `can_set_sticker_set` optionally returned in getChat
  1162. requests to check if the bot can use this method.
  1163. Returns True on success.
  1164. See https://core.telegram.org/bots/api#deletechatstickerset for
  1165. details.
  1166. """
  1167. return await self.api_request(
  1168. 'deleteChatStickerSet',
  1169. parameters=locals()
  1170. )
  1171. async def answerCallbackQuery(self, callback_query_id,
  1172. text=None,
  1173. show_alert=None,
  1174. url=None,
  1175. cache_time=None):
  1176. """Send answers to callback queries sent from inline keyboards.
  1177. The answer will be displayed to the user as a notification at the top
  1178. of the chat screen or as an alert.
  1179. On success, True is returned.
  1180. See https://core.telegram.org/bots/api#answercallbackquery for details.
  1181. """
  1182. return await self.api_request(
  1183. 'answerCallbackQuery',
  1184. parameters=locals()
  1185. )
  1186. async def editMessageText(self, text: str,
  1187. chat_id: Union[int, str] = None,
  1188. message_id: int = None,
  1189. inline_message_id: str = None,
  1190. parse_mode: str = None,
  1191. entities: List[dict] = None,
  1192. disable_web_page_preview: bool = None,
  1193. reply_markup=None):
  1194. """Edit text and game messages.
  1195. On success, if edited message is sent by the bot, the edited Message
  1196. is returned, otherwise True is returned.
  1197. See https://core.telegram.org/bots/api#editmessagetext for details.
  1198. """
  1199. return await self.api_request(
  1200. 'editMessageText',
  1201. parameters=locals()
  1202. )
  1203. async def editMessageCaption(self,
  1204. chat_id: Union[int, str] = None,
  1205. message_id: int = None,
  1206. inline_message_id: str = None,
  1207. caption: str = None,
  1208. parse_mode: str = None,
  1209. caption_entities: List[dict] = None,
  1210. reply_markup=None):
  1211. """Edit captions of messages.
  1212. On success, if edited message is sent by the bot, the edited Message is
  1213. returned, otherwise True is returned.
  1214. See https://core.telegram.org/bots/api#editmessagecaption for details.
  1215. """
  1216. return await self.api_request(
  1217. 'editMessageCaption',
  1218. parameters=locals()
  1219. )
  1220. async def editMessageMedia(self,
  1221. chat_id: Union[int, str] = None,
  1222. message_id: int = None,
  1223. inline_message_id: str = None,
  1224. media=None,
  1225. reply_markup=None):
  1226. """Edit animation, audio, document, photo, or video messages.
  1227. If a message is a part of a message album, then it can be edited only
  1228. to a photo or a video. Otherwise, message type can be changed
  1229. arbitrarily.
  1230. When inline message is edited, new file can't be uploaded.
  1231. Use previously uploaded file via its file_id or specify a URL.
  1232. On success, if the edited message was sent by the bot, the edited
  1233. Message is returned, otherwise True is returned.
  1234. See https://core.telegram.org/bots/api#editmessagemedia for details.
  1235. """
  1236. return await self.api_request(
  1237. 'editMessageMedia',
  1238. parameters=locals()
  1239. )
  1240. async def editMessageReplyMarkup(self,
  1241. chat_id: Union[int, str] = None,
  1242. message_id: int = None,
  1243. inline_message_id: str = None,
  1244. reply_markup=None):
  1245. """Edit only the reply markup of messages.
  1246. On success, if edited message is sent by the bot, the edited Message is
  1247. returned, otherwise True is returned.
  1248. See https://core.telegram.org/bots/api#editmessagereplymarkup for
  1249. details.
  1250. """
  1251. return await self.api_request(
  1252. 'editMessageReplyMarkup',
  1253. parameters=locals()
  1254. )
  1255. async def stopPoll(self, chat_id: Union[int, str], message_id,
  1256. reply_markup=None):
  1257. """Stop a poll which was sent by the bot.
  1258. On success, the stopped Poll with the final results is returned.
  1259. `reply_markup` type may be only `InlineKeyboardMarkup`.
  1260. See https://core.telegram.org/bots/api#stoppoll for details.
  1261. """
  1262. return await self.api_request(
  1263. 'stopPoll',
  1264. parameters=locals()
  1265. )
  1266. async def deleteMessage(self, chat_id: Union[int, str], message_id):
  1267. """Delete a message, including service messages.
  1268. - A message can only be deleted if it was sent less than 48 hours
  1269. ago.
  1270. - Bots can delete outgoing messages in private chats, groups, and
  1271. supergroups.
  1272. - Bots can delete incoming messages in private chats.
  1273. - Bots granted can_post_messages permissions can delete outgoing
  1274. messages in channels.
  1275. - If the bot is an administrator of a group, it can delete any
  1276. message there.
  1277. - If the bot has can_delete_messages permission in a supergroup or
  1278. a channel, it can delete any message there.
  1279. Returns True on success.
  1280. See https://core.telegram.org/bots/api#deletemessage for details.
  1281. """
  1282. return await self.api_request(
  1283. 'deleteMessage',
  1284. parameters=locals()
  1285. )
  1286. async def sendSticker(self, chat_id: Union[int, str],
  1287. sticker: Union[str, dict, IO],
  1288. disable_notification: bool = None,
  1289. reply_to_message_id: int = None,
  1290. allow_sending_without_reply: bool = None,
  1291. message_thread_id: int = None,
  1292. protect_content: bool = None,
  1293. reply_markup=None):
  1294. """Send `.webp` stickers.
  1295. On success, the sent Message is returned.
  1296. See https://core.telegram.org/bots/api#sendsticker for details.
  1297. """
  1298. sticker = self.prepare_file_object(sticker)
  1299. if sticker is None:
  1300. logging.error("Invalid sticker provided!")
  1301. return
  1302. result = await self.api_request(
  1303. 'sendSticker',
  1304. parameters=locals()
  1305. )
  1306. if type(sticker) is dict: # Close sticker file, if it was open
  1307. sticker['file'].close()
  1308. return result
  1309. async def getStickerSet(self, name):
  1310. """Get a sticker set.
  1311. On success, a StickerSet object is returned.
  1312. See https://core.telegram.org/bots/api#getstickerset for details.
  1313. """
  1314. return await self.api_request(
  1315. 'getStickerSet',
  1316. parameters=locals()
  1317. )
  1318. async def uploadStickerFile(self, user_id, png_sticker):
  1319. """Upload a .png file as a sticker.
  1320. Use it later via `createNewStickerSet` and `addStickerToSet` methods
  1321. (can be used multiple times).
  1322. Return the uploaded File on success.
  1323. `png_sticker` must be a *.png image up to 512 kilobytes in size,
  1324. dimensions must not exceed 512px, and either width or height must
  1325. be exactly 512px.
  1326. See https://core.telegram.org/bots/api#uploadstickerfile for details.
  1327. """
  1328. return await self.api_request(
  1329. 'uploadStickerFile',
  1330. parameters=locals()
  1331. )
  1332. async def createNewStickerSet(self, user_id: int, name: str, title: str,
  1333. emojis: str,
  1334. png_sticker: Union[str, dict, IO] = None,
  1335. tgs_sticker: Union[str, dict, IO] = None,
  1336. webm_sticker: Union[str, dict, IO] = None,
  1337. sticker_type: str = 'regular',
  1338. mask_position: dict = None,
  1339. **kwargs):
  1340. """Create new sticker set owned by a user.
  1341. The bot will be able to edit the created sticker set.
  1342. Returns True on success.
  1343. See https://core.telegram.org/bots/api#createnewstickerset for details.
  1344. """
  1345. if 'contains_masks' in kwargs:
  1346. logging.error("Parameter `contains_masks` of method "
  1347. "`createNewStickerSet` has been deprecated. "
  1348. "Use `sticker_type = 'mask'` instead.")
  1349. sticker_type = 'mask' if kwargs['contains_masks'] else 'regular'
  1350. if sticker_type not in ('regular', 'mask'):
  1351. raise TypeError
  1352. png_sticker = self.prepare_file_object(png_sticker)
  1353. tgs_sticker = self.prepare_file_object(tgs_sticker)
  1354. webm_sticker = self.prepare_file_object(webm_sticker)
  1355. if png_sticker is None and tgs_sticker is None and webm_sticker is None:
  1356. logging.error("Invalid sticker provided!")
  1357. return
  1358. result = await self.api_request(
  1359. 'createNewStickerSet',
  1360. parameters=locals()
  1361. )
  1362. if type(png_sticker) is dict: # Close png_sticker file, if it was open
  1363. png_sticker['file'].close()
  1364. if type(tgs_sticker) is dict: # Close tgs_sticker file, if it was open
  1365. tgs_sticker['file'].close()
  1366. if type(webm_sticker) is dict: # Close webm_sticker file, if it was open
  1367. webm_sticker['file'].close()
  1368. return result
  1369. async def addStickerToSet(self, user_id: int, name: str,
  1370. emojis: str,
  1371. png_sticker: Union[str, dict, IO] = None,
  1372. tgs_sticker: Union[str, dict, IO] = None,
  1373. webm_sticker: Union[str, dict, IO] = None,
  1374. mask_position: dict = None):
  1375. """Add a new sticker to a set created by the bot.
  1376. Returns True on success.
  1377. See https://core.telegram.org/bots/api#addstickertoset for details.
  1378. """
  1379. png_sticker = self.prepare_file_object(png_sticker)
  1380. tgs_sticker = self.prepare_file_object(tgs_sticker)
  1381. webm_sticker = self.prepare_file_object(webm_sticker)
  1382. if png_sticker is None and tgs_sticker is None and webm_sticker is None:
  1383. logging.error("Invalid sticker provided!")
  1384. return
  1385. result = await self.api_request(
  1386. 'addStickerToSet',
  1387. parameters=locals()
  1388. )
  1389. if type(png_sticker) is dict: # Close png_sticker file, if it was open
  1390. png_sticker['file'].close()
  1391. if type(tgs_sticker) is dict: # Close tgs_sticker file, if it was open
  1392. tgs_sticker['file'].close()
  1393. if type(webm_sticker) is dict: # Close webm_sticker file, if it was open
  1394. webm_sticker['file'].close()
  1395. return result
  1396. async def setStickerPositionInSet(self, sticker, position):
  1397. """Move a sticker in a set created by the bot to a specific position .
  1398. Position is 0-based.
  1399. Returns True on success.
  1400. See https://core.telegram.org/bots/api#setstickerpositioninset for
  1401. details.
  1402. """
  1403. return await self.api_request(
  1404. 'setStickerPositionInSet',
  1405. parameters=locals()
  1406. )
  1407. async def deleteStickerFromSet(self, sticker):
  1408. """Delete a sticker from a set created by the bot.
  1409. Returns True on success.
  1410. See https://core.telegram.org/bots/api#deletestickerfromset for
  1411. details.
  1412. """
  1413. return await self.api_request(
  1414. 'deleteStickerFromSet',
  1415. parameters=locals()
  1416. )
  1417. async def answerInlineQuery(self, inline_query_id, results,
  1418. cache_time=None,
  1419. is_personal=None,
  1420. next_offset=None,
  1421. switch_pm_text=None,
  1422. switch_pm_parameter=None):
  1423. """Send answers to an inline query.
  1424. On success, True is returned.
  1425. No more than 50 results per query are allowed.
  1426. See https://core.telegram.org/bots/api#answerinlinequery for details.
  1427. """
  1428. return await self.api_request(
  1429. 'answerInlineQuery',
  1430. parameters=locals()
  1431. )
  1432. async def sendInvoice(self, chat_id: int, title: str, description: str,
  1433. payload: str, provider_token: str,
  1434. start_parameter: str,
  1435. currency: str, prices: List[dict],
  1436. message_thread_id: int = None,
  1437. protect_content: bool = None,
  1438. max_tip_amount: int = None,
  1439. suggested_tip_amounts: List[int] = None,
  1440. provider_data: str = None,
  1441. photo_url: str = None,
  1442. photo_size: int = None,
  1443. photo_width: int = None,
  1444. photo_height: int = None,
  1445. need_name: bool = None,
  1446. need_phone_number: bool = None,
  1447. need_email: bool = None,
  1448. need_shipping_address: bool = None,
  1449. send_phone_number_to_provider: bool = None,
  1450. send_email_to_provider: bool = None,
  1451. is_flexible: bool = None,
  1452. disable_notification: bool = None,
  1453. reply_to_message_id: int = None,
  1454. allow_sending_without_reply: bool = None,
  1455. reply_markup=None):
  1456. """Send an invoice.
  1457. On success, the sent Message is returned.
  1458. See https://core.telegram.org/bots/api#sendinvoice for details.
  1459. """
  1460. return await self.api_request(
  1461. 'sendInvoice',
  1462. parameters=locals()
  1463. )
  1464. async def answerShippingQuery(self, shipping_query_id, ok,
  1465. shipping_options=None,
  1466. error_message=None):
  1467. """Reply to shipping queries.
  1468. On success, True is returned.
  1469. If you sent an invoice requesting a shipping address and the parameter
  1470. is_flexible was specified, the Bot API will send an Update with a
  1471. shipping_query field to the bot.
  1472. See https://core.telegram.org/bots/api#answershippingquery for details.
  1473. """
  1474. return await self.api_request(
  1475. 'answerShippingQuery',
  1476. parameters=locals()
  1477. )
  1478. async def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
  1479. error_message=None):
  1480. """Respond to pre-checkout queries.
  1481. Once the user has confirmed their payment and shipping details, the Bot
  1482. API sends the final confirmation in the form of an Update with the
  1483. field pre_checkout_query.
  1484. On success, True is returned.
  1485. Note: The Bot API must receive an answer within 10 seconds after the
  1486. pre-checkout query was sent.
  1487. See https://core.telegram.org/bots/api#answerprecheckoutquery for
  1488. details.
  1489. """
  1490. return await self.api_request(
  1491. 'answerPreCheckoutQuery',
  1492. parameters=locals()
  1493. )
  1494. async def setPassportDataErrors(self, user_id, errors):
  1495. """Refuse a Telegram Passport element with `errors`.
  1496. Inform a user that some of the Telegram Passport elements they provided
  1497. contains errors.
  1498. The user will not be able to re-submit their Passport to you until the
  1499. errors are fixed (the contents of the field for which you returned
  1500. the error must change).
  1501. Returns True on success.
  1502. Use this if the data submitted by the user doesn't satisfy the
  1503. standards your service requires for any reason.
  1504. For example, if a birthday date seems invalid, a submitted document
  1505. is blurry, a scan shows evidence of tampering, etc.
  1506. Supply some details in the error message to make sure the user knows
  1507. how to correct the issues.
  1508. See https://core.telegram.org/bots/api#setpassportdataerrors for
  1509. details.
  1510. """
  1511. return await self.api_request(
  1512. 'setPassportDataErrors',
  1513. parameters=locals()
  1514. )
  1515. async def sendGame(self, chat_id: Union[int, str], game_short_name,
  1516. message_thread_id: int = None,
  1517. protect_content: bool = None,
  1518. disable_notification: bool = None,
  1519. reply_to_message_id: int = None,
  1520. reply_markup=None,
  1521. allow_sending_without_reply: bool = None):
  1522. """Send a game.
  1523. On success, the sent Message is returned.
  1524. See https://core.telegram.org/bots/api#sendgame for
  1525. details.
  1526. """
  1527. return await self.api_request(
  1528. 'sendGame',
  1529. parameters=locals()
  1530. )
  1531. async def setGameScore(self, user_id: int, score: int,
  1532. force: bool = None,
  1533. disable_edit_message: bool = None,
  1534. chat_id: Union[int, str] = None,
  1535. message_id: int = None,
  1536. inline_message_id: str = None):
  1537. """Set the score of the specified user in a game.
  1538. On success, if the message was sent by the bot, returns the edited
  1539. Message, otherwise returns True.
  1540. Returns an error, if the new score is not greater than the user's
  1541. current score in the chat and force is False.
  1542. See https://core.telegram.org/bots/api#setgamescore for
  1543. details.
  1544. """
  1545. return await self.api_request(
  1546. 'setGameScore',
  1547. parameters=locals()
  1548. )
  1549. async def getGameHighScores(self, user_id,
  1550. chat_id: Union[int, str] = None,
  1551. message_id: int = None,
  1552. inline_message_id: str = None):
  1553. """Get data for high score tables.
  1554. Will return the score of the specified user and several of his
  1555. neighbors in a game.
  1556. On success, returns an Array of GameHighScore objects.
  1557. This method will currently return scores for the target user, plus two
  1558. of his closest neighbors on each side. Will also return the top
  1559. three users if the user and his neighbors are not among them.
  1560. Please note that this behavior is subject to change.
  1561. See https://core.telegram.org/bots/api#getgamehighscores for
  1562. details.
  1563. """
  1564. return await self.api_request(
  1565. 'getGameHighScores',
  1566. parameters=locals()
  1567. )
  1568. async def sendDice(self,
  1569. chat_id: Union[int, str] = None,
  1570. emoji: str = None,
  1571. disable_notification: bool = None,
  1572. reply_to_message_id: int = None,
  1573. allow_sending_without_reply: bool = None,
  1574. message_thread_id: int = None,
  1575. protect_content: bool = None,
  1576. reply_markup=None):
  1577. """Send a dice.
  1578. Use this method to send a dice, which will have a random value from 1
  1579. to 6.
  1580. On success, the sent Message is returned.
  1581. (Yes, we're aware of the “proper” singular of die. But it's awkward,
  1582. and we decided to help it change. One dice at a time!)
  1583. See https://core.telegram.org/bots/api#senddice for
  1584. details.
  1585. """
  1586. return await self.api_request(
  1587. 'sendDice',
  1588. parameters=locals()
  1589. )
  1590. async def setChatAdministratorCustomTitle(self,
  1591. chat_id: Union[int, str] = None,
  1592. user_id: int = None,
  1593. custom_title: str = None):
  1594. """Set a custom title for an administrator.
  1595. Use this method to set a custom title for an administrator in a
  1596. supergroup promoted by the bot.
  1597. Returns True on success.
  1598. See https://core.telegram.org/bots/api#setchatadministratorcustomtitle
  1599. for details.
  1600. """
  1601. return await self.api_request(
  1602. 'setChatAdministratorCustomTitle',
  1603. parameters=locals()
  1604. )
  1605. async def setChatPermissions(self,
  1606. chat_id: Union[int, str] = None,
  1607. permissions: Union[ChatPermissions,
  1608. dict] = None):
  1609. """Set default chat permissions for all members.
  1610. Use this method to set default chat permissions for all members.
  1611. The bot must be an administrator in the group or a supergroup for this
  1612. to work and must have the can_restrict_members admin rights.
  1613. Returns True on success.
  1614. See https://core.telegram.org/bots/api#setchatpermissions for details.
  1615. """
  1616. return await self.api_request(
  1617. 'setChatPermissions',
  1618. parameters=locals()
  1619. )
  1620. async def setMyCommands(self,
  1621. commands: List[Union[Command, dict]],
  1622. scope: 'BotCommandScope' = None,
  1623. language_code: str = None):
  1624. """Change the list of the bot's commands.
  1625. Use this method to change the list of the bot's commands.
  1626. Returns True on success.
  1627. See https://core.telegram.org/bots/api#setmycommands for details.
  1628. """
  1629. return await self.api_request(
  1630. 'setMyCommands',
  1631. parameters=locals()
  1632. )
  1633. async def getMyCommands(self,
  1634. scope: 'BotCommandScope' = None,
  1635. language_code: str = None):
  1636. """Get the current list of the bot's commands.
  1637. Use this method to get the current list of the bot's commands for
  1638. the given scope and user language.
  1639. Returns an Array of BotCommand objects.
  1640. If commands aren't set, an empty list is returned.
  1641. See https://core.telegram.org/bots/api#getmycommands for details.
  1642. """
  1643. return await self.api_request(
  1644. 'getMyCommands',
  1645. parameters=locals()
  1646. )
  1647. async def setStickerSetThumb(self,
  1648. name: str = None,
  1649. user_id: int = None,
  1650. thumb=None):
  1651. """Set the thumbnail of a sticker set.
  1652. Use this method to set the thumbnail of a sticker set.
  1653. Animated thumbnails can be set for animated sticker sets only.
  1654. Returns True on success.
  1655. See https://core.telegram.org/bots/api#setstickersetthumb for details.
  1656. """
  1657. return await self.api_request(
  1658. 'setStickerSetThumb',
  1659. parameters=locals()
  1660. )
  1661. async def logOut(self):
  1662. """Log out from the cloud Bot API server.
  1663. Use this method to log out from the cloud Bot API server
  1664. before launching the bot locally.
  1665. You must log out the bot before running it locally, otherwise there
  1666. is no guarantee that the bot will receive updates.
  1667. After a successful call, you can immediately log in on a local server,
  1668. but will not be able to log in back to the cloud Bot API server
  1669. for 10 minutes.
  1670. Returns True on success. Requires no parameters.
  1671. See https://core.telegram.org/bots/api#logout for details.
  1672. """
  1673. return await self.api_request(
  1674. 'logOut',
  1675. parameters=locals()
  1676. )
  1677. async def close(self):
  1678. """Close bot instance in local server.
  1679. Use this method to close the bot instance before moving it from one
  1680. local server to another.
  1681. You need to delete the webhook before calling this method to ensure
  1682. that the bot isn't launched again after server restart.
  1683. The method will return error 429 in the first 10 minutes after the
  1684. bot is launched. Returns True on success.
  1685. Requires no parameters.
  1686. See https://core.telegram.org/bots/api#close for details.
  1687. """
  1688. return await self.api_request(
  1689. 'close',
  1690. parameters=locals()
  1691. )
  1692. async def copyMessage(self, chat_id: Union[int, str],
  1693. from_chat_id: Union[int, str],
  1694. message_id: int,
  1695. message_thread_id: int = None,
  1696. protect_content: bool = None,
  1697. caption: str = None,
  1698. parse_mode: str = None,
  1699. caption_entities: list = None,
  1700. disable_notification: bool = None,
  1701. reply_to_message_id: int = None,
  1702. allow_sending_without_reply: bool = None,
  1703. reply_markup=None):
  1704. """Use this method to copy messages of any kind.
  1705. The method is analogous to the method forwardMessages, but the copied
  1706. message doesn't have a link to the original message.
  1707. Returns the MessageId of the sent message on success.
  1708. See https://core.telegram.org/bots/api#copymessage for details.
  1709. """
  1710. return await self.api_request(
  1711. 'copyMessage',
  1712. parameters=locals()
  1713. )
  1714. async def unpinAllChatMessages(self, chat_id: Union[int, str]):
  1715. """Use this method to clear the list of pinned messages in a chat.
  1716. If the chat is not a private chat, the bot must be an administrator
  1717. in the chat for this to work and must have the 'can_pin_messages'
  1718. admin right in a supergroup or 'can_edit_messages' admin right in a
  1719. channel.
  1720. Returns True on success.
  1721. See https://core.telegram.org/bots/api#unpinallchatmessages for details.
  1722. """
  1723. return await self.api_request(
  1724. 'unpinAllChatMessages',
  1725. parameters=locals()
  1726. )
  1727. async def banChatMember(self, chat_id: Union[int, str],
  1728. user_id: int, until_date: int,
  1729. revoke_messages: bool):
  1730. """Use this method to ban a user in a group, a supergroup or a channel.
  1731. In the case of supergroups and channels, the user will not be able to
  1732. return to the chat on their own using invite links, etc., unless
  1733. unbanned first.
  1734. The bot must be an administrator in the chat for this to work and must
  1735. have the appropriate administrator rights.
  1736. Returns True on success.
  1737. See https://core.telegram.org/bots/api#banchatmember for details.
  1738. """
  1739. return await self.api_request(
  1740. 'banChatMember',
  1741. parameters=locals()
  1742. )
  1743. async def banChatSenderChat(self, chat_id: Union[int, str], sender_chat_id: int):
  1744. """Use this method to ban a channel chat in a supergroup or a channel.
  1745. Until the chat is unbanned, the owner of the banned chat won't be able
  1746. to send messages on behalf of any of their channels.
  1747. The bot must be an administrator in the supergroup or channel for this
  1748. to work and must have the appropriate administrator rights.
  1749. Returns True on success.
  1750. See https://core.telegram.org/bots/api#banchatsenderchat for details.
  1751. """
  1752. return await self.api_request(
  1753. 'banChatSenderChat',
  1754. parameters=locals()
  1755. )
  1756. async def unbanChatSenderChat(self, chat_id: Union[int, str], sender_chat_id: int):
  1757. """Use this method to unban a previously banned channel chat in a supergroup or channel.
  1758. The bot must be an administrator for this to work and must have the
  1759. appropriate administrator rights.
  1760. Returns True on success.
  1761. See https://core.telegram.org/bots/api#unbanchatsenderchat for details.
  1762. """
  1763. return await self.api_request(
  1764. 'unbanChatSenderChat',
  1765. parameters=locals()
  1766. )
  1767. async def createChatInviteLink(self, chat_id: Union[int, str], name: str,
  1768. expire_date: int, member_limit: int,
  1769. creates_join_request: bool):
  1770. """Use this method to create an additional invite link for a chat.
  1771. The bot must be an administrator in the chat for this to work and must
  1772. have the appropriate administrator rights.
  1773. The link can be revoked using the method revokeChatInviteLink.
  1774. Returns the new invite link as ChatInviteLink object.
  1775. See https://core.telegram.org/bots/api#createchatinvitelink for details.
  1776. """
  1777. return await self.api_request(
  1778. 'createChatInviteLink',
  1779. parameters=locals()
  1780. )
  1781. async def editChatInviteLink(self, chat_id: Union[int, str],
  1782. invite_link: str, name: str, expire_date: int,
  1783. member_limit: int, creates_join_request: bool):
  1784. """Use this method to edit a non-primary invite link created by the bot.
  1785. The bot must be an administrator in the chat for this to work and must
  1786. have the appropriate administrator rights.
  1787. Returns the edited invite link as a ChatInviteLink object.
  1788. See https://core.telegram.org/bots/api#editchatinvitelink for details.
  1789. """
  1790. return await self.api_request(
  1791. 'editChatInviteLink',
  1792. parameters=locals()
  1793. )
  1794. async def revokeChatInviteLink(self, chat_id: Union[int, str], invite_link: str):
  1795. """Use this method to revoke an invite link created by the bot.
  1796. If the primary link is revoked, a new link is automatically generated.
  1797. The bot must be an administrator in the chat for this to work and must
  1798. have the appropriate administrator rights.
  1799. Returns the revoked invite link as ChatInviteLink object.
  1800. See https://core.telegram.org/bots/api#revokechatinvitelink for details.
  1801. """
  1802. return await self.api_request(
  1803. 'revokeChatInviteLink',
  1804. parameters=locals()
  1805. )
  1806. async def approveChatJoinRequest(self, chat_id: Union[int, str], user_id: int):
  1807. """Use this method to approve a chat join request.
  1808. The bot must be an administrator in the chat for this to work and must
  1809. have the can_invite_users administrator right.
  1810. Returns True on success.
  1811. See https://core.telegram.org/bots/api#approvechatjoinrequest for details.
  1812. """
  1813. return await self.api_request(
  1814. 'approveChatJoinRequest',
  1815. parameters=locals()
  1816. )
  1817. async def declineChatJoinRequest(self, chat_id: Union[int, str], user_id: int):
  1818. """Use this method to decline a chat join request.
  1819. The bot must be an administrator in the chat for this to work and must
  1820. have the can_invite_users administrator right.
  1821. Returns True on success.
  1822. See https://core.telegram.org/bots/api#declinechatjoinrequest for details.
  1823. """
  1824. return await self.api_request(
  1825. 'declineChatJoinRequest',
  1826. parameters=locals()
  1827. )
  1828. async def getChatMemberCount(self, chat_id: Union[int, str]):
  1829. """Use this method to get the number of members in a chat. Returns Int on success.
  1830. See https://core.telegram.org/bots/api#getchatmembercount for details.
  1831. """
  1832. return await self.api_request(
  1833. 'getChatMemberCount',
  1834. parameters=locals()
  1835. )
  1836. async def getForumTopicIconStickers(self):
  1837. """Use this method to get custom emoji stickers.
  1838. They can be used as a forum topic icon by any user.
  1839. Requires no parameters. Returns an Array of Sticker objects.
  1840. See https://core.telegram.org/bots/api#getforumtopiciconstickers for details.
  1841. """
  1842. return await self.api_request(
  1843. 'getForumTopicIconStickers',
  1844. parameters=locals()
  1845. )
  1846. async def createForumTopic(self, chat_id: Union[int, str], name: str,
  1847. icon_color: int, icon_custom_emoji_id: str):
  1848. """Use this method to create a topic in a forum supergroup chat.
  1849. The bot must be an administrator in the chat for this to work and must
  1850. have the can_manage_topics administrator rights.
  1851. Returns information about the created topic as a ForumTopic object.
  1852. See https://core.telegram.org/bots/api#createforumtopic for details.
  1853. """
  1854. return await self.api_request(
  1855. 'createForumTopic',
  1856. parameters=locals()
  1857. )
  1858. async def editForumTopic(self, chat_id: Union[int, str],
  1859. message_thread_id: int, name: str,
  1860. icon_custom_emoji_id: str):
  1861. """Use this method to edit name and icon of a topic in a forum supergroup chat.
  1862. The bot must be an administrator in the chat for this to work and must
  1863. have can_manage_topics administrator rights, unless it is the
  1864. creator of the topic.
  1865. Returns True on success.
  1866. See https://core.telegram.org/bots/api#editforumtopic for details.
  1867. """
  1868. return await self.api_request(
  1869. 'editForumTopic',
  1870. parameters=locals()
  1871. )
  1872. async def closeForumTopic(self, chat_id: Union[int, str],
  1873. message_thread_id: int):
  1874. """Use this method to close an open topic in a forum supergroup chat.
  1875. The bot must be an administrator in the chat for this to work and must
  1876. have the can_manage_topics administrator rights, unless it is the
  1877. creator of the topic.
  1878. Returns True on success.
  1879. See https://core.telegram.org/bots/api#closeforumtopic for details.
  1880. """
  1881. return await self.api_request(
  1882. 'closeForumTopic',
  1883. parameters=locals()
  1884. )
  1885. async def reopenForumTopic(self, chat_id: Union[int, str],
  1886. message_thread_id: int):
  1887. """Use this method to reopen a closed topic in a forum supergroup chat.
  1888. The bot must be an administrator in the chat for this to work and must
  1889. have the can_manage_topics administrator rights, unless it is the
  1890. creator of the topic.
  1891. Returns True on success.
  1892. See https://core.telegram.org/bots/api#reopenforumtopic for details.
  1893. """
  1894. return await self.api_request(
  1895. 'reopenForumTopic',
  1896. parameters=locals()
  1897. )
  1898. async def deleteForumTopic(self, chat_id: Union[int, str],
  1899. message_thread_id: int):
  1900. """Use this method to delete a forum topic.
  1901. This method deletes a forum topic along with all its messages in a
  1902. forum supergroup chat.
  1903. The bot must be an administrator in the chat for this to work and must
  1904. have the can_delete_messages administrator rights.
  1905. Returns True on success.
  1906. See https://core.telegram.org/bots/api#deleteforumtopic for details.
  1907. """
  1908. return await self.api_request(
  1909. 'deleteForumTopic',
  1910. parameters=locals()
  1911. )
  1912. async def unpinAllForumTopicMessages(self, chat_id: Union[int, str],
  1913. message_thread_id: int):
  1914. """Use this method to clear the list of pinned messages in a forum topic.
  1915. The bot must be an administrator in the chat for this to work and must
  1916. have the can_pin_messages administrator right in the supergroup.
  1917. Returns True on success.
  1918. See https://core.telegram.org/bots/api#unpinallforumtopicmessages for details.
  1919. """
  1920. return await self.api_request(
  1921. 'unpinAllForumTopicMessages',
  1922. parameters=locals()
  1923. )
  1924. async def deleteMyCommands(self, scope: 'BotCommandScope', language_code: str):
  1925. """Use this method to delete the list of the bot's commands for the given scope and user language.
  1926. After deletion, higher level commands will be shown to affected users.
  1927. Returns True on success.
  1928. See https://core.telegram.org/bots/api#deletemycommands for details.
  1929. """
  1930. return await self.api_request(
  1931. 'deleteMyCommands',
  1932. parameters=locals()
  1933. )
  1934. async def setChatMenuButton(self, chat_id: int, menu_button: 'MenuButton'):
  1935. """Use this method to change the bot's menu button in a private chat, or the default menu button.
  1936. Returns True on success.
  1937. See https://core.telegram.org/bots/api#setchatmenubutton for details.
  1938. """
  1939. return await self.api_request(
  1940. 'setChatMenuButton',
  1941. parameters=locals()
  1942. )
  1943. async def getChatMenuButton(self, chat_id: int):
  1944. """Use this method to get the current value of the bot's menu button.
  1945. Use this method to get the current value of the bot's menu button in a
  1946. private chat, or the default menu button.
  1947. Returns MenuButton on success.
  1948. See https://core.telegram.org/bots/api#getchatmenubutton for details.
  1949. """
  1950. return await self.api_request(
  1951. 'getChatMenuButton',
  1952. parameters=locals()
  1953. )
  1954. async def setMyDefaultAdministratorRights(self,
  1955. rights: 'ChatAdministratorRights',
  1956. for_channels: bool):
  1957. """Use this method to change the default administrator rights.
  1958. Use this method to change the default administrator rights requested by
  1959. the bot when it's added as an administrator to groups or channels.
  1960. These rights will be suggested to users, but they are free to modify
  1961. the list before adding the bot.
  1962. Returns True on success.
  1963. See https://core.telegram.org/bots/api#setmydefaultadministratorrights for details.
  1964. """
  1965. return await self.api_request(
  1966. 'setMyDefaultAdministratorRights',
  1967. parameters=locals()
  1968. )
  1969. async def getMyDefaultAdministratorRights(self, for_channels: bool):
  1970. """Use this method to get the current default administrator rights of
  1971. the bot.
  1972. Returns ChatAdministratorRights on success.
  1973. See https://core.telegram.org/bots/api#getmydefaultadministratorrights for details.
  1974. """
  1975. return await self.api_request(
  1976. 'getMyDefaultAdministratorRights',
  1977. parameters=locals()
  1978. )
  1979. async def getCustomEmojiStickers(self, custom_emoji_ids: List[str]):
  1980. """Use this method to get information about custom emoji stickers by their identifiers.
  1981. Returns an Array of Sticker objects.
  1982. See https://core.telegram.org/bots/api#getcustomemojistickers for details.
  1983. """
  1984. return await self.api_request(
  1985. 'getCustomEmojiStickers',
  1986. parameters=locals()
  1987. )
  1988. async def answerWebAppQuery(self, web_app_query_id: str,
  1989. result: 'InlineQueryResult'):
  1990. """Use this method to set the result of an interaction with a Web App.
  1991. Use this method to set the result of an interaction with a Web App and
  1992. send a corresponding message on behalf of the user to the chat from
  1993. which the query originated.
  1994. On success, a SentWebAppMessage object is returned.
  1995. See https://core.telegram.org/bots/api#answerwebappquery for details.
  1996. """
  1997. return await self.api_request(
  1998. 'answerWebAppQuery',
  1999. parameters=locals()
  2000. )
  2001. async def createInvoiceLink(self, title: str, description: str,
  2002. payload: str, provider_token: str,
  2003. currency: str, prices: List['LabeledPrice'],
  2004. max_tip_amount: int,
  2005. suggested_tip_amounts: List[int],
  2006. provider_data: str, photo_url: str,
  2007. photo_size: int, photo_width: int,
  2008. photo_height: int, need_name: bool,
  2009. need_phone_number: bool, need_email: bool,
  2010. need_shipping_address: bool,
  2011. send_phone_number_to_provider: bool,
  2012. send_email_to_provider: bool,
  2013. is_flexible: bool):
  2014. """Use this method to create a link for an invoice.
  2015. Returns the created invoice link as String on success.
  2016. See https://core.telegram.org/bots/api#createinvoicelink for details.
  2017. """
  2018. return await self.api_request(
  2019. 'createInvoiceLink',
  2020. parameters=locals()
  2021. )