id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
224,700 | aiogram/aiogram | aiogram/types/message.py | Message.get_command | def get_command(self, pure=False):
"""
Get command from message
:return:
"""
command = self.get_full_command()
if command:
command = command[0]
if pure:
command, _, _ = command[1:].partition('@')
return command | python | def get_command(self, pure=False):
"""
Get command from message
:return:
"""
command = self.get_full_command()
if command:
command = command[0]
if pure:
command, _, _ = command[1:].partition('@')
return command | [
"def",
"get_command",
"(",
"self",
",",
"pure",
"=",
"False",
")",
":",
"command",
"=",
"self",
".",
"get_full_command",
"(",
")",
"if",
"command",
":",
"command",
"=",
"command",
"[",
"0",
"]",
"if",
"pure",
":",
"command",
",",
"_",
",",
"_",
"="... | Get command from message
:return: | [
"Get",
"command",
"from",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L166-L177 |
224,701 | aiogram/aiogram | aiogram/types/message.py | Message.parse_entities | def parse_entities(self, as_html=True):
"""
Text or caption formatted as HTML or Markdown.
:return: str
"""
text = self.text or self.caption
if text is None:
raise TypeError("This message doesn't have any text.")
quote_fn = md.quote_html if as_html else md.escape_md
entities = self.entities or self.caption_entities
if not entities:
return quote_fn(text)
if not sys.maxunicode == 0xffff:
text = text.encode('utf-16-le')
result = ''
offset = 0
for entity in sorted(entities, key=lambda item: item.offset):
entity_text = entity.parse(text, as_html=as_html)
if sys.maxunicode == 0xffff:
part = text[offset:entity.offset]
result += quote_fn(part) + entity_text
else:
part = text[offset * 2:entity.offset * 2]
result += quote_fn(part.decode('utf-16-le')) + entity_text
offset = entity.offset + entity.length
if sys.maxunicode == 0xffff:
part = text[offset:]
result += quote_fn(part)
else:
part = text[offset * 2:]
result += quote_fn(part.decode('utf-16-le'))
return result | python | def parse_entities(self, as_html=True):
"""
Text or caption formatted as HTML or Markdown.
:return: str
"""
text = self.text or self.caption
if text is None:
raise TypeError("This message doesn't have any text.")
quote_fn = md.quote_html if as_html else md.escape_md
entities = self.entities or self.caption_entities
if not entities:
return quote_fn(text)
if not sys.maxunicode == 0xffff:
text = text.encode('utf-16-le')
result = ''
offset = 0
for entity in sorted(entities, key=lambda item: item.offset):
entity_text = entity.parse(text, as_html=as_html)
if sys.maxunicode == 0xffff:
part = text[offset:entity.offset]
result += quote_fn(part) + entity_text
else:
part = text[offset * 2:entity.offset * 2]
result += quote_fn(part.decode('utf-16-le')) + entity_text
offset = entity.offset + entity.length
if sys.maxunicode == 0xffff:
part = text[offset:]
result += quote_fn(part)
else:
part = text[offset * 2:]
result += quote_fn(part.decode('utf-16-le'))
return result | [
"def",
"parse_entities",
"(",
"self",
",",
"as_html",
"=",
"True",
")",
":",
"text",
"=",
"self",
".",
"text",
"or",
"self",
".",
"caption",
"if",
"text",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"This message doesn't have any text.\"",
")",
"quote_fn... | Text or caption formatted as HTML or Markdown.
:return: str | [
"Text",
"or",
"caption",
"formatted",
"as",
"HTML",
"or",
"Markdown",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L189-L231 |
224,702 | aiogram/aiogram | aiogram/types/message.py | Message.url | def url(self) -> str:
"""
Get URL for the message
:return: str
"""
if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]:
raise TypeError('Invalid chat type!')
elif not self.chat.username:
raise TypeError('This chat does not have @username')
return f"https://t.me/{self.chat.username}/{self.message_id}" | python | def url(self) -> str:
"""
Get URL for the message
:return: str
"""
if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]:
raise TypeError('Invalid chat type!')
elif not self.chat.username:
raise TypeError('This chat does not have @username')
return f"https://t.me/{self.chat.username}/{self.message_id}" | [
"def",
"url",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"chat",
".",
"type",
"not",
"in",
"[",
"ChatType",
".",
"SUPER_GROUP",
",",
"ChatType",
".",
"CHANNEL",
"]",
":",
"raise",
"TypeError",
"(",
"'Invalid chat type!'",
")",
"elif",
"not"... | Get URL for the message
:return: str | [
"Get",
"URL",
"for",
"the",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L252-L263 |
224,703 | aiogram/aiogram | aiogram/types/message.py | Message.link | def link(self, text, as_html=True) -> str:
"""
Generate URL for using in text messages with HTML or MD parse mode
:param text: link label
:param as_html: generate as HTML
:return: str
"""
try:
url = self.url
except TypeError: # URL is not accessible
if as_html:
return md.quote_html(text)
return md.escape_md(text)
if as_html:
return md.hlink(text, url)
return md.link(text, url) | python | def link(self, text, as_html=True) -> str:
"""
Generate URL for using in text messages with HTML or MD parse mode
:param text: link label
:param as_html: generate as HTML
:return: str
"""
try:
url = self.url
except TypeError: # URL is not accessible
if as_html:
return md.quote_html(text)
return md.escape_md(text)
if as_html:
return md.hlink(text, url)
return md.link(text, url) | [
"def",
"link",
"(",
"self",
",",
"text",
",",
"as_html",
"=",
"True",
")",
"->",
"str",
":",
"try",
":",
"url",
"=",
"self",
".",
"url",
"except",
"TypeError",
":",
"# URL is not accessible",
"if",
"as_html",
":",
"return",
"md",
".",
"quote_html",
"("... | Generate URL for using in text messages with HTML or MD parse mode
:param text: link label
:param as_html: generate as HTML
:return: str | [
"Generate",
"URL",
"for",
"using",
"in",
"text",
"messages",
"with",
"HTML",
"or",
"MD",
"parse",
"mode"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L265-L282 |
224,704 | aiogram/aiogram | aiogram/types/message.py | Message.answer | async def answer(self, text, parse_mode=None, disable_web_page_preview=None,
disable_notification=None, reply_markup=None, reply=False) -> Message:
"""
Answer to this message
:param text: str
:param parse_mode: str
:param disable_web_page_preview: bool
:param disable_notification: bool
:param reply_markup:
:param reply: fill 'reply_to_message_id'
:return: :class:`aiogram.types.Message`
"""
return await self.bot.send_message(chat_id=self.chat.id, text=text,
parse_mode=parse_mode,
disable_web_page_preview=disable_web_page_preview,
disable_notification=disable_notification,
reply_to_message_id=self.message_id if reply else None,
reply_markup=reply_markup) | python | async def answer(self, text, parse_mode=None, disable_web_page_preview=None,
disable_notification=None, reply_markup=None, reply=False) -> Message:
"""
Answer to this message
:param text: str
:param parse_mode: str
:param disable_web_page_preview: bool
:param disable_notification: bool
:param reply_markup:
:param reply: fill 'reply_to_message_id'
:return: :class:`aiogram.types.Message`
"""
return await self.bot.send_message(chat_id=self.chat.id, text=text,
parse_mode=parse_mode,
disable_web_page_preview=disable_web_page_preview,
disable_notification=disable_notification,
reply_to_message_id=self.message_id if reply else None,
reply_markup=reply_markup) | [
"async",
"def",
"answer",
"(",
"self",
",",
"text",
",",
"parse_mode",
"=",
"None",
",",
"disable_web_page_preview",
"=",
"None",
",",
"disable_notification",
"=",
"None",
",",
"reply_markup",
"=",
"None",
",",
"reply",
"=",
"False",
")",
"->",
"Message",
... | Answer to this message
:param text: str
:param parse_mode: str
:param disable_web_page_preview: bool
:param disable_notification: bool
:param reply_markup:
:param reply: fill 'reply_to_message_id'
:return: :class:`aiogram.types.Message` | [
"Answer",
"to",
"this",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L284-L302 |
224,705 | aiogram/aiogram | aiogram/types/message.py | Message.answer_photo | async def answer_photo(self, photo: typing.Union[base.InputFile, base.String],
caption: typing.Union[base.String, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
reply_markup=None, reply=False) -> Message:
"""
Use this method to send photos.
Source: https://core.telegram.org/bots/api#sendphoto
:param photo: Photo to send.
:type photo: :obj:`typing.Union[base.InputFile, base.String]`
:param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters
:type caption: :obj:`typing.Union[base.String, None]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: :obj:`typing.Union[base.Boolean, None]`
:param reply_markup: Additional interface options.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup,
types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]`
:param reply: fill 'reply_to_message_id'
:return: On success, the sent Message is returned.
:rtype: :obj:`types.Message`
"""
return await self.bot.send_photo(chat_id=self.chat.id, photo=photo, caption=caption,
disable_notification=disable_notification,
reply_to_message_id=self.message_id if reply else None,
reply_markup=reply_markup) | python | async def answer_photo(self, photo: typing.Union[base.InputFile, base.String],
caption: typing.Union[base.String, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
reply_markup=None, reply=False) -> Message:
"""
Use this method to send photos.
Source: https://core.telegram.org/bots/api#sendphoto
:param photo: Photo to send.
:type photo: :obj:`typing.Union[base.InputFile, base.String]`
:param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters
:type caption: :obj:`typing.Union[base.String, None]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: :obj:`typing.Union[base.Boolean, None]`
:param reply_markup: Additional interface options.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup,
types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]`
:param reply: fill 'reply_to_message_id'
:return: On success, the sent Message is returned.
:rtype: :obj:`types.Message`
"""
return await self.bot.send_photo(chat_id=self.chat.id, photo=photo, caption=caption,
disable_notification=disable_notification,
reply_to_message_id=self.message_id if reply else None,
reply_markup=reply_markup) | [
"async",
"def",
"answer_photo",
"(",
"self",
",",
"photo",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"InputFile",
",",
"base",
".",
"String",
"]",
",",
"caption",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"String",
",",
"None",
"]",
"=",
... | Use this method to send photos.
Source: https://core.telegram.org/bots/api#sendphoto
:param photo: Photo to send.
:type photo: :obj:`typing.Union[base.InputFile, base.String]`
:param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters
:type caption: :obj:`typing.Union[base.String, None]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: :obj:`typing.Union[base.Boolean, None]`
:param reply_markup: Additional interface options.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup,
types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]`
:param reply: fill 'reply_to_message_id'
:return: On success, the sent Message is returned.
:rtype: :obj:`types.Message` | [
"Use",
"this",
"method",
"to",
"send",
"photos",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L304-L329 |
224,706 | aiogram/aiogram | aiogram/types/message.py | Message.forward | async def forward(self, chat_id, disable_notification=None) -> Message:
"""
Forward this message
:param chat_id:
:param disable_notification:
:return:
"""
return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification) | python | async def forward(self, chat_id, disable_notification=None) -> Message:
"""
Forward this message
:param chat_id:
:param disable_notification:
:return:
"""
return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification) | [
"async",
"def",
"forward",
"(",
"self",
",",
"chat_id",
",",
"disable_notification",
"=",
"None",
")",
"->",
"Message",
":",
"return",
"await",
"self",
".",
"bot",
".",
"forward_message",
"(",
"chat_id",
",",
"self",
".",
"chat",
".",
"id",
",",
"self",
... | Forward this message
:param chat_id:
:param disable_notification:
:return: | [
"Forward",
"this",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L1322-L1330 |
224,707 | aiogram/aiogram | aiogram/types/message.py | Message.delete | async def delete(self):
"""
Delete this message
:return: bool
"""
return await self.bot.delete_message(self.chat.id, self.message_id) | python | async def delete(self):
"""
Delete this message
:return: bool
"""
return await self.bot.delete_message(self.chat.id, self.message_id) | [
"async",
"def",
"delete",
"(",
"self",
")",
":",
"return",
"await",
"self",
".",
"bot",
".",
"delete_message",
"(",
"self",
".",
"chat",
".",
"id",
",",
"self",
".",
"message_id",
")"
] | Delete this message
:return: bool | [
"Delete",
"this",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L1470-L1476 |
224,708 | aiogram/aiogram | aiogram/utils/callback_data.py | CallbackData.new | def new(self, *args, **kwargs) -> str:
"""
Generate callback data
:param args:
:param kwargs:
:return:
"""
args = list(args)
data = [self.prefix]
for part in self._part_names:
value = kwargs.pop(part, None)
if value is None:
if args:
value = args.pop(0)
else:
raise ValueError(f"Value for '{part}' is not passed!")
if value is not None and not isinstance(value, str):
value = str(value)
if not value:
raise ValueError(f"Value for part {part} can't be empty!'")
elif self.sep in value:
raise ValueError(f"Symbol defined as separator can't be used in values of parts")
data.append(value)
if args or kwargs:
raise TypeError('Too many arguments is passed!')
callback_data = self.sep.join(data)
if len(callback_data) > 64:
raise ValueError('Resulted callback data is too long!')
return callback_data | python | def new(self, *args, **kwargs) -> str:
"""
Generate callback data
:param args:
:param kwargs:
:return:
"""
args = list(args)
data = [self.prefix]
for part in self._part_names:
value = kwargs.pop(part, None)
if value is None:
if args:
value = args.pop(0)
else:
raise ValueError(f"Value for '{part}' is not passed!")
if value is not None and not isinstance(value, str):
value = str(value)
if not value:
raise ValueError(f"Value for part {part} can't be empty!'")
elif self.sep in value:
raise ValueError(f"Symbol defined as separator can't be used in values of parts")
data.append(value)
if args or kwargs:
raise TypeError('Too many arguments is passed!')
callback_data = self.sep.join(data)
if len(callback_data) > 64:
raise ValueError('Resulted callback data is too long!')
return callback_data | [
"def",
"new",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"args",
"=",
"list",
"(",
"args",
")",
"data",
"=",
"[",
"self",
".",
"prefix",
"]",
"for",
"part",
"in",
"self",
".",
"_part_names",
":",
"value",
"="... | Generate callback data
:param args:
:param kwargs:
:return: | [
"Generate",
"callback",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/callback_data.py#L44-L81 |
224,709 | aiogram/aiogram | examples/webhook_example.py | cmd_id | async def cmd_id(message: types.Message):
"""
Return info about user.
"""
if message.reply_to_message:
target = message.reply_to_message.from_user
chat = message.chat
elif message.forward_from and message.chat.type == ChatType.PRIVATE:
target = message.forward_from
chat = message.forward_from or message.chat
else:
target = message.from_user
chat = message.chat
result_msg = [hbold('Info about user:'),
f"First name: {target.first_name}"]
if target.last_name:
result_msg.append(f"Last name: {target.last_name}")
if target.username:
result_msg.append(f"Username: {target.mention}")
result_msg.append(f"User ID: {target.id}")
result_msg.extend([hbold('Chat:'),
f"Type: {chat.type}",
f"Chat ID: {chat.id}"])
if chat.type != ChatType.PRIVATE:
result_msg.append(f"Title: {chat.title}")
else:
result_msg.append(f"Title: {chat.full_name}")
return SendMessage(message.chat.id, '\n'.join(result_msg), reply_to_message_id=message.message_id,
parse_mode=ParseMode.HTML) | python | async def cmd_id(message: types.Message):
"""
Return info about user.
"""
if message.reply_to_message:
target = message.reply_to_message.from_user
chat = message.chat
elif message.forward_from and message.chat.type == ChatType.PRIVATE:
target = message.forward_from
chat = message.forward_from or message.chat
else:
target = message.from_user
chat = message.chat
result_msg = [hbold('Info about user:'),
f"First name: {target.first_name}"]
if target.last_name:
result_msg.append(f"Last name: {target.last_name}")
if target.username:
result_msg.append(f"Username: {target.mention}")
result_msg.append(f"User ID: {target.id}")
result_msg.extend([hbold('Chat:'),
f"Type: {chat.type}",
f"Chat ID: {chat.id}"])
if chat.type != ChatType.PRIVATE:
result_msg.append(f"Title: {chat.title}")
else:
result_msg.append(f"Title: {chat.full_name}")
return SendMessage(message.chat.id, '\n'.join(result_msg), reply_to_message_id=message.message_id,
parse_mode=ParseMode.HTML) | [
"async",
"def",
"cmd_id",
"(",
"message",
":",
"types",
".",
"Message",
")",
":",
"if",
"message",
".",
"reply_to_message",
":",
"target",
"=",
"message",
".",
"reply_to_message",
".",
"from_user",
"chat",
"=",
"message",
".",
"chat",
"elif",
"message",
".... | Return info about user. | [
"Return",
"info",
"about",
"user",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/webhook_example.py#L83-L113 |
224,710 | aiogram/aiogram | examples/webhook_example.py | on_shutdown | async def on_shutdown(app):
"""
Graceful shutdown. This method is recommended by aiohttp docs.
"""
# Remove webhook.
await bot.delete_webhook()
# Close Redis connection.
await dp.storage.close()
await dp.storage.wait_closed() | python | async def on_shutdown(app):
"""
Graceful shutdown. This method is recommended by aiohttp docs.
"""
# Remove webhook.
await bot.delete_webhook()
# Close Redis connection.
await dp.storage.close()
await dp.storage.wait_closed() | [
"async",
"def",
"on_shutdown",
"(",
"app",
")",
":",
"# Remove webhook.",
"await",
"bot",
".",
"delete_webhook",
"(",
")",
"# Close Redis connection.",
"await",
"dp",
".",
"storage",
".",
"close",
"(",
")",
"await",
"dp",
".",
"storage",
".",
"wait_closed",
... | Graceful shutdown. This method is recommended by aiohttp docs. | [
"Graceful",
"shutdown",
".",
"This",
"method",
"is",
"recommended",
"by",
"aiohttp",
"docs",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/webhook_example.py#L149-L158 |
224,711 | aiogram/aiogram | aiogram/types/input_file.py | InputFile.from_url | def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE):
"""
Download file from URL
Manually is not required action. You can send urls instead!
:param url: target URL
:param filename: optional. set custom file name
:param chunk_size:
:return: InputFile
"""
pipe = _WebPipe(url, chunk_size=chunk_size)
if filename is None:
filename = pipe.name
return cls(pipe, filename, chunk_size) | python | def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE):
"""
Download file from URL
Manually is not required action. You can send urls instead!
:param url: target URL
:param filename: optional. set custom file name
:param chunk_size:
:return: InputFile
"""
pipe = _WebPipe(url, chunk_size=chunk_size)
if filename is None:
filename = pipe.name
return cls(pipe, filename, chunk_size) | [
"def",
"from_url",
"(",
"cls",
",",
"url",
",",
"filename",
"=",
"None",
",",
"chunk_size",
"=",
"CHUNK_SIZE",
")",
":",
"pipe",
"=",
"_WebPipe",
"(",
"url",
",",
"chunk_size",
"=",
"chunk_size",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=... | Download file from URL
Manually is not required action. You can send urls instead!
:param url: target URL
:param filename: optional. set custom file name
:param chunk_size:
:return: InputFile | [
"Download",
"file",
"from",
"URL"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_file.py#L101-L117 |
224,712 | aiogram/aiogram | aiogram/types/input_file.py | InputFile.save | def save(self, filename, chunk_size=CHUNK_SIZE):
"""
Write file to disk
:param filename:
:param chunk_size:
"""
with open(filename, 'wb') as fp:
while True:
# Chunk writer
data = self.file.read(chunk_size)
if not data:
break
fp.write(data)
# Flush all data
fp.flush()
# Go to start of file.
if self.file.seekable():
self.file.seek(0) | python | def save(self, filename, chunk_size=CHUNK_SIZE):
"""
Write file to disk
:param filename:
:param chunk_size:
"""
with open(filename, 'wb') as fp:
while True:
# Chunk writer
data = self.file.read(chunk_size)
if not data:
break
fp.write(data)
# Flush all data
fp.flush()
# Go to start of file.
if self.file.seekable():
self.file.seek(0) | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"chunk_size",
"=",
"CHUNK_SIZE",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"fp",
":",
"while",
"True",
":",
"# Chunk writer",
"data",
"=",
"self",
".",
"file",
".",
"read",
"(... | Write file to disk
:param filename:
:param chunk_size: | [
"Write",
"file",
"to",
"disk"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_file.py#L119-L138 |
224,713 | aiogram/aiogram | aiogram/types/force_reply.py | ForceReply.create | def create(cls, selective: typing.Optional[base.Boolean] = None):
"""
Create new force reply
:param selective:
:return:
"""
return cls(selective=selective) | python | def create(cls, selective: typing.Optional[base.Boolean] = None):
"""
Create new force reply
:param selective:
:return:
"""
return cls(selective=selective) | [
"def",
"create",
"(",
"cls",
",",
"selective",
":",
"typing",
".",
"Optional",
"[",
"base",
".",
"Boolean",
"]",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"selective",
"=",
"selective",
")"
] | Create new force reply
:param selective:
:return: | [
"Create",
"new",
"force",
"reply"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/force_reply.py#L29-L36 |
224,714 | aiogram/aiogram | examples/finite_state_machine_example.py | cancel_handler | async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None):
"""
Allow user to cancel any action
"""
if raw_state is None:
return
# Cancel state and inform user about it
await state.finish()
# And remove keyboard (just in case)
await message.reply('Canceled.', reply_markup=types.ReplyKeyboardRemove()) | python | async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None):
"""
Allow user to cancel any action
"""
if raw_state is None:
return
# Cancel state and inform user about it
await state.finish()
# And remove keyboard (just in case)
await message.reply('Canceled.', reply_markup=types.ReplyKeyboardRemove()) | [
"async",
"def",
"cancel_handler",
"(",
"message",
":",
"types",
".",
"Message",
",",
"state",
":",
"FSMContext",
",",
"raw_state",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"raw_state",
"is",
"None",
":",
"return",
"# Cancel state and ... | Allow user to cancel any action | [
"Allow",
"user",
"to",
"cancel",
"any",
"action"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/finite_state_machine_example.py#L44-L54 |
224,715 | aiogram/aiogram | examples/finite_state_machine_example.py | process_name | async def process_name(message: types.Message, state: FSMContext):
"""
Process user name
"""
async with state.proxy() as data:
data['name'] = message.text
await Form.next()
await message.reply("How old are you?") | python | async def process_name(message: types.Message, state: FSMContext):
"""
Process user name
"""
async with state.proxy() as data:
data['name'] = message.text
await Form.next()
await message.reply("How old are you?") | [
"async",
"def",
"process_name",
"(",
"message",
":",
"types",
".",
"Message",
",",
"state",
":",
"FSMContext",
")",
":",
"async",
"with",
"state",
".",
"proxy",
"(",
")",
"as",
"data",
":",
"data",
"[",
"'name'",
"]",
"=",
"message",
".",
"text",
"aw... | Process user name | [
"Process",
"user",
"name"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/finite_state_machine_example.py#L58-L66 |
224,716 | aiogram/aiogram | examples/middleware_and_antiflood.py | rate_limit | def rate_limit(limit: int, key=None):
"""
Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return:
"""
def decorator(func):
setattr(func, 'throttling_rate_limit', limit)
if key:
setattr(func, 'throttling_key', key)
return func
return decorator | python | def rate_limit(limit: int, key=None):
"""
Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return:
"""
def decorator(func):
setattr(func, 'throttling_rate_limit', limit)
if key:
setattr(func, 'throttling_key', key)
return func
return decorator | [
"def",
"rate_limit",
"(",
"limit",
":",
"int",
",",
"key",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"setattr",
"(",
"func",
",",
"'throttling_rate_limit'",
",",
"limit",
")",
"if",
"key",
":",
"setattr",
"(",
"func",
",",
"'t... | Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return: | [
"Decorator",
"for",
"configuring",
"rate",
"limit",
"and",
"key",
"in",
"different",
"functions",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L21-L36 |
224,717 | aiogram/aiogram | examples/middleware_and_antiflood.py | ThrottlingMiddleware.on_process_message | async def on_process_message(self, message: types.Message, data: dict):
"""
This handler is called when dispatcher receives a message
:param message:
"""
# Get current handler
handler = current_handler.get()
# Get dispatcher from context
dispatcher = Dispatcher.get_current()
# If handler was configured, get rate limit and key from handler
if handler:
limit = getattr(handler, 'throttling_rate_limit', self.rate_limit)
key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
else:
limit = self.rate_limit
key = f"{self.prefix}_message"
# Use Dispatcher.throttle method.
try:
await dispatcher.throttle(key, rate=limit)
except Throttled as t:
# Execute action
await self.message_throttled(message, t)
# Cancel current handler
raise CancelHandler() | python | async def on_process_message(self, message: types.Message, data: dict):
"""
This handler is called when dispatcher receives a message
:param message:
"""
# Get current handler
handler = current_handler.get()
# Get dispatcher from context
dispatcher = Dispatcher.get_current()
# If handler was configured, get rate limit and key from handler
if handler:
limit = getattr(handler, 'throttling_rate_limit', self.rate_limit)
key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
else:
limit = self.rate_limit
key = f"{self.prefix}_message"
# Use Dispatcher.throttle method.
try:
await dispatcher.throttle(key, rate=limit)
except Throttled as t:
# Execute action
await self.message_throttled(message, t)
# Cancel current handler
raise CancelHandler() | [
"async",
"def",
"on_process_message",
"(",
"self",
",",
"message",
":",
"types",
".",
"Message",
",",
"data",
":",
"dict",
")",
":",
"# Get current handler",
"handler",
"=",
"current_handler",
".",
"get",
"(",
")",
"# Get dispatcher from context",
"dispatcher",
... | This handler is called when dispatcher receives a message
:param message: | [
"This",
"handler",
"is",
"called",
"when",
"dispatcher",
"receives",
"a",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L49-L76 |
224,718 | aiogram/aiogram | examples/middleware_and_antiflood.py | ThrottlingMiddleware.message_throttled | async def message_throttled(self, message: types.Message, throttled: Throttled):
"""
Notify user only on first exceed and notify about unlocking only on last exceed
:param message:
:param throttled:
"""
handler = current_handler.get()
dispatcher = Dispatcher.get_current()
if handler:
key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
else:
key = f"{self.prefix}_message"
# Calculate how many time is left till the block ends
delta = throttled.rate - throttled.delta
# Prevent flooding
if throttled.exceeded_count <= 2:
await message.reply('Too many requests! ')
# Sleep.
await asyncio.sleep(delta)
# Check lock status
thr = await dispatcher.check_key(key)
# If current message is not last with current key - do not send message
if thr.exceeded_count == throttled.exceeded_count:
await message.reply('Unlocked.') | python | async def message_throttled(self, message: types.Message, throttled: Throttled):
"""
Notify user only on first exceed and notify about unlocking only on last exceed
:param message:
:param throttled:
"""
handler = current_handler.get()
dispatcher = Dispatcher.get_current()
if handler:
key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
else:
key = f"{self.prefix}_message"
# Calculate how many time is left till the block ends
delta = throttled.rate - throttled.delta
# Prevent flooding
if throttled.exceeded_count <= 2:
await message.reply('Too many requests! ')
# Sleep.
await asyncio.sleep(delta)
# Check lock status
thr = await dispatcher.check_key(key)
# If current message is not last with current key - do not send message
if thr.exceeded_count == throttled.exceeded_count:
await message.reply('Unlocked.') | [
"async",
"def",
"message_throttled",
"(",
"self",
",",
"message",
":",
"types",
".",
"Message",
",",
"throttled",
":",
"Throttled",
")",
":",
"handler",
"=",
"current_handler",
".",
"get",
"(",
")",
"dispatcher",
"=",
"Dispatcher",
".",
"get_current",
"(",
... | Notify user only on first exceed and notify about unlocking only on last exceed
:param message:
:param throttled: | [
"Notify",
"user",
"only",
"on",
"first",
"exceed",
"and",
"notify",
"about",
"unlocking",
"only",
"on",
"last",
"exceed"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L78-L107 |
224,719 | aiogram/aiogram | aiogram/utils/auth_widget.py | generate_hash | def generate_hash(data: dict, token: str) -> str:
"""
Generate secret hash
:param data:
:param token:
:return:
"""
secret = hashlib.sha256()
secret.update(token.encode('utf-8'))
sorted_params = collections.OrderedDict(sorted(data.items()))
msg = '\n'.join("{}={}".format(k, v) for k, v in sorted_params.items() if k != 'hash')
return hmac.new(secret.digest(), msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest() | python | def generate_hash(data: dict, token: str) -> str:
"""
Generate secret hash
:param data:
:param token:
:return:
"""
secret = hashlib.sha256()
secret.update(token.encode('utf-8'))
sorted_params = collections.OrderedDict(sorted(data.items()))
msg = '\n'.join("{}={}".format(k, v) for k, v in sorted_params.items() if k != 'hash')
return hmac.new(secret.digest(), msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest() | [
"def",
"generate_hash",
"(",
"data",
":",
"dict",
",",
"token",
":",
"str",
")",
"->",
"str",
":",
"secret",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"secret",
".",
"update",
"(",
"token",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"sorted_params",
"="... | Generate secret hash
:param data:
:param token:
:return: | [
"Generate",
"secret",
"hash"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L12-L24 |
224,720 | aiogram/aiogram | aiogram/utils/auth_widget.py | check_token | def check_token(data: dict, token: str) -> bool:
"""
Validate auth token
:param data:
:param token:
:return:
"""
param_hash = data.get('hash', '') or ''
return param_hash == generate_hash(data, token) | python | def check_token(data: dict, token: str) -> bool:
"""
Validate auth token
:param data:
:param token:
:return:
"""
param_hash = data.get('hash', '') or ''
return param_hash == generate_hash(data, token) | [
"def",
"check_token",
"(",
"data",
":",
"dict",
",",
"token",
":",
"str",
")",
"->",
"bool",
":",
"param_hash",
"=",
"data",
".",
"get",
"(",
"'hash'",
",",
"''",
")",
"or",
"''",
"return",
"param_hash",
"==",
"generate_hash",
"(",
"data",
",",
"toke... | Validate auth token
:param data:
:param token:
:return: | [
"Validate",
"auth",
"token"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L27-L36 |
224,721 | aiogram/aiogram | aiogram/dispatcher/filters/factory.py | FiltersFactory.resolve | def resolve(self, event_handler, *custom_filters, **full_config
) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]:
"""
Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return:
"""
filters_set = []
filters_set.extend(self._resolve_registered(event_handler,
{k: v for k, v in full_config.items() if v is not None}))
if custom_filters:
filters_set.extend(custom_filters)
return filters_set | python | def resolve(self, event_handler, *custom_filters, **full_config
) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]:
"""
Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return:
"""
filters_set = []
filters_set.extend(self._resolve_registered(event_handler,
{k: v for k, v in full_config.items() if v is not None}))
if custom_filters:
filters_set.extend(custom_filters)
return filters_set | [
"def",
"resolve",
"(",
"self",
",",
"event_handler",
",",
"*",
"custom_filters",
",",
"*",
"*",
"full_config",
")",
"->",
"typing",
".",
"List",
"[",
"typing",
".",
"Union",
"[",
"typing",
".",
"Callable",
",",
"AbstractFilter",
"]",
"]",
":",
"filters_s... | Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return: | [
"Resolve",
"filters",
"to",
"filters",
"-",
"set"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/factory.py#L41-L57 |
224,722 | aiogram/aiogram | aiogram/dispatcher/filters/factory.py | FiltersFactory._resolve_registered | def _resolve_registered(self, event_handler, full_config) -> typing.Generator:
"""
Resolve registered filters
:param event_handler:
:param full_config:
:return:
"""
for record in self._registered:
filter_ = record.resolve(self._dispatcher, event_handler, full_config)
if filter_:
yield filter_
if full_config:
raise NameError('Invalid filter name(s): \'' + '\', '.join(full_config.keys()) + '\'') | python | def _resolve_registered(self, event_handler, full_config) -> typing.Generator:
"""
Resolve registered filters
:param event_handler:
:param full_config:
:return:
"""
for record in self._registered:
filter_ = record.resolve(self._dispatcher, event_handler, full_config)
if filter_:
yield filter_
if full_config:
raise NameError('Invalid filter name(s): \'' + '\', '.join(full_config.keys()) + '\'') | [
"def",
"_resolve_registered",
"(",
"self",
",",
"event_handler",
",",
"full_config",
")",
"->",
"typing",
".",
"Generator",
":",
"for",
"record",
"in",
"self",
".",
"_registered",
":",
"filter_",
"=",
"record",
".",
"resolve",
"(",
"self",
".",
"_dispatcher"... | Resolve registered filters
:param event_handler:
:param full_config:
:return: | [
"Resolve",
"registered",
"filters"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/factory.py#L59-L73 |
224,723 | aiogram/aiogram | aiogram/types/auth_widget_data.py | AuthWidgetData.parse | def parse(cls, request: web.Request) -> AuthWidgetData:
"""
Parse request as Telegram auth widget data.
:param request:
:return: :obj:`AuthWidgetData`
:raise: :obj:`aiohttp.web.HTTPBadRequest`
"""
try:
query = dict(request.query)
query['id'] = int(query['id'])
query['auth_date'] = int(query['auth_date'])
widget = AuthWidgetData(**query)
except (ValueError, KeyError):
raise web.HTTPBadRequest(text='Invalid auth data')
else:
return widget | python | def parse(cls, request: web.Request) -> AuthWidgetData:
"""
Parse request as Telegram auth widget data.
:param request:
:return: :obj:`AuthWidgetData`
:raise: :obj:`aiohttp.web.HTTPBadRequest`
"""
try:
query = dict(request.query)
query['id'] = int(query['id'])
query['auth_date'] = int(query['auth_date'])
widget = AuthWidgetData(**query)
except (ValueError, KeyError):
raise web.HTTPBadRequest(text='Invalid auth data')
else:
return widget | [
"def",
"parse",
"(",
"cls",
",",
"request",
":",
"web",
".",
"Request",
")",
"->",
"AuthWidgetData",
":",
"try",
":",
"query",
"=",
"dict",
"(",
"request",
".",
"query",
")",
"query",
"[",
"'id'",
"]",
"=",
"int",
"(",
"query",
"[",
"'id'",
"]",
... | Parse request as Telegram auth widget data.
:param request:
:return: :obj:`AuthWidgetData`
:raise: :obj:`aiohttp.web.HTTPBadRequest` | [
"Parse",
"request",
"as",
"Telegram",
"auth",
"widget",
"data",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/auth_widget_data.py#L19-L35 |
224,724 | aiogram/aiogram | aiogram/dispatcher/webhook.py | _check_ip | def _check_ip(ip: str) -> bool:
"""
Check IP in range
:param ip:
:return:
"""
address = ipaddress.IPv4Address(ip)
return address in allowed_ips | python | def _check_ip(ip: str) -> bool:
"""
Check IP in range
:param ip:
:return:
"""
address = ipaddress.IPv4Address(ip)
return address in allowed_ips | [
"def",
"_check_ip",
"(",
"ip",
":",
"str",
")",
"->",
"bool",
":",
"address",
"=",
"ipaddress",
".",
"IPv4Address",
"(",
"ip",
")",
"return",
"address",
"in",
"allowed_ips"
] | Check IP in range
:param ip:
:return: | [
"Check",
"IP",
"in",
"range"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L39-L47 |
224,725 | aiogram/aiogram | aiogram/dispatcher/webhook.py | allow_ip | def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):
"""
Allow ip address.
:param ips:
:return:
"""
for ip in ips:
if isinstance(ip, ipaddress.IPv4Address):
allowed_ips.add(ip)
elif isinstance(ip, str):
allowed_ips.add(ipaddress.IPv4Address(ip))
elif isinstance(ip, ipaddress.IPv4Network):
allowed_ips.update(ip.hosts())
else:
raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')") | python | def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):
"""
Allow ip address.
:param ips:
:return:
"""
for ip in ips:
if isinstance(ip, ipaddress.IPv4Address):
allowed_ips.add(ip)
elif isinstance(ip, str):
allowed_ips.add(ipaddress.IPv4Address(ip))
elif isinstance(ip, ipaddress.IPv4Network):
allowed_ips.update(ip.hosts())
else:
raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')") | [
"def",
"allow_ip",
"(",
"*",
"ips",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"ipaddress",
".",
"IPv4Network",
",",
"ipaddress",
".",
"IPv4Address",
"]",
")",
":",
"for",
"ip",
"in",
"ips",
":",
"if",
"isinstance",
"(",
"ip",
",",
"ipaddress",
".... | Allow ip address.
:param ips:
:return: | [
"Allow",
"ip",
"address",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L50-L65 |
224,726 | aiogram/aiogram | aiogram/dispatcher/webhook.py | configure_app | def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME):
"""
You can prepare web.Application for working with webhook handler.
:param dispatcher: Dispatcher instance
:param app: :class:`aiohttp.web.Application`
:param path: Path to your webhook.
:param route_name: Name of webhook handler route
:return:
"""
app.router.add_route('*', path, WebhookRequestHandler, name=route_name)
app[BOT_DISPATCHER_KEY] = dispatcher | python | def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME):
"""
You can prepare web.Application for working with webhook handler.
:param dispatcher: Dispatcher instance
:param app: :class:`aiohttp.web.Application`
:param path: Path to your webhook.
:param route_name: Name of webhook handler route
:return:
"""
app.router.add_route('*', path, WebhookRequestHandler, name=route_name)
app[BOT_DISPATCHER_KEY] = dispatcher | [
"def",
"configure_app",
"(",
"dispatcher",
",",
"app",
":",
"web",
".",
"Application",
",",
"path",
"=",
"DEFAULT_WEB_PATH",
",",
"route_name",
"=",
"DEFAULT_ROUTE_NAME",
")",
":",
"app",
".",
"router",
".",
"add_route",
"(",
"'*'",
",",
"path",
",",
"Webh... | You can prepare web.Application for working with webhook handler.
:param dispatcher: Dispatcher instance
:param app: :class:`aiohttp.web.Application`
:param path: Path to your webhook.
:param route_name: Name of webhook handler route
:return: | [
"You",
"can",
"prepare",
"web",
".",
"Application",
"for",
"working",
"with",
"webhook",
"handler",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L278-L289 |
224,727 | aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.get_dispatcher | def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
dp = self.request.app[BOT_DISPATCHER_KEY]
try:
from aiogram import Bot, Dispatcher
Dispatcher.set_current(dp)
Bot.set_current(dp.bot)
except RuntimeError:
pass
return dp | python | def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
dp = self.request.app[BOT_DISPATCHER_KEY]
try:
from aiogram import Bot, Dispatcher
Dispatcher.set_current(dp)
Bot.set_current(dp.bot)
except RuntimeError:
pass
return dp | [
"def",
"get_dispatcher",
"(",
"self",
")",
":",
"dp",
"=",
"self",
".",
"request",
".",
"app",
"[",
"BOT_DISPATCHER_KEY",
"]",
"try",
":",
"from",
"aiogram",
"import",
"Bot",
",",
"Dispatcher",
"Dispatcher",
".",
"set_current",
"(",
"dp",
")",
"Bot",
"."... | Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher` | [
"Get",
"Dispatcher",
"instance",
"from",
"environment"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L93-L106 |
224,728 | aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.parse_update | async def parse_update(self, bot):
"""
Read update from stream and deserialize it.
:param bot: bot instance. You an get it from Dispatcher
:return: :class:`aiogram.types.Update`
"""
data = await self.request.json()
update = types.Update(**data)
return update | python | async def parse_update(self, bot):
"""
Read update from stream and deserialize it.
:param bot: bot instance. You an get it from Dispatcher
:return: :class:`aiogram.types.Update`
"""
data = await self.request.json()
update = types.Update(**data)
return update | [
"async",
"def",
"parse_update",
"(",
"self",
",",
"bot",
")",
":",
"data",
"=",
"await",
"self",
".",
"request",
".",
"json",
"(",
")",
"update",
"=",
"types",
".",
"Update",
"(",
"*",
"*",
"data",
")",
"return",
"update"
] | Read update from stream and deserialize it.
:param bot: bot instance. You an get it from Dispatcher
:return: :class:`aiogram.types.Update` | [
"Read",
"update",
"from",
"stream",
"and",
"deserialize",
"it",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L108-L117 |
224,729 | aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.post | async def post(self):
"""
Process POST request
if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.
Otherwise do nothing (return 'ok')
:return: :class:`aiohttp.web.Response`
"""
self.validate_ip()
# context.update_state({'CALLER': WEBHOOK,
# WEBHOOK_CONNECTION: True,
# WEBHOOK_REQUEST: self.request})
dispatcher = self.get_dispatcher()
update = await self.parse_update(dispatcher.bot)
results = await self.process_update(update)
response = self.get_response(results)
if response:
web_response = response.get_web_response()
else:
web_response = web.Response(text='ok')
if self.request.app.get('RETRY_AFTER', None):
web_response.headers['Retry-After'] = self.request.app['RETRY_AFTER']
return web_response | python | async def post(self):
"""
Process POST request
if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.
Otherwise do nothing (return 'ok')
:return: :class:`aiohttp.web.Response`
"""
self.validate_ip()
# context.update_state({'CALLER': WEBHOOK,
# WEBHOOK_CONNECTION: True,
# WEBHOOK_REQUEST: self.request})
dispatcher = self.get_dispatcher()
update = await self.parse_update(dispatcher.bot)
results = await self.process_update(update)
response = self.get_response(results)
if response:
web_response = response.get_web_response()
else:
web_response = web.Response(text='ok')
if self.request.app.get('RETRY_AFTER', None):
web_response.headers['Retry-After'] = self.request.app['RETRY_AFTER']
return web_response | [
"async",
"def",
"post",
"(",
"self",
")",
":",
"self",
".",
"validate_ip",
"(",
")",
"# context.update_state({'CALLER': WEBHOOK,",
"# WEBHOOK_CONNECTION: True,",
"# WEBHOOK_REQUEST: self.request})",
"dispatcher",
"=",
"self",
".",
"ge... | Process POST request
if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.
Otherwise do nothing (return 'ok')
:return: :class:`aiohttp.web.Response` | [
"Process",
"POST",
"request"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L119-L148 |
224,730 | aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.process_update | async def process_update(self, update):
"""
Need respond in less than 60 seconds in to webhook.
So... If you respond greater than 55 seconds webhook automatically respond 'ok'
and execute callback response via simple HTTP request.
:param update:
:return:
"""
dispatcher = self.get_dispatcher()
loop = dispatcher.loop
# Analog of `asyncio.wait_for` but without cancelling task
waiter = loop.create_future()
timeout_handle = loop.call_later(RESPONSE_TIMEOUT, asyncio.tasks._release_waiter, waiter)
cb = functools.partial(asyncio.tasks._release_waiter, waiter)
fut = asyncio.ensure_future(dispatcher.updates_handler.notify(update), loop=loop)
fut.add_done_callback(cb)
try:
try:
await waiter
except asyncio.futures.CancelledError:
fut.remove_done_callback(cb)
fut.cancel()
raise
if fut.done():
return fut.result()
else:
# context.set_value(WEBHOOK_CONNECTION, False)
fut.remove_done_callback(cb)
fut.add_done_callback(self.respond_via_request)
finally:
timeout_handle.cancel() | python | async def process_update(self, update):
"""
Need respond in less than 60 seconds in to webhook.
So... If you respond greater than 55 seconds webhook automatically respond 'ok'
and execute callback response via simple HTTP request.
:param update:
:return:
"""
dispatcher = self.get_dispatcher()
loop = dispatcher.loop
# Analog of `asyncio.wait_for` but without cancelling task
waiter = loop.create_future()
timeout_handle = loop.call_later(RESPONSE_TIMEOUT, asyncio.tasks._release_waiter, waiter)
cb = functools.partial(asyncio.tasks._release_waiter, waiter)
fut = asyncio.ensure_future(dispatcher.updates_handler.notify(update), loop=loop)
fut.add_done_callback(cb)
try:
try:
await waiter
except asyncio.futures.CancelledError:
fut.remove_done_callback(cb)
fut.cancel()
raise
if fut.done():
return fut.result()
else:
# context.set_value(WEBHOOK_CONNECTION, False)
fut.remove_done_callback(cb)
fut.add_done_callback(self.respond_via_request)
finally:
timeout_handle.cancel() | [
"async",
"def",
"process_update",
"(",
"self",
",",
"update",
")",
":",
"dispatcher",
"=",
"self",
".",
"get_dispatcher",
"(",
")",
"loop",
"=",
"dispatcher",
".",
"loop",
"# Analog of `asyncio.wait_for` but without cancelling task",
"waiter",
"=",
"loop",
".",
"c... | Need respond in less than 60 seconds in to webhook.
So... If you respond greater than 55 seconds webhook automatically respond 'ok'
and execute callback response via simple HTTP request.
:param update:
:return: | [
"Need",
"respond",
"in",
"less",
"than",
"60",
"seconds",
"in",
"to",
"webhook",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L158-L194 |
224,731 | aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.respond_via_request | def respond_via_request(self, task):
"""
Handle response after 55 second.
:param task:
:return:
"""
warn(f"Detected slow response into webhook. "
f"(Greater than {RESPONSE_TIMEOUT} seconds)\n"
f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.",
TimeoutWarning)
dispatcher = self.get_dispatcher()
loop = dispatcher.loop
try:
results = task.result()
except Exception as e:
loop.create_task(
dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e))
else:
response = self.get_response(results)
if response is not None:
asyncio.ensure_future(response.execute_response(dispatcher.bot), loop=loop) | python | def respond_via_request(self, task):
"""
Handle response after 55 second.
:param task:
:return:
"""
warn(f"Detected slow response into webhook. "
f"(Greater than {RESPONSE_TIMEOUT} seconds)\n"
f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.",
TimeoutWarning)
dispatcher = self.get_dispatcher()
loop = dispatcher.loop
try:
results = task.result()
except Exception as e:
loop.create_task(
dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e))
else:
response = self.get_response(results)
if response is not None:
asyncio.ensure_future(response.execute_response(dispatcher.bot), loop=loop) | [
"def",
"respond_via_request",
"(",
"self",
",",
"task",
")",
":",
"warn",
"(",
"f\"Detected slow response into webhook. \"",
"f\"(Greater than {RESPONSE_TIMEOUT} seconds)\\n\"",
"f\"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.\"",
",",
"Timeou... | Handle response after 55 second.
:param task:
:return: | [
"Handle",
"response",
"after",
"55",
"second",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L196-L219 |
224,732 | aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.get_response | def get_response(self, results):
"""
Get response object from results.
:param results: list
:return:
"""
if results is None:
return None
for result in itertools.chain.from_iterable(results):
if isinstance(result, BaseResponse):
return result | python | def get_response(self, results):
"""
Get response object from results.
:param results: list
:return:
"""
if results is None:
return None
for result in itertools.chain.from_iterable(results):
if isinstance(result, BaseResponse):
return result | [
"def",
"get_response",
"(",
"self",
",",
"results",
")",
":",
"if",
"results",
"is",
"None",
":",
"return",
"None",
"for",
"result",
"in",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"results",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
... | Get response object from results.
:param results: list
:return: | [
"Get",
"response",
"object",
"from",
"results",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L221-L232 |
224,733 | aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.check_ip | def check_ip(self):
"""
Check client IP. Accept requests only from telegram servers.
:return:
"""
# For reverse proxy (nginx)
forwarded_for = self.request.headers.get('X-Forwarded-For', None)
if forwarded_for:
return forwarded_for, _check_ip(forwarded_for)
# For default method
peer_name = self.request.transport.get_extra_info('peername')
if peer_name is not None:
host, _ = peer_name
return host, _check_ip(host)
# Not allowed and can't get client IP
return None, False | python | def check_ip(self):
"""
Check client IP. Accept requests only from telegram servers.
:return:
"""
# For reverse proxy (nginx)
forwarded_for = self.request.headers.get('X-Forwarded-For', None)
if forwarded_for:
return forwarded_for, _check_ip(forwarded_for)
# For default method
peer_name = self.request.transport.get_extra_info('peername')
if peer_name is not None:
host, _ = peer_name
return host, _check_ip(host)
# Not allowed and can't get client IP
return None, False | [
"def",
"check_ip",
"(",
"self",
")",
":",
"# For reverse proxy (nginx)",
"forwarded_for",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'X-Forwarded-For'",
",",
"None",
")",
"if",
"forwarded_for",
":",
"return",
"forwarded_for",
",",
"_check_ip"... | Check client IP. Accept requests only from telegram servers.
:return: | [
"Check",
"client",
"IP",
".",
"Accept",
"requests",
"only",
"from",
"telegram",
"servers",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L234-L252 |
224,734 | aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.validate_ip | def validate_ip(self):
"""
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
"""
if self.request.app.get('_check_ip', False):
ip_address, accept = self.check_ip()
if not accept:
raise web.HTTPUnauthorized() | python | def validate_ip(self):
"""
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
"""
if self.request.app.get('_check_ip', False):
ip_address, accept = self.check_ip()
if not accept:
raise web.HTTPUnauthorized() | [
"def",
"validate_ip",
"(",
"self",
")",
":",
"if",
"self",
".",
"request",
".",
"app",
".",
"get",
"(",
"'_check_ip'",
",",
"False",
")",
":",
"ip_address",
",",
"accept",
"=",
"self",
".",
"check_ip",
"(",
")",
"if",
"not",
"accept",
":",
"raise",
... | Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts. | [
"Check",
"ip",
"if",
"that",
"is",
"needed",
".",
"Raise",
"web",
".",
"HTTPUnauthorized",
"for",
"not",
"allowed",
"hosts",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L254-L261 |
224,735 | aiogram/aiogram | aiogram/dispatcher/webhook.py | BaseResponse.cleanup | def cleanup(self) -> typing.Dict:
"""
Cleanup response after preparing. Remove empty fields.
:return: response parameters dict
"""
return {k: v for k, v in self.prepare().items() if v is not None} | python | def cleanup(self) -> typing.Dict:
"""
Cleanup response after preparing. Remove empty fields.
:return: response parameters dict
"""
return {k: v for k, v in self.prepare().items() if v is not None} | [
"def",
"cleanup",
"(",
"self",
")",
"->",
"typing",
".",
"Dict",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"prepare",
"(",
")",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}"
] | Cleanup response after preparing. Remove empty fields.
:return: response parameters dict | [
"Cleanup",
"response",
"after",
"preparing",
".",
"Remove",
"empty",
"fields",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L327-L333 |
224,736 | aiogram/aiogram | aiogram/dispatcher/webhook.py | BaseResponse.execute_response | async def execute_response(self, bot):
"""
Use this method if you want to execute response as simple HTTP request.
:param bot: Bot instance.
:return:
"""
method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case)
method = getattr(bot, method_name, None)
if method:
return await method(**self.cleanup())
return await bot.request(self.method, self.cleanup()) | python | async def execute_response(self, bot):
"""
Use this method if you want to execute response as simple HTTP request.
:param bot: Bot instance.
:return:
"""
method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case)
method = getattr(bot, method_name, None)
if method:
return await method(**self.cleanup())
return await bot.request(self.method, self.cleanup()) | [
"async",
"def",
"execute_response",
"(",
"self",
",",
"bot",
")",
":",
"method_name",
"=",
"helper",
".",
"HelperMode",
".",
"apply",
"(",
"self",
".",
"method",
",",
"helper",
".",
"HelperMode",
".",
"snake_case",
")",
"method",
"=",
"getattr",
"(",
"bo... | Use this method if you want to execute response as simple HTTP request.
:param bot: Bot instance.
:return: | [
"Use",
"this",
"method",
"if",
"you",
"want",
"to",
"execute",
"response",
"as",
"simple",
"HTTP",
"request",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L351-L362 |
224,737 | aiogram/aiogram | aiogram/dispatcher/webhook.py | ReplyToMixin.reply | def reply(self, message: typing.Union[int, types.Message]):
"""
Reply to message
:param message: :obj:`int` or :obj:`types.Message`
:return: self
"""
setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message)
return self | python | def reply(self, message: typing.Union[int, types.Message]):
"""
Reply to message
:param message: :obj:`int` or :obj:`types.Message`
:return: self
"""
setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message)
return self | [
"def",
"reply",
"(",
"self",
",",
"message",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"types",
".",
"Message",
"]",
")",
":",
"setattr",
"(",
"self",
",",
"'reply_to_message_id'",
",",
"message",
".",
"message_id",
"if",
"isinstance",
"(",
"message"... | Reply to message
:param message: :obj:`int` or :obj:`types.Message`
:return: self | [
"Reply",
"to",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L382-L390 |
224,738 | aiogram/aiogram | aiogram/dispatcher/webhook.py | ReplyToMixin.to | def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]):
"""
Send to chat
:param target: message or chat or id
:return:
"""
if isinstance(target, types.Message):
chat_id = target.chat.id
elif isinstance(target, types.Chat):
chat_id = target.id
elif isinstance(target, (int, str)):
chat_id = target
else:
raise TypeError(f"Bad type of target. ({type(target)})")
setattr(self, 'chat_id', chat_id)
return self | python | def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]):
"""
Send to chat
:param target: message or chat or id
:return:
"""
if isinstance(target, types.Message):
chat_id = target.chat.id
elif isinstance(target, types.Chat):
chat_id = target.id
elif isinstance(target, (int, str)):
chat_id = target
else:
raise TypeError(f"Bad type of target. ({type(target)})")
setattr(self, 'chat_id', chat_id)
return self | [
"def",
"to",
"(",
"self",
",",
"target",
":",
"typing",
".",
"Union",
"[",
"types",
".",
"Message",
",",
"types",
".",
"Chat",
",",
"types",
".",
"base",
".",
"Integer",
",",
"types",
".",
"base",
".",
"String",
"]",
")",
":",
"if",
"isinstance",
... | Send to chat
:param target: message or chat or id
:return: | [
"Send",
"to",
"chat"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L392-L409 |
224,739 | aiogram/aiogram | aiogram/dispatcher/webhook.py | SendMessage.write | def write(self, *text, sep=' '):
"""
Write text to response
:param text:
:param sep:
:return:
"""
self.text += markdown.text(*text, sep)
return self | python | def write(self, *text, sep=' '):
"""
Write text to response
:param text:
:param sep:
:return:
"""
self.text += markdown.text(*text, sep)
return self | [
"def",
"write",
"(",
"self",
",",
"*",
"text",
",",
"sep",
"=",
"' '",
")",
":",
"self",
".",
"text",
"+=",
"markdown",
".",
"text",
"(",
"*",
"text",
",",
"sep",
")",
"return",
"self"
] | Write text to response
:param text:
:param sep:
:return: | [
"Write",
"text",
"to",
"response"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L524-L533 |
224,740 | aiogram/aiogram | aiogram/dispatcher/webhook.py | ForwardMessage.message | def message(self, message: types.Message):
"""
Select target message
:param message:
:return:
"""
setattr(self, 'from_chat_id', message.chat.id)
setattr(self, 'message_id', message.message_id)
return self | python | def message(self, message: types.Message):
"""
Select target message
:param message:
:return:
"""
setattr(self, 'from_chat_id', message.chat.id)
setattr(self, 'message_id', message.message_id)
return self | [
"def",
"message",
"(",
"self",
",",
"message",
":",
"types",
".",
"Message",
")",
":",
"setattr",
"(",
"self",
",",
"'from_chat_id'",
",",
"message",
".",
"chat",
".",
"id",
")",
"setattr",
"(",
"self",
",",
"'message_id'",
",",
"message",
".",
"messag... | Select target message
:param message:
:return: | [
"Select",
"target",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L575-L584 |
224,741 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.check_address | def check_address(cls, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]):
"""
In all storage's methods chat or user is always required.
If one of them is not provided, you have to set missing value based on the provided one.
This method performs the check described above.
:param chat:
:param user:
:return:
"""
if chat is None and user is None:
raise ValueError('`user` or `chat` parameter is required but no one is provided!')
if user is None and chat is not None:
user = chat
elif user is not None and chat is None:
chat = user
return chat, user | python | def check_address(cls, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]):
"""
In all storage's methods chat or user is always required.
If one of them is not provided, you have to set missing value based on the provided one.
This method performs the check described above.
:param chat:
:param user:
:return:
"""
if chat is None and user is None:
raise ValueError('`user` or `chat` parameter is required but no one is provided!')
if user is None and chat is not None:
user = chat
elif user is not None and chat is None:
chat = user
return chat, user | [
"def",
"check_address",
"(",
"cls",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
")",... | In all storage's methods chat or user is always required.
If one of them is not provided, you have to set missing value based on the provided one.
This method performs the check described above.
:param chat:
:param user:
:return: | [
"In",
"all",
"storage",
"s",
"methods",
"chat",
"or",
"user",
"is",
"always",
"required",
".",
"If",
"one",
"of",
"them",
"is",
"not",
"provided",
"you",
"have",
"to",
"set",
"missing",
"value",
"based",
"on",
"the",
"provided",
"one",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L41-L61 |
224,742 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.get_data | async def get_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
default: typing.Optional[typing.Dict] = None) -> typing.Dict:
"""
Get state-data for user in chat. Return `default` if no data is provided in storage.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param default:
:return:
"""
raise NotImplementedError | python | async def get_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
default: typing.Optional[typing.Dict] = None) -> typing.Dict:
"""
Get state-data for user in chat. Return `default` if no data is provided in storage.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param default:
:return:
"""
raise NotImplementedError | [
"async",
"def",
"get_data",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",... | Get state-data for user in chat. Return `default` if no data is provided in storage.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param default:
:return: | [
"Get",
"state",
"-",
"data",
"for",
"user",
"in",
"chat",
".",
"Return",
"default",
"if",
"no",
"data",
"is",
"provided",
"in",
"storage",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L80-L95 |
224,743 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.update_data | async def update_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
data: typing.Dict = None,
**kwargs):
"""
Update data for user in chat
You can use data parameter or|and kwargs.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param data:
:param chat:
:param user:
:param kwargs:
:return:
"""
raise NotImplementedError | python | async def update_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
data: typing.Dict = None,
**kwargs):
"""
Update data for user in chat
You can use data parameter or|and kwargs.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param data:
:param chat:
:param user:
:param kwargs:
:return:
"""
raise NotImplementedError | [
"async",
"def",
"update_data",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"Non... | Update data for user in chat
You can use data parameter or|and kwargs.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param data:
:param chat:
:param user:
:param kwargs:
:return: | [
"Update",
"data",
"for",
"user",
"in",
"chat"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L129-L148 |
224,744 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.reset_state | async def reset_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
with_data: typing.Optional[bool] = True):
"""
Reset state for user in chat.
You may desire to use this method when finishing conversations.
Chat or user is always required. If one of this is not presented,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param with_data:
:return:
"""
chat, user = self.check_address(chat=chat, user=user)
await self.set_state(chat=chat, user=user, state=None)
if with_data:
await self.set_data(chat=chat, user=user, data={}) | python | async def reset_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
with_data: typing.Optional[bool] = True):
"""
Reset state for user in chat.
You may desire to use this method when finishing conversations.
Chat or user is always required. If one of this is not presented,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param with_data:
:return:
"""
chat, user = self.check_address(chat=chat, user=user)
await self.set_state(chat=chat, user=user, state=None)
if with_data:
await self.set_data(chat=chat, user=user, data={}) | [
"async",
"def",
"reset_state",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"Non... | Reset state for user in chat.
You may desire to use this method when finishing conversations.
Chat or user is always required. If one of this is not presented,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param with_data:
:return: | [
"Reset",
"state",
"for",
"user",
"in",
"chat",
".",
"You",
"may",
"desire",
"to",
"use",
"this",
"method",
"when",
"finishing",
"conversations",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L165-L184 |
224,745 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.finish | async def finish(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None):
"""
Finish conversation for user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:return:
"""
await self.reset_state(chat=chat, user=user, with_data=True) | python | async def finish(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None):
"""
Finish conversation for user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:return:
"""
await self.reset_state(chat=chat, user=user, with_data=True) | [
"async",
"def",
"finish",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
... | Finish conversation for user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:return: | [
"Finish",
"conversation",
"for",
"user",
"in",
"chat",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L186-L199 |
224,746 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.get_bucket | async def get_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
default: typing.Optional[dict] = None) -> typing.Dict:
"""
Get bucket for user in chat. Return `default` if no data is provided in storage.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param default:
:return:
"""
raise NotImplementedError | python | async def get_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
default: typing.Optional[dict] = None) -> typing.Dict:
"""
Get bucket for user in chat. Return `default` if no data is provided in storage.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param default:
:return:
"""
raise NotImplementedError | [
"async",
"def",
"get_bucket",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None... | Get bucket for user in chat. Return `default` if no data is provided in storage.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param default:
:return: | [
"Get",
"bucket",
"for",
"user",
"in",
"chat",
".",
"Return",
"default",
"if",
"no",
"data",
"is",
"provided",
"in",
"storage",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L204-L219 |
224,747 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.set_bucket | async def set_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
bucket: typing.Dict = None):
"""
Set bucket for user in chat
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param bucket:
"""
raise NotImplementedError | python | async def set_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
bucket: typing.Dict = None):
"""
Set bucket for user in chat
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param bucket:
"""
raise NotImplementedError | [
"async",
"def",
"set_bucket",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None... | Set bucket for user in chat
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param bucket: | [
"Set",
"bucket",
"for",
"user",
"in",
"chat"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L221-L235 |
224,748 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.update_bucket | async def update_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
bucket: typing.Dict = None,
**kwargs):
"""
Update bucket for user in chat
You can use bucket parameter or|and kwargs.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param bucket:
:param chat:
:param user:
:param kwargs:
:return:
"""
raise NotImplementedError | python | async def update_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
bucket: typing.Dict = None,
**kwargs):
"""
Update bucket for user in chat
You can use bucket parameter or|and kwargs.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param bucket:
:param chat:
:param user:
:param kwargs:
:return:
"""
raise NotImplementedError | [
"async",
"def",
"update_bucket",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"N... | Update bucket for user in chat
You can use bucket parameter or|and kwargs.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param bucket:
:param chat:
:param user:
:param kwargs:
:return: | [
"Update",
"bucket",
"for",
"user",
"in",
"chat"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L237-L256 |
224,749 | aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.reset_bucket | async def reset_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None):
"""
Reset bucket dor user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:return:
"""
await self.set_data(chat=chat, user=user, data={}) | python | async def reset_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None):
"""
Reset bucket dor user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:return:
"""
await self.set_data(chat=chat, user=user, data={}) | [
"async",
"def",
"reset_bucket",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"No... | Reset bucket dor user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:return: | [
"Reset",
"bucket",
"dor",
"user",
"in",
"chat",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L258-L271 |
224,750 | aiogram/aiogram | aiogram/contrib/fsm_storage/rethinkdb.py | RethinkDBStorage.connect | async def connect(self) -> Connection:
"""
Get or create a connection.
"""
if self._conn is None:
self._conn = await r.connect(host=self._host,
port=self._port,
db=self._db,
auth_key=self._auth_key,
user=self._user,
password=self._password,
timeout=self._timeout,
ssl=self._ssl,
io_loop=self._loop)
return self._conn | python | async def connect(self) -> Connection:
"""
Get or create a connection.
"""
if self._conn is None:
self._conn = await r.connect(host=self._host,
port=self._port,
db=self._db,
auth_key=self._auth_key,
user=self._user,
password=self._password,
timeout=self._timeout,
ssl=self._ssl,
io_loop=self._loop)
return self._conn | [
"async",
"def",
"connect",
"(",
"self",
")",
"->",
"Connection",
":",
"if",
"self",
".",
"_conn",
"is",
"None",
":",
"self",
".",
"_conn",
"=",
"await",
"r",
".",
"connect",
"(",
"host",
"=",
"self",
".",
"_host",
",",
"port",
"=",
"self",
".",
"... | Get or create a connection. | [
"Get",
"or",
"create",
"a",
"connection",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/fsm_storage/rethinkdb.py#L59-L73 |
224,751 | aiogram/aiogram | aiogram/types/input_media.py | MediaGroup.attach_many | def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]):
"""
Attach list of media
:param medias:
"""
for media in medias:
self.attach(media) | python | def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]):
"""
Attach list of media
:param medias:
"""
for media in medias:
self.attach(media) | [
"def",
"attach_many",
"(",
"self",
",",
"*",
"medias",
":",
"typing",
".",
"Union",
"[",
"InputMedia",
",",
"typing",
".",
"Dict",
"]",
")",
":",
"for",
"media",
"in",
"medias",
":",
"self",
".",
"attach",
"(",
"media",
")"
] | Attach list of media
:param medias: | [
"Attach",
"list",
"of",
"media"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_media.py#L209-L216 |
224,752 | aiogram/aiogram | aiogram/dispatcher/filters/builtin.py | Command.validate | def validate(cls, full_config: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Validator for filters factory
From filters factory this filter can be registered with arguments:
- ``command``
- ``commands_prefix`` (will be passed as ``prefixes``)
- ``commands_ignore_mention`` (will be passed as ``ignore_mention``
:param full_config:
:return: config or empty dict
"""
config = {}
if 'commands' in full_config:
config['commands'] = full_config.pop('commands')
if config and 'commands_prefix' in full_config:
config['prefixes'] = full_config.pop('commands_prefix')
if config and 'commands_ignore_mention' in full_config:
config['ignore_mention'] = full_config.pop('commands_ignore_mention')
return config | python | def validate(cls, full_config: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Validator for filters factory
From filters factory this filter can be registered with arguments:
- ``command``
- ``commands_prefix`` (will be passed as ``prefixes``)
- ``commands_ignore_mention`` (will be passed as ``ignore_mention``
:param full_config:
:return: config or empty dict
"""
config = {}
if 'commands' in full_config:
config['commands'] = full_config.pop('commands')
if config and 'commands_prefix' in full_config:
config['prefixes'] = full_config.pop('commands_prefix')
if config and 'commands_ignore_mention' in full_config:
config['ignore_mention'] = full_config.pop('commands_ignore_mention')
return config | [
"def",
"validate",
"(",
"cls",
",",
"full_config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"config",
"=",
"{",
"}",
"if",
"'commands'",
"in",
"full_config",
":",
"config",... | Validator for filters factory
From filters factory this filter can be registered with arguments:
- ``command``
- ``commands_prefix`` (will be passed as ``prefixes``)
- ``commands_ignore_mention`` (will be passed as ``ignore_mention``
:param full_config:
:return: config or empty dict | [
"Validator",
"for",
"filters",
"factory"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/builtin.py#L55-L75 |
224,753 | aiogram/aiogram | aiogram/dispatcher/filters/builtin.py | CommandStart.check | async def check(self, message: types.Message):
"""
If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler
:param message:
:return:
"""
check = await super(CommandStart, self).check(message)
if check and self.deep_link is not None:
if not isinstance(self.deep_link, re.Pattern):
return message.get_args() == self.deep_link
match = self.deep_link.match(message.get_args())
if match:
return {'deep_link': match}
return False
return check | python | async def check(self, message: types.Message):
"""
If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler
:param message:
:return:
"""
check = await super(CommandStart, self).check(message)
if check and self.deep_link is not None:
if not isinstance(self.deep_link, re.Pattern):
return message.get_args() == self.deep_link
match = self.deep_link.match(message.get_args())
if match:
return {'deep_link': match}
return False
return check | [
"async",
"def",
"check",
"(",
"self",
",",
"message",
":",
"types",
".",
"Message",
")",
":",
"check",
"=",
"await",
"super",
"(",
"CommandStart",
",",
"self",
")",
".",
"check",
"(",
"message",
")",
"if",
"check",
"and",
"self",
".",
"deep_link",
"i... | If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler
:param message:
:return: | [
"If",
"deep",
"-",
"linking",
"is",
"passed",
"to",
"the",
"filter",
"result",
"of",
"the",
"matching",
"will",
"be",
"passed",
"as",
"deep_link",
"to",
"the",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/builtin.py#L155-L173 |
224,754 | aiogram/aiogram | aiogram/utils/parts.py | paginate | def paginate(data: typing.Iterable, page: int = 0, limit: int = 10) -> typing.Iterable:
"""
Slice data over pages
:param data: any iterable object
:type data: :obj:`typing.Iterable`
:param page: number of page
:type page: :obj:`int`
:param limit: items per page
:type limit: :obj:`int`
:return: sliced object
:rtype: :obj:`typing.Iterable`
"""
return data[page * limit:page * limit + limit] | python | def paginate(data: typing.Iterable, page: int = 0, limit: int = 10) -> typing.Iterable:
"""
Slice data over pages
:param data: any iterable object
:type data: :obj:`typing.Iterable`
:param page: number of page
:type page: :obj:`int`
:param limit: items per page
:type limit: :obj:`int`
:return: sliced object
:rtype: :obj:`typing.Iterable`
"""
return data[page * limit:page * limit + limit] | [
"def",
"paginate",
"(",
"data",
":",
"typing",
".",
"Iterable",
",",
"page",
":",
"int",
"=",
"0",
",",
"limit",
":",
"int",
"=",
"10",
")",
"->",
"typing",
".",
"Iterable",
":",
"return",
"data",
"[",
"page",
"*",
"limit",
":",
"page",
"*",
"lim... | Slice data over pages
:param data: any iterable object
:type data: :obj:`typing.Iterable`
:param page: number of page
:type page: :obj:`int`
:param limit: items per page
:type limit: :obj:`int`
:return: sliced object
:rtype: :obj:`typing.Iterable` | [
"Slice",
"data",
"over",
"pages"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/parts.py#L46-L59 |
224,755 | aiogram/aiogram | aiogram/bot/bot.py | Bot.download_file_by_id | async def download_file_by_id(self, file_id: base.String, destination=None,
timeout: base.Integer = 30, chunk_size: base.Integer = 65536,
seek: base.Boolean = True):
"""
Download file by file_id to destination
if You want to automatically create destination (:class:`io.BytesIO`) use default
value of destination and handle result of this method.
:param file_id: str
:param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO`
:param timeout: int
:param chunk_size: int
:param seek: bool - go to start of file when downloading is finished
:return: destination
"""
file = await self.get_file(file_id)
return await self.download_file(file_path=file.file_path, destination=destination,
timeout=timeout, chunk_size=chunk_size, seek=seek) | python | async def download_file_by_id(self, file_id: base.String, destination=None,
timeout: base.Integer = 30, chunk_size: base.Integer = 65536,
seek: base.Boolean = True):
"""
Download file by file_id to destination
if You want to automatically create destination (:class:`io.BytesIO`) use default
value of destination and handle result of this method.
:param file_id: str
:param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO`
:param timeout: int
:param chunk_size: int
:param seek: bool - go to start of file when downloading is finished
:return: destination
"""
file = await self.get_file(file_id)
return await self.download_file(file_path=file.file_path, destination=destination,
timeout=timeout, chunk_size=chunk_size, seek=seek) | [
"async",
"def",
"download_file_by_id",
"(",
"self",
",",
"file_id",
":",
"base",
".",
"String",
",",
"destination",
"=",
"None",
",",
"timeout",
":",
"base",
".",
"Integer",
"=",
"30",
",",
"chunk_size",
":",
"base",
".",
"Integer",
"=",
"65536",
",",
... | Download file by file_id to destination
if You want to automatically create destination (:class:`io.BytesIO`) use default
value of destination and handle result of this method.
:param file_id: str
:param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO`
:param timeout: int
:param chunk_size: int
:param seek: bool - go to start of file when downloading is finished
:return: destination | [
"Download",
"file",
"by",
"file_id",
"to",
"destination"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L42-L60 |
224,756 | aiogram/aiogram | aiogram/bot/bot.py | Bot.get_webhook_info | async def get_webhook_info(self) -> types.WebhookInfo:
"""
Use this method to get current webhook status. Requires no parameters.
If the bot is using getUpdates, will return an object with the url field empty.
Source: https://core.telegram.org/bots/api#getwebhookinfo
:return: On success, returns a WebhookInfo object
:rtype: :obj:`types.WebhookInfo`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_WEBHOOK_INFO, payload)
return types.WebhookInfo(**result) | python | async def get_webhook_info(self) -> types.WebhookInfo:
"""
Use this method to get current webhook status. Requires no parameters.
If the bot is using getUpdates, will return an object with the url field empty.
Source: https://core.telegram.org/bots/api#getwebhookinfo
:return: On success, returns a WebhookInfo object
:rtype: :obj:`types.WebhookInfo`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_WEBHOOK_INFO, payload)
return types.WebhookInfo(**result) | [
"async",
"def",
"get_webhook_info",
"(",
"self",
")",
"->",
"types",
".",
"WebhookInfo",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"result",
"=",
"await",
"self",
".",
"request",
"(",
"api",
".",
"Methods",
".",
"... | Use this method to get current webhook status. Requires no parameters.
If the bot is using getUpdates, will return an object with the url field empty.
Source: https://core.telegram.org/bots/api#getwebhookinfo
:return: On success, returns a WebhookInfo object
:rtype: :obj:`types.WebhookInfo` | [
"Use",
"this",
"method",
"to",
"get",
"current",
"webhook",
"status",
".",
"Requires",
"no",
"parameters",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L144-L158 |
224,757 | aiogram/aiogram | aiogram/bot/bot.py | Bot.get_me | async def get_me(self) -> types.User:
"""
A simple method for testing your bot's auth token. Requires no parameters.
Source: https://core.telegram.org/bots/api#getme
:return: Returns basic information about the bot in form of a User object
:rtype: :obj:`types.User`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_ME, payload)
return types.User(**result) | python | async def get_me(self) -> types.User:
"""
A simple method for testing your bot's auth token. Requires no parameters.
Source: https://core.telegram.org/bots/api#getme
:return: Returns basic information about the bot in form of a User object
:rtype: :obj:`types.User`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_ME, payload)
return types.User(**result) | [
"async",
"def",
"get_me",
"(",
"self",
")",
"->",
"types",
".",
"User",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"result",
"=",
"await",
"self",
".",
"request",
"(",
"api",
".",
"Methods",
".",
"GET_ME",
",",
... | A simple method for testing your bot's auth token. Requires no parameters.
Source: https://core.telegram.org/bots/api#getme
:return: Returns basic information about the bot in form of a User object
:rtype: :obj:`types.User` | [
"A",
"simple",
"method",
"for",
"testing",
"your",
"bot",
"s",
"auth",
"token",
".",
"Requires",
"no",
"parameters",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L163-L175 |
224,758 | aiogram/aiogram | aiogram/bot/bot.py | Bot.send_poll | async def send_poll(self, chat_id: typing.Union[base.Integer, base.String],
question: base.String,
options: typing.List[base.String],
disable_notification: typing.Optional[base.Boolean],
reply_to_message_id: typing.Union[base.Integer, None],
reply_markup: typing.Union[types.InlineKeyboardMarkup,
types.ReplyKeyboardMarkup,
types.ReplyKeyboardRemove,
types.ForceReply, None] = None) -> types.Message:
"""
Use this method to send a native poll. A native poll can't be sent to a private chat.
On success, the sent Message is returned.
:param chat_id: Unique identifier for the target chat
or username of the target channel (in the format @channelusername).
A native poll can't be sent to a private chat.
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param question: Poll question, 1-255 characters
:type question: :obj:`base.String`
:param options: List of answer options, 2-10 strings 1-100 characters each
:param options: :obj:`typing.List[base.String]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: :obj:`typing.Optional[Boolean]`
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: :obj:`typing.Optional[Integer]`
:param reply_markup: Additional interface options
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup,
types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]`
:return: On success, the sent Message is returned
:rtype: :obj:`types.Message`
"""
options = prepare_arg(options)
payload = generate_payload(**locals())
result = await self.request(api.Methods.SEND_POLL, payload)
return types.Message(**result) | python | async def send_poll(self, chat_id: typing.Union[base.Integer, base.String],
question: base.String,
options: typing.List[base.String],
disable_notification: typing.Optional[base.Boolean],
reply_to_message_id: typing.Union[base.Integer, None],
reply_markup: typing.Union[types.InlineKeyboardMarkup,
types.ReplyKeyboardMarkup,
types.ReplyKeyboardRemove,
types.ForceReply, None] = None) -> types.Message:
"""
Use this method to send a native poll. A native poll can't be sent to a private chat.
On success, the sent Message is returned.
:param chat_id: Unique identifier for the target chat
or username of the target channel (in the format @channelusername).
A native poll can't be sent to a private chat.
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param question: Poll question, 1-255 characters
:type question: :obj:`base.String`
:param options: List of answer options, 2-10 strings 1-100 characters each
:param options: :obj:`typing.List[base.String]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: :obj:`typing.Optional[Boolean]`
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: :obj:`typing.Optional[Integer]`
:param reply_markup: Additional interface options
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup,
types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]`
:return: On success, the sent Message is returned
:rtype: :obj:`types.Message`
"""
options = prepare_arg(options)
payload = generate_payload(**locals())
result = await self.request(api.Methods.SEND_POLL, payload)
return types.Message(**result) | [
"async",
"def",
"send_poll",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
",",
"question",
":",
"base",
".",
"String",
",",
"options",
":",
"typing",
".",
"List",
"[",
"base",... | Use this method to send a native poll. A native poll can't be sent to a private chat.
On success, the sent Message is returned.
:param chat_id: Unique identifier for the target chat
or username of the target channel (in the format @channelusername).
A native poll can't be sent to a private chat.
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param question: Poll question, 1-255 characters
:type question: :obj:`base.String`
:param options: List of answer options, 2-10 strings 1-100 characters each
:param options: :obj:`typing.List[base.String]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: :obj:`typing.Optional[Boolean]`
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: :obj:`typing.Optional[Integer]`
:param reply_markup: Additional interface options
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup,
types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]`
:return: On success, the sent Message is returned
:rtype: :obj:`types.Message` | [
"Use",
"this",
"method",
"to",
"send",
"a",
"native",
"poll",
".",
"A",
"native",
"poll",
"can",
"t",
"be",
"sent",
"to",
"a",
"private",
"chat",
".",
"On",
"success",
"the",
"sent",
"Message",
"is",
"returned",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L850-L885 |
224,759 | aiogram/aiogram | aiogram/bot/bot.py | Bot.get_file | async def get_file(self, file_id: base.String) -> types.File:
"""
Use this method to get basic info about a file and prepare it for downloading.
For the moment, bots can download files of up to 20MB in size.
Note: This function may not preserve the original file name and MIME type.
You should save the file's MIME type and name (if available) when the File object is received.
Source: https://core.telegram.org/bots/api#getfile
:param file_id: File identifier to get info about
:type file_id: :obj:`base.String`
:return: On success, a File object is returned
:rtype: :obj:`types.File`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_FILE, payload)
return types.File(**result) | python | async def get_file(self, file_id: base.String) -> types.File:
"""
Use this method to get basic info about a file and prepare it for downloading.
For the moment, bots can download files of up to 20MB in size.
Note: This function may not preserve the original file name and MIME type.
You should save the file's MIME type and name (if available) when the File object is received.
Source: https://core.telegram.org/bots/api#getfile
:param file_id: File identifier to get info about
:type file_id: :obj:`base.String`
:return: On success, a File object is returned
:rtype: :obj:`types.File`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_FILE, payload)
return types.File(**result) | [
"async",
"def",
"get_file",
"(",
"self",
",",
"file_id",
":",
"base",
".",
"String",
")",
"->",
"types",
".",
"File",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"result",
"=",
"await",
"self",
".",
"request",
"("... | Use this method to get basic info about a file and prepare it for downloading.
For the moment, bots can download files of up to 20MB in size.
Note: This function may not preserve the original file name and MIME type.
You should save the file's MIME type and name (if available) when the File object is received.
Source: https://core.telegram.org/bots/api#getfile
:param file_id: File identifier to get info about
:type file_id: :obj:`base.String`
:return: On success, a File object is returned
:rtype: :obj:`types.File` | [
"Use",
"this",
"method",
"to",
"get",
"basic",
"info",
"about",
"a",
"file",
"and",
"prepare",
"it",
"for",
"downloading",
".",
"For",
"the",
"moment",
"bots",
"can",
"download",
"files",
"of",
"up",
"to",
"20MB",
"in",
"size",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L932-L950 |
224,760 | aiogram/aiogram | aiogram/bot/bot.py | Bot.export_chat_invite_link | async def export_chat_invite_link(self, chat_id: typing.Union[base.Integer, base.String]) -> base.String:
"""
Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns exported invite link as String on success
:rtype: :obj:`base.String`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.EXPORT_CHAT_INVITE_LINK, payload)
return result | python | async def export_chat_invite_link(self, chat_id: typing.Union[base.Integer, base.String]) -> base.String:
"""
Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns exported invite link as String on success
:rtype: :obj:`base.String`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.EXPORT_CHAT_INVITE_LINK, payload)
return result | [
"async",
"def",
"export_chat_invite_link",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
")",
"->",
"base",
".",
"String",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
... | Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns exported invite link as String on success
:rtype: :obj:`base.String` | [
"Use",
"this",
"method",
"to",
"generate",
"a",
"new",
"invite",
"link",
"for",
"a",
"chat",
";",
"any",
"previously",
"generated",
"link",
"is",
"revoked",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this",
"to",... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1091-L1106 |
224,761 | aiogram/aiogram | aiogram/bot/bot.py | Bot.set_chat_photo | async def set_chat_photo(self, chat_id: typing.Union[base.Integer, base.String],
photo: base.InputFile) -> base.Boolean:
"""
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’
setting is off in the target group.
Source: https://core.telegram.org/bots/api#setchatphoto
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param photo: New chat photo, uploaded using multipart/form-data
:type photo: :obj:`base.InputFile`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals(), exclude=['photo'])
files = {}
prepare_file(payload, files, 'photo', photo)
result = await self.request(api.Methods.SET_CHAT_PHOTO, payload, files)
return result | python | async def set_chat_photo(self, chat_id: typing.Union[base.Integer, base.String],
photo: base.InputFile) -> base.Boolean:
"""
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’
setting is off in the target group.
Source: https://core.telegram.org/bots/api#setchatphoto
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param photo: New chat photo, uploaded using multipart/form-data
:type photo: :obj:`base.InputFile`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals(), exclude=['photo'])
files = {}
prepare_file(payload, files, 'photo', photo)
result = await self.request(api.Methods.SET_CHAT_PHOTO, payload, files)
return result | [
"async",
"def",
"set_chat_photo",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
",",
"photo",
":",
"base",
".",
"InputFile",
")",
"->",
"base",
".",
"Boolean",
":",
"payload",
... | Use this method to set a new profile photo for the chat. Photos can't be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’
setting is off in the target group.
Source: https://core.telegram.org/bots/api#setchatphoto
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param photo: New chat photo, uploaded using multipart/form-data
:type photo: :obj:`base.InputFile`
:return: Returns True on success
:rtype: :obj:`base.Boolean` | [
"Use",
"this",
"method",
"to",
"set",
"a",
"new",
"profile",
"photo",
"for",
"the",
"chat",
".",
"Photos",
"can",
"t",
"be",
"changed",
"for",
"private",
"chats",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1108-L1132 |
224,762 | aiogram/aiogram | aiogram/bot/bot.py | Bot.set_chat_description | async def set_chat_description(self, chat_id: typing.Union[base.Integer, base.String],
description: typing.Union[base.String, None] = None) -> base.Boolean:
"""
Use this method to change the description of a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#setchatdescription
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param description: New chat description, 0-255 characters
:type description: :obj:`typing.Union[base.String, None]`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.SET_CHAT_DESCRIPTION, payload)
return result | python | async def set_chat_description(self, chat_id: typing.Union[base.Integer, base.String],
description: typing.Union[base.String, None] = None) -> base.Boolean:
"""
Use this method to change the description of a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#setchatdescription
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param description: New chat description, 0-255 characters
:type description: :obj:`typing.Union[base.String, None]`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.SET_CHAT_DESCRIPTION, payload)
return result | [
"async",
"def",
"set_chat_description",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
",",
"description",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"String",
",",
"None",
"]... | Use this method to change the description of a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#setchatdescription
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param description: New chat description, 0-255 characters
:type description: :obj:`typing.Union[base.String, None]`
:return: Returns True on success
:rtype: :obj:`base.Boolean` | [
"Use",
"this",
"method",
"to",
"change",
"the",
"description",
"of",
"a",
"supergroup",
"or",
"a",
"channel",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this",
"to",
"work",
"and",
"must",
"have",
"the",
"appropr... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1177-L1195 |
224,763 | aiogram/aiogram | aiogram/bot/bot.py | Bot.unpin_chat_message | async def unpin_chat_message(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean:
"""
Use this method to unpin a message in a supergroup chat.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#unpinchatmessage
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.UNPIN_CHAT_MESSAGE, payload)
return result | python | async def unpin_chat_message(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean:
"""
Use this method to unpin a message in a supergroup chat.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#unpinchatmessage
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.UNPIN_CHAT_MESSAGE, payload)
return result | [
"async",
"def",
"unpin_chat_message",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
")",
"->",
"base",
".",
"Boolean",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
"lo... | Use this method to unpin a message in a supergroup chat.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#unpinchatmessage
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns True on success
:rtype: :obj:`base.Boolean` | [
"Use",
"this",
"method",
"to",
"unpin",
"a",
"message",
"in",
"a",
"supergroup",
"chat",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this",
"to",
"work",
"and",
"must",
"have",
"the",
"appropriate",
"admin",
"righ... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1220-L1235 |
224,764 | aiogram/aiogram | aiogram/bot/bot.py | Bot.get_chat_administrators | async def get_chat_administrators(self, chat_id: typing.Union[base.Integer, base.String]
) -> typing.List[types.ChatMember]:
"""
Use this method to get a list of administrators in a chat.
Source: https://core.telegram.org/bots/api#getchatadministrators
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: On success, returns an Array of ChatMember objects that contains information about all
chat administrators except other bots.
If the chat is a group or a supergroup and no administrators were appointed,
only the creator will be returned.
:rtype: :obj:`typing.List[types.ChatMember]`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_CHAT_ADMINISTRATORS, payload)
return [types.ChatMember(**chatmember) for chatmember in result] | python | async def get_chat_administrators(self, chat_id: typing.Union[base.Integer, base.String]
) -> typing.List[types.ChatMember]:
"""
Use this method to get a list of administrators in a chat.
Source: https://core.telegram.org/bots/api#getchatadministrators
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: On success, returns an Array of ChatMember objects that contains information about all
chat administrators except other bots.
If the chat is a group or a supergroup and no administrators were appointed,
only the creator will be returned.
:rtype: :obj:`typing.List[types.ChatMember]`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_CHAT_ADMINISTRATORS, payload)
return [types.ChatMember(**chatmember) for chatmember in result] | [
"async",
"def",
"get_chat_administrators",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
")",
"->",
"typing",
".",
"List",
"[",
"types",
".",
"ChatMember",
"]",
":",
"payload",
"... | Use this method to get a list of administrators in a chat.
Source: https://core.telegram.org/bots/api#getchatadministrators
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: On success, returns an Array of ChatMember objects that contains information about all
chat administrators except other bots.
If the chat is a group or a supergroup and no administrators were appointed,
only the creator will be returned.
:rtype: :obj:`typing.List[types.ChatMember]` | [
"Use",
"this",
"method",
"to",
"get",
"a",
"list",
"of",
"administrators",
"in",
"a",
"chat",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1270-L1288 |
224,765 | aiogram/aiogram | aiogram/bot/bot.py | Bot.get_chat_member | async def get_chat_member(self, chat_id: typing.Union[base.Integer, base.String],
user_id: base.Integer) -> types.ChatMember:
"""
Use this method to get information about a member of a chat.
Source: https://core.telegram.org/bots/api#getchatmember
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param user_id: Unique identifier of the target user
:type user_id: :obj:`base.Integer`
:return: Returns a ChatMember object on success
:rtype: :obj:`types.ChatMember`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_CHAT_MEMBER, payload)
return types.ChatMember(**result) | python | async def get_chat_member(self, chat_id: typing.Union[base.Integer, base.String],
user_id: base.Integer) -> types.ChatMember:
"""
Use this method to get information about a member of a chat.
Source: https://core.telegram.org/bots/api#getchatmember
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param user_id: Unique identifier of the target user
:type user_id: :obj:`base.Integer`
:return: Returns a ChatMember object on success
:rtype: :obj:`types.ChatMember`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_CHAT_MEMBER, payload)
return types.ChatMember(**result) | [
"async",
"def",
"get_chat_member",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
",",
"user_id",
":",
"base",
".",
"Integer",
")",
"->",
"types",
".",
"ChatMember",
":",
"payload... | Use this method to get information about a member of a chat.
Source: https://core.telegram.org/bots/api#getchatmember
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param user_id: Unique identifier of the target user
:type user_id: :obj:`base.Integer`
:return: Returns a ChatMember object on success
:rtype: :obj:`types.ChatMember` | [
"Use",
"this",
"method",
"to",
"get",
"information",
"about",
"a",
"member",
"of",
"a",
"chat",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1306-L1323 |
224,766 | aiogram/aiogram | aiogram/bot/bot.py | Bot.set_chat_sticker_set | async def set_chat_sticker_set(self, chat_id: typing.Union[base.Integer, base.String],
sticker_set_name: base.String) -> base.Boolean:
"""
Use this method to set a new group sticker set for a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Use the field can_set_sticker_set optionally returned in getChat requests to check
if the bot can use this method.
Source: https://core.telegram.org/bots/api#setchatstickerset
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param sticker_set_name: Name of the sticker set to be set as the group sticker set
:type sticker_set_name: :obj:`base.String`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.SET_CHAT_STICKER_SET, payload)
return result | python | async def set_chat_sticker_set(self, chat_id: typing.Union[base.Integer, base.String],
sticker_set_name: base.String) -> base.Boolean:
"""
Use this method to set a new group sticker set for a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Use the field can_set_sticker_set optionally returned in getChat requests to check
if the bot can use this method.
Source: https://core.telegram.org/bots/api#setchatstickerset
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param sticker_set_name: Name of the sticker set to be set as the group sticker set
:type sticker_set_name: :obj:`base.String`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.SET_CHAT_STICKER_SET, payload)
return result | [
"async",
"def",
"set_chat_sticker_set",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
",",
"sticker_set_name",
":",
"base",
".",
"String",
")",
"->",
"base",
".",
"Boolean",
":",
... | Use this method to set a new group sticker set for a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Use the field can_set_sticker_set optionally returned in getChat requests to check
if the bot can use this method.
Source: https://core.telegram.org/bots/api#setchatstickerset
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param sticker_set_name: Name of the sticker set to be set as the group sticker set
:type sticker_set_name: :obj:`base.String`
:return: Returns True on success
:rtype: :obj:`base.Boolean` | [
"Use",
"this",
"method",
"to",
"set",
"a",
"new",
"group",
"sticker",
"set",
"for",
"a",
"supergroup",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this",
"to",
"work",
"and",
"must",
"have",
"the",
"appropriate",
... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1325-L1346 |
224,767 | aiogram/aiogram | aiogram/bot/bot.py | Bot.delete_chat_sticker_set | async def delete_chat_sticker_set(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean:
"""
Use this method to delete a group sticker set from a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Use the field can_set_sticker_set optionally returned in getChat requests
to check if the bot can use this method.
Source: https://core.telegram.org/bots/api#deletechatstickerset
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.DELETE_CHAT_STICKER_SET, payload)
return result | python | async def delete_chat_sticker_set(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean:
"""
Use this method to delete a group sticker set from a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Use the field can_set_sticker_set optionally returned in getChat requests
to check if the bot can use this method.
Source: https://core.telegram.org/bots/api#deletechatstickerset
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.DELETE_CHAT_STICKER_SET, payload)
return result | [
"async",
"def",
"delete_chat_sticker_set",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
")",
"->",
"base",
".",
"Boolean",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
... | Use this method to delete a group sticker set from a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Use the field can_set_sticker_set optionally returned in getChat requests
to check if the bot can use this method.
Source: https://core.telegram.org/bots/api#deletechatstickerset
:param chat_id: Unique identifier for the target chat or username of the target supergroup
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns True on success
:rtype: :obj:`base.Boolean` | [
"Use",
"this",
"method",
"to",
"delete",
"a",
"group",
"sticker",
"set",
"from",
"a",
"supergroup",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this",
"to",
"work",
"and",
"must",
"have",
"the",
"appropriate",
"ad... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1348-L1366 |
224,768 | aiogram/aiogram | aiogram/bot/bot.py | Bot.stop_poll | async def stop_poll(self, chat_id: typing.Union[base.String, base.Integer],
message_id: base.Integer,
reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Poll:
"""
Use this method to stop a poll which was sent by the bot.
On success, the stopped Poll with the final results is returned.
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.String, base.Integer]`
:param message_id: Identifier of the original message with the poll
:type message_id: :obj:`base.Integer`
:param reply_markup: A JSON-serialized object for a new message inline keyboard.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]`
:return: On success, the stopped Poll with the final results is returned.
:rtype: :obj:`types.Poll`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.STOP_POLL, payload)
return types.Poll(**result) | python | async def stop_poll(self, chat_id: typing.Union[base.String, base.Integer],
message_id: base.Integer,
reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Poll:
"""
Use this method to stop a poll which was sent by the bot.
On success, the stopped Poll with the final results is returned.
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.String, base.Integer]`
:param message_id: Identifier of the original message with the poll
:type message_id: :obj:`base.Integer`
:param reply_markup: A JSON-serialized object for a new message inline keyboard.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]`
:return: On success, the stopped Poll with the final results is returned.
:rtype: :obj:`types.Poll`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.STOP_POLL, payload)
return types.Poll(**result) | [
"async",
"def",
"stop_poll",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"String",
",",
"base",
".",
"Integer",
"]",
",",
"message_id",
":",
"base",
".",
"Integer",
",",
"reply_markup",
":",
"typing",
".",
"Union",
"[",
... | Use this method to stop a poll which was sent by the bot.
On success, the stopped Poll with the final results is returned.
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.String, base.Integer]`
:param message_id: Identifier of the original message with the poll
:type message_id: :obj:`base.Integer`
:param reply_markup: A JSON-serialized object for a new message inline keyboard.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]`
:return: On success, the stopped Poll with the final results is returned.
:rtype: :obj:`types.Poll` | [
"Use",
"this",
"method",
"to",
"stop",
"a",
"poll",
"which",
"was",
"sent",
"by",
"the",
"bot",
".",
"On",
"success",
"the",
"stopped",
"Poll",
"with",
"the",
"final",
"results",
"is",
"returned",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1564-L1583 |
224,769 | aiogram/aiogram | aiogram/bot/bot.py | Bot.get_sticker_set | async def get_sticker_set(self, name: base.String) -> types.StickerSet:
"""
Use this method to get a sticker set.
Source: https://core.telegram.org/bots/api#getstickerset
:param name: Name of the sticker set
:type name: :obj:`base.String`
:return: On success, a StickerSet object is returned
:rtype: :obj:`types.StickerSet`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_STICKER_SET, payload)
return types.StickerSet(**result) | python | async def get_sticker_set(self, name: base.String) -> types.StickerSet:
"""
Use this method to get a sticker set.
Source: https://core.telegram.org/bots/api#getstickerset
:param name: Name of the sticker set
:type name: :obj:`base.String`
:return: On success, a StickerSet object is returned
:rtype: :obj:`types.StickerSet`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.GET_STICKER_SET, payload)
return types.StickerSet(**result) | [
"async",
"def",
"get_sticker_set",
"(",
"self",
",",
"name",
":",
"base",
".",
"String",
")",
"->",
"types",
".",
"StickerSet",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"result",
"=",
"await",
"self",
".",
"reque... | Use this method to get a sticker set.
Source: https://core.telegram.org/bots/api#getstickerset
:param name: Name of the sticker set
:type name: :obj:`base.String`
:return: On success, a StickerSet object is returned
:rtype: :obj:`types.StickerSet` | [
"Use",
"this",
"method",
"to",
"get",
"a",
"sticker",
"set",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1649-L1663 |
224,770 | aiogram/aiogram | aiogram/bot/bot.py | Bot.create_new_sticker_set | async def create_new_sticker_set(self, user_id: base.Integer, name: base.String, title: base.String,
png_sticker: typing.Union[base.InputFile, base.String], emojis: base.String,
contains_masks: typing.Union[base.Boolean, None] = None,
mask_position: typing.Union[types.MaskPosition, None] = None) -> base.Boolean:
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
Source: https://core.telegram.org/bots/api#createnewstickerset
:param user_id: User identifier of created sticker set owner
:type user_id: :obj:`base.Integer`
:param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals)
:type name: :obj:`base.String`
:param title: Sticker set title, 1-64 characters
:type title: :obj:`base.String`
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size,
dimensions must not exceed 512px, and either width or height must be exactly 512px.
:type png_sticker: :obj:`typing.Union[base.InputFile, base.String]`
:param emojis: One or more emoji corresponding to the sticker
:type emojis: :obj:`base.String`
:param contains_masks: Pass True, if a set of mask stickers should be created
:type contains_masks: :obj:`typing.Union[base.Boolean, None]`
:param mask_position: A JSON-serialized object for position where the mask should be placed on faces
:type mask_position: :obj:`typing.Union[types.MaskPosition, None]`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
mask_position = prepare_arg(mask_position)
payload = generate_payload(**locals(), exclude=['png_sticker'])
files = {}
prepare_file(payload, files, 'png_sticker', png_sticker)
result = await self.request(api.Methods.CREATE_NEW_STICKER_SET, payload, files)
return result | python | async def create_new_sticker_set(self, user_id: base.Integer, name: base.String, title: base.String,
png_sticker: typing.Union[base.InputFile, base.String], emojis: base.String,
contains_masks: typing.Union[base.Boolean, None] = None,
mask_position: typing.Union[types.MaskPosition, None] = None) -> base.Boolean:
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
Source: https://core.telegram.org/bots/api#createnewstickerset
:param user_id: User identifier of created sticker set owner
:type user_id: :obj:`base.Integer`
:param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals)
:type name: :obj:`base.String`
:param title: Sticker set title, 1-64 characters
:type title: :obj:`base.String`
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size,
dimensions must not exceed 512px, and either width or height must be exactly 512px.
:type png_sticker: :obj:`typing.Union[base.InputFile, base.String]`
:param emojis: One or more emoji corresponding to the sticker
:type emojis: :obj:`base.String`
:param contains_masks: Pass True, if a set of mask stickers should be created
:type contains_masks: :obj:`typing.Union[base.Boolean, None]`
:param mask_position: A JSON-serialized object for position where the mask should be placed on faces
:type mask_position: :obj:`typing.Union[types.MaskPosition, None]`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
mask_position = prepare_arg(mask_position)
payload = generate_payload(**locals(), exclude=['png_sticker'])
files = {}
prepare_file(payload, files, 'png_sticker', png_sticker)
result = await self.request(api.Methods.CREATE_NEW_STICKER_SET, payload, files)
return result | [
"async",
"def",
"create_new_sticker_set",
"(",
"self",
",",
"user_id",
":",
"base",
".",
"Integer",
",",
"name",
":",
"base",
".",
"String",
",",
"title",
":",
"base",
".",
"String",
",",
"png_sticker",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"I... | Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
Source: https://core.telegram.org/bots/api#createnewstickerset
:param user_id: User identifier of created sticker set owner
:type user_id: :obj:`base.Integer`
:param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals)
:type name: :obj:`base.String`
:param title: Sticker set title, 1-64 characters
:type title: :obj:`base.String`
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size,
dimensions must not exceed 512px, and either width or height must be exactly 512px.
:type png_sticker: :obj:`typing.Union[base.InputFile, base.String]`
:param emojis: One or more emoji corresponding to the sticker
:type emojis: :obj:`base.String`
:param contains_masks: Pass True, if a set of mask stickers should be created
:type contains_masks: :obj:`typing.Union[base.Boolean, None]`
:param mask_position: A JSON-serialized object for position where the mask should be placed on faces
:type mask_position: :obj:`typing.Union[types.MaskPosition, None]`
:return: Returns True on success
:rtype: :obj:`base.Boolean` | [
"Use",
"this",
"method",
"to",
"create",
"new",
"sticker",
"set",
"owned",
"by",
"a",
"user",
".",
"The",
"bot",
"will",
"be",
"able",
"to",
"edit",
"the",
"created",
"sticker",
"set",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1688-L1722 |
224,771 | aiogram/aiogram | aiogram/bot/bot.py | Bot.set_sticker_position_in_set | async def set_sticker_position_in_set(self, sticker: base.String, position: base.Integer) -> base.Boolean:
"""
Use this method to move a sticker in a set created by the bot to a specific position.
Source: https://core.telegram.org/bots/api#setstickerpositioninset
:param sticker: File identifier of the sticker
:type sticker: :obj:`base.String`
:param position: New sticker position in the set, zero-based
:type position: :obj:`base.Integer`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.SET_STICKER_POSITION_IN_SET, payload)
return result | python | async def set_sticker_position_in_set(self, sticker: base.String, position: base.Integer) -> base.Boolean:
"""
Use this method to move a sticker in a set created by the bot to a specific position.
Source: https://core.telegram.org/bots/api#setstickerpositioninset
:param sticker: File identifier of the sticker
:type sticker: :obj:`base.String`
:param position: New sticker position in the set, zero-based
:type position: :obj:`base.Integer`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.SET_STICKER_POSITION_IN_SET, payload)
return result | [
"async",
"def",
"set_sticker_position_in_set",
"(",
"self",
",",
"sticker",
":",
"base",
".",
"String",
",",
"position",
":",
"base",
".",
"Integer",
")",
"->",
"base",
".",
"Boolean",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
"locals",
"(",
... | Use this method to move a sticker in a set created by the bot to a specific position.
Source: https://core.telegram.org/bots/api#setstickerpositioninset
:param sticker: File identifier of the sticker
:type sticker: :obj:`base.String`
:param position: New sticker position in the set, zero-based
:type position: :obj:`base.Integer`
:return: Returns True on success
:rtype: :obj:`base.Boolean` | [
"Use",
"this",
"method",
"to",
"move",
"a",
"sticker",
"in",
"a",
"set",
"created",
"by",
"the",
"bot",
"to",
"a",
"specific",
"position",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1755-L1771 |
224,772 | aiogram/aiogram | aiogram/bot/bot.py | Bot.delete_sticker_from_set | async def delete_sticker_from_set(self, sticker: base.String) -> base.Boolean:
"""
Use this method to delete a sticker from a set created by the bot.
The following methods and objects allow your bot to work in inline mode.
Source: https://core.telegram.org/bots/api#deletestickerfromset
:param sticker: File identifier of the sticker
:type sticker: :obj:`base.String`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.DELETE_STICKER_FROM_SET, payload)
return result | python | async def delete_sticker_from_set(self, sticker: base.String) -> base.Boolean:
"""
Use this method to delete a sticker from a set created by the bot.
The following methods and objects allow your bot to work in inline mode.
Source: https://core.telegram.org/bots/api#deletestickerfromset
:param sticker: File identifier of the sticker
:type sticker: :obj:`base.String`
:return: Returns True on success
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.DELETE_STICKER_FROM_SET, payload)
return result | [
"async",
"def",
"delete_sticker_from_set",
"(",
"self",
",",
"sticker",
":",
"base",
".",
"String",
")",
"->",
"base",
".",
"Boolean",
":",
"payload",
"=",
"generate_payload",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"result",
"=",
"await",
"self",
".",
... | Use this method to delete a sticker from a set created by the bot.
The following methods and objects allow your bot to work in inline mode.
Source: https://core.telegram.org/bots/api#deletestickerfromset
:param sticker: File identifier of the sticker
:type sticker: :obj:`base.String`
:return: Returns True on success
:rtype: :obj:`base.Boolean` | [
"Use",
"this",
"method",
"to",
"delete",
"a",
"sticker",
"from",
"a",
"set",
"created",
"by",
"the",
"bot",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1773-L1789 |
224,773 | aiogram/aiogram | aiogram/bot/bot.py | Bot.send_invoice | async def send_invoice(self, chat_id: base.Integer, title: base.String,
description: base.String, payload: base.String,
provider_token: base.String, start_parameter: base.String,
currency: base.String, prices: typing.List[types.LabeledPrice],
provider_data: typing.Union[typing.Dict, None] = None,
photo_url: typing.Union[base.String, None] = None,
photo_size: typing.Union[base.Integer, None] = None,
photo_width: typing.Union[base.Integer, None] = None,
photo_height: typing.Union[base.Integer, None] = None,
need_name: typing.Union[base.Boolean, None] = None,
need_phone_number: typing.Union[base.Boolean, None] = None,
need_email: typing.Union[base.Boolean, None] = None,
need_shipping_address: typing.Union[base.Boolean, None] = None,
is_flexible: typing.Union[base.Boolean, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
reply_to_message_id: typing.Union[base.Integer, None] = None,
reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Message:
"""
Use this method to send invoices.
Source: https://core.telegram.org/bots/api#sendinvoice
:param chat_id: Unique identifier for the target private chat
:type chat_id: :obj:`base.Integer`
:param title: Product name, 1-32 characters
:type title: :obj:`base.String`
:param description: Product description, 1-255 characters
:type description: :obj:`base.String`
:param payload: Bot-defined invoice payload, 1-128 bytes
This will not be displayed to the user, use for your internal processes.
:type payload: :obj:`base.String`
:param provider_token: Payments provider token, obtained via Botfather
:type provider_token: :obj:`base.String`
:param start_parameter: Unique deep-linking parameter that can be used to generate this
invoice when used as a start parameter
:type start_parameter: :obj:`base.String`
:param currency: Three-letter ISO 4217 currency code, see more on currencies
:type currency: :obj:`base.String`
:param prices: Price breakdown, a list of components
(e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
:type prices: :obj:`typing.List[types.LabeledPrice]`
:param provider_data: JSON-encoded data about the invoice, which will be shared with the payment provider
:type provider_data: :obj:`typing.Union[typing.Dict, None]`
:param photo_url: URL of the product photo for the invoice
:type photo_url: :obj:`typing.Union[base.String, None]`
:param photo_size: Photo size
:type photo_size: :obj:`typing.Union[base.Integer, None]`
:param photo_width: Photo width
:type photo_width: :obj:`typing.Union[base.Integer, None]`
:param photo_height: Photo height
:type photo_height: :obj:`typing.Union[base.Integer, None]`
:param need_name: Pass True, if you require the user's full name to complete the order
:type need_name: :obj:`typing.Union[base.Boolean, None]`
:param need_phone_number: Pass True, if you require the user's phone number to complete the order
:type need_phone_number: :obj:`typing.Union[base.Boolean, None]`
:param need_email: Pass True, if you require the user's email to complete the order
:type need_email: :obj:`typing.Union[base.Boolean, None]`
:param need_shipping_address: Pass True, if you require the user's shipping address to complete the order
:type need_shipping_address: :obj:`typing.Union[base.Boolean, None]`
:param is_flexible: Pass True, if the final price depends on the shipping method
:type is_flexible: :obj:`typing.Union[base.Boolean, None]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound
:type disable_notification: :obj:`typing.Union[base.Boolean, None]`
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: :obj:`typing.Union[base.Integer, None]`
:param reply_markup: A JSON-serialized object for an inline keyboard
If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]`
:return: On success, the sent Message is returned
:rtype: :obj:`types.Message`
"""
prices = prepare_arg([price.to_python() if hasattr(price, 'to_python') else price for price in prices])
reply_markup = prepare_arg(reply_markup)
payload_ = generate_payload(**locals())
result = await self.request(api.Methods.SEND_INVOICE, payload_)
return types.Message(**result) | python | async def send_invoice(self, chat_id: base.Integer, title: base.String,
description: base.String, payload: base.String,
provider_token: base.String, start_parameter: base.String,
currency: base.String, prices: typing.List[types.LabeledPrice],
provider_data: typing.Union[typing.Dict, None] = None,
photo_url: typing.Union[base.String, None] = None,
photo_size: typing.Union[base.Integer, None] = None,
photo_width: typing.Union[base.Integer, None] = None,
photo_height: typing.Union[base.Integer, None] = None,
need_name: typing.Union[base.Boolean, None] = None,
need_phone_number: typing.Union[base.Boolean, None] = None,
need_email: typing.Union[base.Boolean, None] = None,
need_shipping_address: typing.Union[base.Boolean, None] = None,
is_flexible: typing.Union[base.Boolean, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
reply_to_message_id: typing.Union[base.Integer, None] = None,
reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Message:
"""
Use this method to send invoices.
Source: https://core.telegram.org/bots/api#sendinvoice
:param chat_id: Unique identifier for the target private chat
:type chat_id: :obj:`base.Integer`
:param title: Product name, 1-32 characters
:type title: :obj:`base.String`
:param description: Product description, 1-255 characters
:type description: :obj:`base.String`
:param payload: Bot-defined invoice payload, 1-128 bytes
This will not be displayed to the user, use for your internal processes.
:type payload: :obj:`base.String`
:param provider_token: Payments provider token, obtained via Botfather
:type provider_token: :obj:`base.String`
:param start_parameter: Unique deep-linking parameter that can be used to generate this
invoice when used as a start parameter
:type start_parameter: :obj:`base.String`
:param currency: Three-letter ISO 4217 currency code, see more on currencies
:type currency: :obj:`base.String`
:param prices: Price breakdown, a list of components
(e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
:type prices: :obj:`typing.List[types.LabeledPrice]`
:param provider_data: JSON-encoded data about the invoice, which will be shared with the payment provider
:type provider_data: :obj:`typing.Union[typing.Dict, None]`
:param photo_url: URL of the product photo for the invoice
:type photo_url: :obj:`typing.Union[base.String, None]`
:param photo_size: Photo size
:type photo_size: :obj:`typing.Union[base.Integer, None]`
:param photo_width: Photo width
:type photo_width: :obj:`typing.Union[base.Integer, None]`
:param photo_height: Photo height
:type photo_height: :obj:`typing.Union[base.Integer, None]`
:param need_name: Pass True, if you require the user's full name to complete the order
:type need_name: :obj:`typing.Union[base.Boolean, None]`
:param need_phone_number: Pass True, if you require the user's phone number to complete the order
:type need_phone_number: :obj:`typing.Union[base.Boolean, None]`
:param need_email: Pass True, if you require the user's email to complete the order
:type need_email: :obj:`typing.Union[base.Boolean, None]`
:param need_shipping_address: Pass True, if you require the user's shipping address to complete the order
:type need_shipping_address: :obj:`typing.Union[base.Boolean, None]`
:param is_flexible: Pass True, if the final price depends on the shipping method
:type is_flexible: :obj:`typing.Union[base.Boolean, None]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound
:type disable_notification: :obj:`typing.Union[base.Boolean, None]`
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: :obj:`typing.Union[base.Integer, None]`
:param reply_markup: A JSON-serialized object for an inline keyboard
If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]`
:return: On success, the sent Message is returned
:rtype: :obj:`types.Message`
"""
prices = prepare_arg([price.to_python() if hasattr(price, 'to_python') else price for price in prices])
reply_markup = prepare_arg(reply_markup)
payload_ = generate_payload(**locals())
result = await self.request(api.Methods.SEND_INVOICE, payload_)
return types.Message(**result) | [
"async",
"def",
"send_invoice",
"(",
"self",
",",
"chat_id",
":",
"base",
".",
"Integer",
",",
"title",
":",
"base",
".",
"String",
",",
"description",
":",
"base",
".",
"String",
",",
"payload",
":",
"base",
".",
"String",
",",
"provider_token",
":",
... | Use this method to send invoices.
Source: https://core.telegram.org/bots/api#sendinvoice
:param chat_id: Unique identifier for the target private chat
:type chat_id: :obj:`base.Integer`
:param title: Product name, 1-32 characters
:type title: :obj:`base.String`
:param description: Product description, 1-255 characters
:type description: :obj:`base.String`
:param payload: Bot-defined invoice payload, 1-128 bytes
This will not be displayed to the user, use for your internal processes.
:type payload: :obj:`base.String`
:param provider_token: Payments provider token, obtained via Botfather
:type provider_token: :obj:`base.String`
:param start_parameter: Unique deep-linking parameter that can be used to generate this
invoice when used as a start parameter
:type start_parameter: :obj:`base.String`
:param currency: Three-letter ISO 4217 currency code, see more on currencies
:type currency: :obj:`base.String`
:param prices: Price breakdown, a list of components
(e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
:type prices: :obj:`typing.List[types.LabeledPrice]`
:param provider_data: JSON-encoded data about the invoice, which will be shared with the payment provider
:type provider_data: :obj:`typing.Union[typing.Dict, None]`
:param photo_url: URL of the product photo for the invoice
:type photo_url: :obj:`typing.Union[base.String, None]`
:param photo_size: Photo size
:type photo_size: :obj:`typing.Union[base.Integer, None]`
:param photo_width: Photo width
:type photo_width: :obj:`typing.Union[base.Integer, None]`
:param photo_height: Photo height
:type photo_height: :obj:`typing.Union[base.Integer, None]`
:param need_name: Pass True, if you require the user's full name to complete the order
:type need_name: :obj:`typing.Union[base.Boolean, None]`
:param need_phone_number: Pass True, if you require the user's phone number to complete the order
:type need_phone_number: :obj:`typing.Union[base.Boolean, None]`
:param need_email: Pass True, if you require the user's email to complete the order
:type need_email: :obj:`typing.Union[base.Boolean, None]`
:param need_shipping_address: Pass True, if you require the user's shipping address to complete the order
:type need_shipping_address: :obj:`typing.Union[base.Boolean, None]`
:param is_flexible: Pass True, if the final price depends on the shipping method
:type is_flexible: :obj:`typing.Union[base.Boolean, None]`
:param disable_notification: Sends the message silently. Users will receive a notification with no sound
:type disable_notification: :obj:`typing.Union[base.Boolean, None]`
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: :obj:`typing.Union[base.Integer, None]`
:param reply_markup: A JSON-serialized object for an inline keyboard
If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
:type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]`
:return: On success, the sent Message is returned
:rtype: :obj:`types.Message` | [
"Use",
"this",
"method",
"to",
"send",
"invoices",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1838-L1914 |
224,774 | aiogram/aiogram | aiogram/bot/bot.py | Bot.answer_shipping_query | async def answer_shipping_query(self, shipping_query_id: base.String, ok: base.Boolean,
shipping_options: typing.Union[typing.List[types.ShippingOption], None] = None,
error_message: typing.Union[base.String, None] = None) -> base.Boolean:
"""
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified,
the Bot API will send an Update with a shipping_query field to the bot.
Source: https://core.telegram.org/bots/api#answershippingquery
:param shipping_query_id: Unique identifier for the query to be answered
:type shipping_query_id: :obj:`base.String`
:param ok: Specify True if delivery to the specified address is possible and False if there are any problems
(for example, if delivery to the specified address is not possible)
:type ok: :obj:`base.Boolean`
:param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options
:type shipping_options: :obj:`typing.Union[typing.List[types.ShippingOption], None]`
:param error_message: Required if ok is False
Error message in human readable form that explains why it is impossible to complete the order
(e.g. "Sorry, delivery to your desired address is unavailable').
Telegram will display this message to the user.
:type error_message: :obj:`typing.Union[base.String, None]`
:return: On success, True is returned
:rtype: :obj:`base.Boolean`
"""
if shipping_options:
shipping_options = prepare_arg([shipping_option.to_python()
if hasattr(shipping_option, 'to_python')
else shipping_option
for shipping_option in shipping_options])
payload = generate_payload(**locals())
result = await self.request(api.Methods.ANSWER_SHIPPING_QUERY, payload)
return result | python | async def answer_shipping_query(self, shipping_query_id: base.String, ok: base.Boolean,
shipping_options: typing.Union[typing.List[types.ShippingOption], None] = None,
error_message: typing.Union[base.String, None] = None) -> base.Boolean:
"""
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified,
the Bot API will send an Update with a shipping_query field to the bot.
Source: https://core.telegram.org/bots/api#answershippingquery
:param shipping_query_id: Unique identifier for the query to be answered
:type shipping_query_id: :obj:`base.String`
:param ok: Specify True if delivery to the specified address is possible and False if there are any problems
(for example, if delivery to the specified address is not possible)
:type ok: :obj:`base.Boolean`
:param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options
:type shipping_options: :obj:`typing.Union[typing.List[types.ShippingOption], None]`
:param error_message: Required if ok is False
Error message in human readable form that explains why it is impossible to complete the order
(e.g. "Sorry, delivery to your desired address is unavailable').
Telegram will display this message to the user.
:type error_message: :obj:`typing.Union[base.String, None]`
:return: On success, True is returned
:rtype: :obj:`base.Boolean`
"""
if shipping_options:
shipping_options = prepare_arg([shipping_option.to_python()
if hasattr(shipping_option, 'to_python')
else shipping_option
for shipping_option in shipping_options])
payload = generate_payload(**locals())
result = await self.request(api.Methods.ANSWER_SHIPPING_QUERY, payload)
return result | [
"async",
"def",
"answer_shipping_query",
"(",
"self",
",",
"shipping_query_id",
":",
"base",
".",
"String",
",",
"ok",
":",
"base",
".",
"Boolean",
",",
"shipping_options",
":",
"typing",
".",
"Union",
"[",
"typing",
".",
"List",
"[",
"types",
".",
"Shippi... | If you sent an invoice requesting a shipping address and the parameter is_flexible was specified,
the Bot API will send an Update with a shipping_query field to the bot.
Source: https://core.telegram.org/bots/api#answershippingquery
:param shipping_query_id: Unique identifier for the query to be answered
:type shipping_query_id: :obj:`base.String`
:param ok: Specify True if delivery to the specified address is possible and False if there are any problems
(for example, if delivery to the specified address is not possible)
:type ok: :obj:`base.Boolean`
:param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options
:type shipping_options: :obj:`typing.Union[typing.List[types.ShippingOption], None]`
:param error_message: Required if ok is False
Error message in human readable form that explains why it is impossible to complete the order
(e.g. "Sorry, delivery to your desired address is unavailable').
Telegram will display this message to the user.
:type error_message: :obj:`typing.Union[base.String, None]`
:return: On success, True is returned
:rtype: :obj:`base.Boolean` | [
"If",
"you",
"sent",
"an",
"invoice",
"requesting",
"a",
"shipping",
"address",
"and",
"the",
"parameter",
"is_flexible",
"was",
"specified",
"the",
"Bot",
"API",
"will",
"send",
"an",
"Update",
"with",
"a",
"shipping_query",
"field",
"to",
"the",
"bot",
"."... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1916-L1948 |
224,775 | aiogram/aiogram | aiogram/bot/bot.py | Bot.answer_pre_checkout_query | async def answer_pre_checkout_query(self, pre_checkout_query_id: base.String, ok: base.Boolean,
error_message: typing.Union[base.String, None] = None) -> base.Boolean:
"""
Once the user has confirmed their payment and shipping details,
the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query.
Use this method to respond to such pre-checkout queries.
Source: https://core.telegram.org/bots/api#answerprecheckoutquery
:param pre_checkout_query_id: Unique identifier for the query to be answered
:type pre_checkout_query_id: :obj:`base.String`
:param ok: Specify True if everything is alright (goods are available, etc.) and the
bot is ready to proceed with the order. Use False if there are any problems.
:type ok: :obj:`base.Boolean`
:param error_message: Required if ok is False
Error message in human readable form that explains the reason for failure to proceed with the checkout
(e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling
out your payment details. Please choose a different color or garment!").
Telegram will display this message to the user.
:type error_message: :obj:`typing.Union[base.String, None]`
:return: On success, True is returned
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.ANSWER_PRE_CHECKOUT_QUERY, payload)
return result | python | async def answer_pre_checkout_query(self, pre_checkout_query_id: base.String, ok: base.Boolean,
error_message: typing.Union[base.String, None] = None) -> base.Boolean:
"""
Once the user has confirmed their payment and shipping details,
the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query.
Use this method to respond to such pre-checkout queries.
Source: https://core.telegram.org/bots/api#answerprecheckoutquery
:param pre_checkout_query_id: Unique identifier for the query to be answered
:type pre_checkout_query_id: :obj:`base.String`
:param ok: Specify True if everything is alright (goods are available, etc.) and the
bot is ready to proceed with the order. Use False if there are any problems.
:type ok: :obj:`base.Boolean`
:param error_message: Required if ok is False
Error message in human readable form that explains the reason for failure to proceed with the checkout
(e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling
out your payment details. Please choose a different color or garment!").
Telegram will display this message to the user.
:type error_message: :obj:`typing.Union[base.String, None]`
:return: On success, True is returned
:rtype: :obj:`base.Boolean`
"""
payload = generate_payload(**locals())
result = await self.request(api.Methods.ANSWER_PRE_CHECKOUT_QUERY, payload)
return result | [
"async",
"def",
"answer_pre_checkout_query",
"(",
"self",
",",
"pre_checkout_query_id",
":",
"base",
".",
"String",
",",
"ok",
":",
"base",
".",
"Boolean",
",",
"error_message",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"String",
",",
"None",
"]",
"="... | Once the user has confirmed their payment and shipping details,
the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query.
Use this method to respond to such pre-checkout queries.
Source: https://core.telegram.org/bots/api#answerprecheckoutquery
:param pre_checkout_query_id: Unique identifier for the query to be answered
:type pre_checkout_query_id: :obj:`base.String`
:param ok: Specify True if everything is alright (goods are available, etc.) and the
bot is ready to proceed with the order. Use False if there are any problems.
:type ok: :obj:`base.Boolean`
:param error_message: Required if ok is False
Error message in human readable form that explains the reason for failure to proceed with the checkout
(e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling
out your payment details. Please choose a different color or garment!").
Telegram will display this message to the user.
:type error_message: :obj:`typing.Union[base.String, None]`
:return: On success, True is returned
:rtype: :obj:`base.Boolean` | [
"Once",
"the",
"user",
"has",
"confirmed",
"their",
"payment",
"and",
"shipping",
"details",
"the",
"Bot",
"API",
"sends",
"the",
"final",
"confirmation",
"in",
"the",
"form",
"of",
"an",
"Update",
"with",
"the",
"field",
"pre_checkout_query",
".",
"Use",
"t... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1950-L1976 |
224,776 | aiogram/aiogram | examples/callback_data_factory.py | get_keyboard | def get_keyboard() -> types.InlineKeyboardMarkup:
"""
Generate keyboard with list of posts
"""
markup = types.InlineKeyboardMarkup()
for post_id, post in POSTS.items():
markup.add(
types.InlineKeyboardButton(
post['title'],
callback_data=posts_cb.new(id=post_id, action='view'))
)
return markup | python | def get_keyboard() -> types.InlineKeyboardMarkup:
"""
Generate keyboard with list of posts
"""
markup = types.InlineKeyboardMarkup()
for post_id, post in POSTS.items():
markup.add(
types.InlineKeyboardButton(
post['title'],
callback_data=posts_cb.new(id=post_id, action='view'))
)
return markup | [
"def",
"get_keyboard",
"(",
")",
"->",
"types",
".",
"InlineKeyboardMarkup",
":",
"markup",
"=",
"types",
".",
"InlineKeyboardMarkup",
"(",
")",
"for",
"post_id",
",",
"post",
"in",
"POSTS",
".",
"items",
"(",
")",
":",
"markup",
".",
"add",
"(",
"types"... | Generate keyboard with list of posts | [
"Generate",
"keyboard",
"with",
"list",
"of",
"posts"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/callback_data_factory.py#L36-L47 |
224,777 | aiogram/aiogram | aiogram/contrib/middlewares/i18n.py | I18nMiddleware.find_locales | def find_locales(self) -> Dict[str, gettext.GNUTranslations]:
"""
Load all compiled locales from path
:return: dict with locales
"""
translations = {}
for name in os.listdir(self.path):
if not os.path.isdir(os.path.join(self.path, name)):
continue
mo_path = os.path.join(self.path, name, 'LC_MESSAGES', self.domain + '.mo')
if os.path.exists(mo_path):
with open(mo_path, 'rb') as fp:
translations[name] = gettext.GNUTranslations(fp)
elif os.path.exists(mo_path[:-2] + 'po'):
raise RuntimeError(f"Found locale '{name} but this language is not compiled!")
return translations | python | def find_locales(self) -> Dict[str, gettext.GNUTranslations]:
"""
Load all compiled locales from path
:return: dict with locales
"""
translations = {}
for name in os.listdir(self.path):
if not os.path.isdir(os.path.join(self.path, name)):
continue
mo_path = os.path.join(self.path, name, 'LC_MESSAGES', self.domain + '.mo')
if os.path.exists(mo_path):
with open(mo_path, 'rb') as fp:
translations[name] = gettext.GNUTranslations(fp)
elif os.path.exists(mo_path[:-2] + 'po'):
raise RuntimeError(f"Found locale '{name} but this language is not compiled!")
return translations | [
"def",
"find_locales",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"gettext",
".",
"GNUTranslations",
"]",
":",
"translations",
"=",
"{",
"}",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"path",
")",
":",
"if",
"not",
"os",
".... | Load all compiled locales from path
:return: dict with locales | [
"Load",
"all",
"compiled",
"locales",
"from",
"path"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/i18n.py#L45-L64 |
224,778 | aiogram/aiogram | aiogram/contrib/middlewares/i18n.py | I18nMiddleware.lazy_gettext | def lazy_gettext(self, singular, plural=None, n=1, locale=None) -> LazyProxy:
"""
Lazy get text
:param singular:
:param plural:
:param n:
:param locale:
:return:
"""
return LazyProxy(self.gettext, singular, plural, n, locale) | python | def lazy_gettext(self, singular, plural=None, n=1, locale=None) -> LazyProxy:
"""
Lazy get text
:param singular:
:param plural:
:param n:
:param locale:
:return:
"""
return LazyProxy(self.gettext, singular, plural, n, locale) | [
"def",
"lazy_gettext",
"(",
"self",
",",
"singular",
",",
"plural",
"=",
"None",
",",
"n",
"=",
"1",
",",
"locale",
"=",
"None",
")",
"->",
"LazyProxy",
":",
"return",
"LazyProxy",
"(",
"self",
".",
"gettext",
",",
"singular",
",",
"plural",
",",
"n"... | Lazy get text
:param singular:
:param plural:
:param n:
:param locale:
:return: | [
"Lazy",
"get",
"text"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/i18n.py#L110-L120 |
224,779 | aiogram/aiogram | aiogram/utils/executor.py | Executor.on_startup | def on_startup(self, callback: callable, polling=True, webhook=True):
"""
Register a callback for the startup process
:param callback:
:param polling: use with polling
:param webhook: use with webhook
"""
self._check_frozen()
if not webhook and not polling:
warn('This action has no effect!', UserWarning)
return
if isinstance(callback, (list, tuple, set)):
for cb in callback:
self.on_startup(cb, polling, webhook)
return
if polling:
self._on_startup_polling.append(callback)
if webhook:
self._on_startup_webhook.append(callback) | python | def on_startup(self, callback: callable, polling=True, webhook=True):
"""
Register a callback for the startup process
:param callback:
:param polling: use with polling
:param webhook: use with webhook
"""
self._check_frozen()
if not webhook and not polling:
warn('This action has no effect!', UserWarning)
return
if isinstance(callback, (list, tuple, set)):
for cb in callback:
self.on_startup(cb, polling, webhook)
return
if polling:
self._on_startup_polling.append(callback)
if webhook:
self._on_startup_webhook.append(callback) | [
"def",
"on_startup",
"(",
"self",
",",
"callback",
":",
"callable",
",",
"polling",
"=",
"True",
",",
"webhook",
"=",
"True",
")",
":",
"self",
".",
"_check_frozen",
"(",
")",
"if",
"not",
"webhook",
"and",
"not",
"polling",
":",
"warn",
"(",
"'This ac... | Register a callback for the startup process
:param callback:
:param polling: use with polling
:param webhook: use with webhook | [
"Register",
"a",
"callback",
"for",
"the",
"startup",
"process"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/executor.py#L166-L187 |
224,780 | aiogram/aiogram | aiogram/utils/executor.py | Executor.on_shutdown | def on_shutdown(self, callback: callable, polling=True, webhook=True):
"""
Register a callback for the shutdown process
:param callback:
:param polling: use with polling
:param webhook: use with webhook
"""
self._check_frozen()
if not webhook and not polling:
warn('This action has no effect!', UserWarning)
return
if isinstance(callback, (list, tuple, set)):
for cb in callback:
self.on_shutdown(cb, polling, webhook)
return
if polling:
self._on_shutdown_polling.append(callback)
if webhook:
self._on_shutdown_webhook.append(callback) | python | def on_shutdown(self, callback: callable, polling=True, webhook=True):
"""
Register a callback for the shutdown process
:param callback:
:param polling: use with polling
:param webhook: use with webhook
"""
self._check_frozen()
if not webhook and not polling:
warn('This action has no effect!', UserWarning)
return
if isinstance(callback, (list, tuple, set)):
for cb in callback:
self.on_shutdown(cb, polling, webhook)
return
if polling:
self._on_shutdown_polling.append(callback)
if webhook:
self._on_shutdown_webhook.append(callback) | [
"def",
"on_shutdown",
"(",
"self",
",",
"callback",
":",
"callable",
",",
"polling",
"=",
"True",
",",
"webhook",
"=",
"True",
")",
":",
"self",
".",
"_check_frozen",
"(",
")",
"if",
"not",
"webhook",
"and",
"not",
"polling",
":",
"warn",
"(",
"'This a... | Register a callback for the shutdown process
:param callback:
:param polling: use with polling
:param webhook: use with webhook | [
"Register",
"a",
"callback",
"for",
"the",
"shutdown",
"process"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/executor.py#L189-L210 |
224,781 | aiogram/aiogram | setup.py | get_requirements | def get_requirements(filename=None):
"""
Read requirements from 'requirements txt'
:return: requirements
:rtype: list
"""
if filename is None:
filename = 'requirements.txt'
file = WORK_DIR / filename
install_reqs = parse_requirements(str(file), session='hack')
return [str(ir.req) for ir in install_reqs] | python | def get_requirements(filename=None):
"""
Read requirements from 'requirements txt'
:return: requirements
:rtype: list
"""
if filename is None:
filename = 'requirements.txt'
file = WORK_DIR / filename
install_reqs = parse_requirements(str(file), session='hack')
return [str(ir.req) for ir in install_reqs] | [
"def",
"get_requirements",
"(",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"'requirements.txt'",
"file",
"=",
"WORK_DIR",
"/",
"filename",
"install_reqs",
"=",
"parse_requirements",
"(",
"str",
"(",
"file",
")",
... | Read requirements from 'requirements txt'
:return: requirements
:rtype: list | [
"Read",
"requirements",
"from",
"requirements",
"txt"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/setup.py#L45-L58 |
224,782 | aiogram/aiogram | aiogram/bot/base.py | BaseBot.request_timeout | def request_timeout(self, timeout):
"""
Context manager implements opportunity to change request timeout in current context
:param timeout:
:return:
"""
timeout = self._prepare_timeout(timeout)
token = self._ctx_timeout.set(timeout)
try:
yield
finally:
self._ctx_timeout.reset(token) | python | def request_timeout(self, timeout):
"""
Context manager implements opportunity to change request timeout in current context
:param timeout:
:return:
"""
timeout = self._prepare_timeout(timeout)
token = self._ctx_timeout.set(timeout)
try:
yield
finally:
self._ctx_timeout.reset(token) | [
"def",
"request_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"timeout",
"=",
"self",
".",
"_prepare_timeout",
"(",
"timeout",
")",
"token",
"=",
"self",
".",
"_ctx_timeout",
".",
"set",
"(",
"timeout",
")",
"try",
":",
"yield",
"finally",
":",
"self"... | Context manager implements opportunity to change request timeout in current context
:param timeout:
:return: | [
"Context",
"manager",
"implements",
"opportunity",
"to",
"change",
"request",
"timeout",
"in",
"current",
"context"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/base.py#L124-L136 |
224,783 | aiogram/aiogram | aiogram/bot/base.py | BaseBot.request | async def request(self, method: base.String,
data: Optional[Dict] = None,
files: Optional[Dict] = None, **kwargs) -> Union[List, Dict, base.Boolean]:
"""
Make an request to Telegram Bot API
https://core.telegram.org/bots/api#making-requests
:param method: API method
:type method: :obj:`str`
:param data: request parameters
:type data: :obj:`dict`
:param files: files
:type files: :obj:`dict`
:return: result
:rtype: Union[List, Dict]
:raise: :obj:`aiogram.exceptions.TelegramApiError`
"""
return await api.make_request(self.session, self.__token, method, data, files,
proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs) | python | async def request(self, method: base.String,
data: Optional[Dict] = None,
files: Optional[Dict] = None, **kwargs) -> Union[List, Dict, base.Boolean]:
"""
Make an request to Telegram Bot API
https://core.telegram.org/bots/api#making-requests
:param method: API method
:type method: :obj:`str`
:param data: request parameters
:type data: :obj:`dict`
:param files: files
:type files: :obj:`dict`
:return: result
:rtype: Union[List, Dict]
:raise: :obj:`aiogram.exceptions.TelegramApiError`
"""
return await api.make_request(self.session, self.__token, method, data, files,
proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs) | [
"async",
"def",
"request",
"(",
"self",
",",
"method",
":",
"base",
".",
"String",
",",
"data",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
",",
"files",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"Uni... | Make an request to Telegram Bot API
https://core.telegram.org/bots/api#making-requests
:param method: API method
:type method: :obj:`str`
:param data: request parameters
:type data: :obj:`dict`
:param files: files
:type files: :obj:`dict`
:return: result
:rtype: Union[List, Dict]
:raise: :obj:`aiogram.exceptions.TelegramApiError` | [
"Make",
"an",
"request",
"to",
"Telegram",
"Bot",
"API"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/base.py#L144-L163 |
224,784 | aiogram/aiogram | aiogram/bot/base.py | BaseBot.download_file | async def download_file(self, file_path: base.String,
destination: Optional[base.InputFile] = None,
timeout: Optional[base.Integer] = sentinel,
chunk_size: Optional[base.Integer] = 65536,
seek: Optional[base.Boolean] = True) -> Union[io.BytesIO, io.FileIO]:
"""
Download file by file_path to destination
if You want to automatically create destination (:class:`io.BytesIO`) use default
value of destination and handle result of this method.
:param file_path: file path on telegram server (You can get it from :obj:`aiogram.types.File`)
:type file_path: :obj:`str`
:param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO`
:param timeout: Integer
:param chunk_size: Integer
:param seek: Boolean - go to start of file when downloading is finished.
:return: destination
"""
if destination is None:
destination = io.BytesIO()
url = api.Methods.file_url(token=self.__token, path=file_path)
dest = destination if isinstance(destination, io.IOBase) else open(destination, 'wb')
async with self.session.get(url, timeout=timeout, proxy=self.proxy, proxy_auth=self.proxy_auth) as response:
while True:
chunk = await response.content.read(chunk_size)
if not chunk:
break
dest.write(chunk)
dest.flush()
if seek:
dest.seek(0)
return dest | python | async def download_file(self, file_path: base.String,
destination: Optional[base.InputFile] = None,
timeout: Optional[base.Integer] = sentinel,
chunk_size: Optional[base.Integer] = 65536,
seek: Optional[base.Boolean] = True) -> Union[io.BytesIO, io.FileIO]:
"""
Download file by file_path to destination
if You want to automatically create destination (:class:`io.BytesIO`) use default
value of destination and handle result of this method.
:param file_path: file path on telegram server (You can get it from :obj:`aiogram.types.File`)
:type file_path: :obj:`str`
:param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO`
:param timeout: Integer
:param chunk_size: Integer
:param seek: Boolean - go to start of file when downloading is finished.
:return: destination
"""
if destination is None:
destination = io.BytesIO()
url = api.Methods.file_url(token=self.__token, path=file_path)
dest = destination if isinstance(destination, io.IOBase) else open(destination, 'wb')
async with self.session.get(url, timeout=timeout, proxy=self.proxy, proxy_auth=self.proxy_auth) as response:
while True:
chunk = await response.content.read(chunk_size)
if not chunk:
break
dest.write(chunk)
dest.flush()
if seek:
dest.seek(0)
return dest | [
"async",
"def",
"download_file",
"(",
"self",
",",
"file_path",
":",
"base",
".",
"String",
",",
"destination",
":",
"Optional",
"[",
"base",
".",
"InputFile",
"]",
"=",
"None",
",",
"timeout",
":",
"Optional",
"[",
"base",
".",
"Integer",
"]",
"=",
"s... | Download file by file_path to destination
if You want to automatically create destination (:class:`io.BytesIO`) use default
value of destination and handle result of this method.
:param file_path: file path on telegram server (You can get it from :obj:`aiogram.types.File`)
:type file_path: :obj:`str`
:param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO`
:param timeout: Integer
:param chunk_size: Integer
:param seek: Boolean - go to start of file when downloading is finished.
:return: destination | [
"Download",
"file",
"by",
"file_path",
"to",
"destination"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/base.py#L165-L199 |
224,785 | aiogram/aiogram | aiogram/types/fields.py | BaseField.get_value | def get_value(self, instance):
"""
Get value for the current object instance
:param instance:
:return:
"""
return instance.values.get(self.alias, self.default) | python | def get_value(self, instance):
"""
Get value for the current object instance
:param instance:
:return:
"""
return instance.values.get(self.alias, self.default) | [
"def",
"get_value",
"(",
"self",
",",
"instance",
")",
":",
"return",
"instance",
".",
"values",
".",
"get",
"(",
"self",
".",
"alias",
",",
"self",
".",
"default",
")"
] | Get value for the current object instance
:param instance:
:return: | [
"Get",
"value",
"for",
"the",
"current",
"object",
"instance"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/fields.py#L37-L44 |
224,786 | aiogram/aiogram | aiogram/types/fields.py | BaseField.set_value | def set_value(self, instance, value, parent=None):
"""
Set prop value
:param instance:
:param value:
:param parent:
:return:
"""
self.resolve_base(instance)
value = self.deserialize(value, parent)
instance.values[self.alias] = value
self._trigger_changed(instance, value) | python | def set_value(self, instance, value, parent=None):
"""
Set prop value
:param instance:
:param value:
:param parent:
:return:
"""
self.resolve_base(instance)
value = self.deserialize(value, parent)
instance.values[self.alias] = value
self._trigger_changed(instance, value) | [
"def",
"set_value",
"(",
"self",
",",
"instance",
",",
"value",
",",
"parent",
"=",
"None",
")",
":",
"self",
".",
"resolve_base",
"(",
"instance",
")",
"value",
"=",
"self",
".",
"deserialize",
"(",
"value",
",",
"parent",
")",
"instance",
".",
"value... | Set prop value
:param instance:
:param value:
:param parent:
:return: | [
"Set",
"prop",
"value"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/fields.py#L46-L58 |
224,787 | aiogram/aiogram | aiogram/types/base.py | TelegramObject.clean | def clean(self):
"""
Remove empty values
"""
for key, value in self.values.copy().items():
if value is None:
del self.values[key] | python | def clean(self):
"""
Remove empty values
"""
for key, value in self.values.copy().items():
if value is None:
del self.values[key] | [
"def",
"clean",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"values",
".",
"copy",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"del",
"self",
".",
"values",
"[",
"key",
"]"
] | Remove empty values | [
"Remove",
"empty",
"values"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/base.py#L173-L179 |
224,788 | aiogram/aiogram | aiogram/types/chat.py | Chat.mention | def mention(self):
"""
Get mention if a Chat has a username, or get full name if this is a Private Chat, otherwise None is returned
"""
if self.username:
return '@' + self.username
if self.type == ChatType.PRIVATE:
return self.full_name
return None | python | def mention(self):
"""
Get mention if a Chat has a username, or get full name if this is a Private Chat, otherwise None is returned
"""
if self.username:
return '@' + self.username
if self.type == ChatType.PRIVATE:
return self.full_name
return None | [
"def",
"mention",
"(",
"self",
")",
":",
"if",
"self",
".",
"username",
":",
"return",
"'@'",
"+",
"self",
".",
"username",
"if",
"self",
".",
"type",
"==",
"ChatType",
".",
"PRIVATE",
":",
"return",
"self",
".",
"full_name",
"return",
"None"
] | Get mention if a Chat has a username, or get full name if this is a Private Chat, otherwise None is returned | [
"Get",
"mention",
"if",
"a",
"Chat",
"has",
"a",
"username",
"or",
"get",
"full",
"name",
"if",
"this",
"is",
"a",
"Private",
"Chat",
"otherwise",
"None",
"is",
"returned"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/chat.py#L46-L54 |
224,789 | aiogram/aiogram | aiogram/types/chat.py | Chat.update_chat | async def update_chat(self):
"""
User this method to update Chat data
:return: None
"""
other = await self.bot.get_chat(self.id)
for key, value in other:
self[key] = value | python | async def update_chat(self):
"""
User this method to update Chat data
:return: None
"""
other = await self.bot.get_chat(self.id)
for key, value in other:
self[key] = value | [
"async",
"def",
"update_chat",
"(",
"self",
")",
":",
"other",
"=",
"await",
"self",
".",
"bot",
".",
"get_chat",
"(",
"self",
".",
"id",
")",
"for",
"key",
",",
"value",
"in",
"other",
":",
"self",
"[",
"key",
"]",
"=",
"value"
] | User this method to update Chat data
:return: None | [
"User",
"this",
"method",
"to",
"update",
"Chat",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/chat.py#L90-L99 |
224,790 | aiogram/aiogram | aiogram/types/chat.py | Chat.export_invite_link | async def export_invite_link(self):
"""
Use this method to export an invite link to a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
:return: Returns exported invite link as String on success.
:rtype: :obj:`base.String`
"""
if not self.invite_link:
self.invite_link = await self.bot.export_chat_invite_link(self.id)
return self.invite_link | python | async def export_invite_link(self):
"""
Use this method to export an invite link to a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
:return: Returns exported invite link as String on success.
:rtype: :obj:`base.String`
"""
if not self.invite_link:
self.invite_link = await self.bot.export_chat_invite_link(self.id)
return self.invite_link | [
"async",
"def",
"export_invite_link",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"invite_link",
":",
"self",
".",
"invite_link",
"=",
"await",
"self",
".",
"bot",
".",
"export_chat_invite_link",
"(",
"self",
".",
"id",
")",
"return",
"self",
".",
"... | Use this method to export an invite link to a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
:return: Returns exported invite link as String on success.
:rtype: :obj:`base.String` | [
"Use",
"this",
"method",
"to",
"export",
"an",
"invite",
"link",
"to",
"a",
"supergroup",
"or",
"a",
"channel",
".",
"The",
"bot",
"must",
"be",
"an",
"administrator",
"in",
"the",
"chat",
"for",
"this",
"to",
"work",
"and",
"must",
"have",
"the",
"app... | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/chat.py#L387-L400 |
224,791 | aiogram/aiogram | aiogram/types/chat.py | ChatType.is_group_or_super_group | def is_group_or_super_group(cls, obj) -> bool:
"""
Check chat is group or super-group
:param obj:
:return:
"""
return cls._check(obj, [cls.GROUP, cls.SUPER_GROUP]) | python | def is_group_or_super_group(cls, obj) -> bool:
"""
Check chat is group or super-group
:param obj:
:return:
"""
return cls._check(obj, [cls.GROUP, cls.SUPER_GROUP]) | [
"def",
"is_group_or_super_group",
"(",
"cls",
",",
"obj",
")",
"->",
"bool",
":",
"return",
"cls",
".",
"_check",
"(",
"obj",
",",
"[",
"cls",
".",
"GROUP",
",",
"cls",
".",
"SUPER_GROUP",
"]",
")"
] | Check chat is group or super-group
:param obj:
:return: | [
"Check",
"chat",
"is",
"group",
"or",
"super",
"-",
"group"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/chat.py#L462-L469 |
224,792 | aiogram/aiogram | aiogram/types/message_entity.py | MessageEntity.get_text | def get_text(self, text):
"""
Get value of entity
:param text: full text
:return: part of text
"""
if sys.maxunicode == 0xffff:
return text[self.offset:self.offset + self.length]
if not isinstance(text, bytes):
entity_text = text.encode('utf-16-le')
else:
entity_text = text
entity_text = entity_text[self.offset * 2:(self.offset + self.length) * 2]
return entity_text.decode('utf-16-le') | python | def get_text(self, text):
"""
Get value of entity
:param text: full text
:return: part of text
"""
if sys.maxunicode == 0xffff:
return text[self.offset:self.offset + self.length]
if not isinstance(text, bytes):
entity_text = text.encode('utf-16-le')
else:
entity_text = text
entity_text = entity_text[self.offset * 2:(self.offset + self.length) * 2]
return entity_text.decode('utf-16-le') | [
"def",
"get_text",
"(",
"self",
",",
"text",
")",
":",
"if",
"sys",
".",
"maxunicode",
"==",
"0xffff",
":",
"return",
"text",
"[",
"self",
".",
"offset",
":",
"self",
".",
"offset",
"+",
"self",
".",
"length",
"]",
"if",
"not",
"isinstance",
"(",
"... | Get value of entity
:param text: full text
:return: part of text | [
"Get",
"value",
"of",
"entity"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message_entity.py#L21-L37 |
224,793 | aiogram/aiogram | aiogram/types/message_entity.py | MessageEntity.parse | def parse(self, text, as_html=True):
"""
Get entity value with markup
:param text: original text
:param as_html: as html?
:return: entity text with markup
"""
if not text:
return text
entity_text = self.get_text(text)
if self.type == MessageEntityType.BOLD:
if as_html:
return markdown.hbold(entity_text)
return markdown.bold(entity_text)
elif self.type == MessageEntityType.ITALIC:
if as_html:
return markdown.hitalic(entity_text)
return markdown.italic(entity_text)
elif self.type == MessageEntityType.PRE:
if as_html:
return markdown.hpre(entity_text)
return markdown.pre(entity_text)
elif self.type == MessageEntityType.CODE:
if as_html:
return markdown.hcode(entity_text)
return markdown.code(entity_text)
elif self.type == MessageEntityType.URL:
if as_html:
return markdown.hlink(entity_text, entity_text)
return markdown.link(entity_text, entity_text)
elif self.type == MessageEntityType.TEXT_LINK:
if as_html:
return markdown.hlink(entity_text, self.url)
return markdown.link(entity_text, self.url)
elif self.type == MessageEntityType.TEXT_MENTION and self.user:
return self.user.get_mention(entity_text)
return entity_text | python | def parse(self, text, as_html=True):
"""
Get entity value with markup
:param text: original text
:param as_html: as html?
:return: entity text with markup
"""
if not text:
return text
entity_text = self.get_text(text)
if self.type == MessageEntityType.BOLD:
if as_html:
return markdown.hbold(entity_text)
return markdown.bold(entity_text)
elif self.type == MessageEntityType.ITALIC:
if as_html:
return markdown.hitalic(entity_text)
return markdown.italic(entity_text)
elif self.type == MessageEntityType.PRE:
if as_html:
return markdown.hpre(entity_text)
return markdown.pre(entity_text)
elif self.type == MessageEntityType.CODE:
if as_html:
return markdown.hcode(entity_text)
return markdown.code(entity_text)
elif self.type == MessageEntityType.URL:
if as_html:
return markdown.hlink(entity_text, entity_text)
return markdown.link(entity_text, entity_text)
elif self.type == MessageEntityType.TEXT_LINK:
if as_html:
return markdown.hlink(entity_text, self.url)
return markdown.link(entity_text, self.url)
elif self.type == MessageEntityType.TEXT_MENTION and self.user:
return self.user.get_mention(entity_text)
return entity_text | [
"def",
"parse",
"(",
"self",
",",
"text",
",",
"as_html",
"=",
"True",
")",
":",
"if",
"not",
"text",
":",
"return",
"text",
"entity_text",
"=",
"self",
".",
"get_text",
"(",
"text",
")",
"if",
"self",
".",
"type",
"==",
"MessageEntityType",
".",
"BO... | Get entity value with markup
:param text: original text
:param as_html: as html?
:return: entity text with markup | [
"Get",
"entity",
"value",
"with",
"markup"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message_entity.py#L39-L77 |
224,794 | aiogram/aiogram | aiogram/utils/payload.py | _normalize | def _normalize(obj):
"""
Normalize dicts and lists
:param obj:
:return: normalized object
"""
if isinstance(obj, list):
return [_normalize(item) for item in obj]
elif isinstance(obj, dict):
return {k: _normalize(v) for k, v in obj.items() if v is not None}
elif hasattr(obj, 'to_python'):
return obj.to_python()
return obj | python | def _normalize(obj):
"""
Normalize dicts and lists
:param obj:
:return: normalized object
"""
if isinstance(obj, list):
return [_normalize(item) for item in obj]
elif isinstance(obj, dict):
return {k: _normalize(v) for k, v in obj.items() if v is not None}
elif hasattr(obj, 'to_python'):
return obj.to_python()
return obj | [
"def",
"_normalize",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"[",
"_normalize",
"(",
"item",
")",
"for",
"item",
"in",
"obj",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{"... | Normalize dicts and lists
:param obj:
:return: normalized object | [
"Normalize",
"dicts",
"and",
"lists"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/payload.py#L30-L43 |
224,795 | aiogram/aiogram | aiogram/utils/helper.py | HelperMode._screaming_snake_case | def _screaming_snake_case(cls, text):
"""
Transform text to SCREAMING_SNAKE_CASE
:param text:
:return:
"""
if text.isupper():
return text
result = ''
for pos, symbol in enumerate(text):
if symbol.isupper() and pos > 0:
result += '_' + symbol
else:
result += symbol.upper()
return result | python | def _screaming_snake_case(cls, text):
"""
Transform text to SCREAMING_SNAKE_CASE
:param text:
:return:
"""
if text.isupper():
return text
result = ''
for pos, symbol in enumerate(text):
if symbol.isupper() and pos > 0:
result += '_' + symbol
else:
result += symbol.upper()
return result | [
"def",
"_screaming_snake_case",
"(",
"cls",
",",
"text",
")",
":",
"if",
"text",
".",
"isupper",
"(",
")",
":",
"return",
"text",
"result",
"=",
"''",
"for",
"pos",
",",
"symbol",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"symbol",
".",
"isuppe... | Transform text to SCREAMING_SNAKE_CASE
:param text:
:return: | [
"Transform",
"text",
"to",
"SCREAMING_SNAKE_CASE"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/helper.py#L59-L74 |
224,796 | aiogram/aiogram | aiogram/utils/helper.py | HelperMode._camel_case | def _camel_case(cls, text, first_upper=False):
"""
Transform text to camelCase or CamelCase
:param text:
:param first_upper: first symbol must be upper?
:return:
"""
result = ''
need_upper = False
for pos, symbol in enumerate(text):
if symbol == '_' and pos > 0:
need_upper = True
else:
if need_upper:
result += symbol.upper()
else:
result += symbol.lower()
need_upper = False
if first_upper:
result = result[0].upper() + result[1:]
return result | python | def _camel_case(cls, text, first_upper=False):
"""
Transform text to camelCase or CamelCase
:param text:
:param first_upper: first symbol must be upper?
:return:
"""
result = ''
need_upper = False
for pos, symbol in enumerate(text):
if symbol == '_' and pos > 0:
need_upper = True
else:
if need_upper:
result += symbol.upper()
else:
result += symbol.lower()
need_upper = False
if first_upper:
result = result[0].upper() + result[1:]
return result | [
"def",
"_camel_case",
"(",
"cls",
",",
"text",
",",
"first_upper",
"=",
"False",
")",
":",
"result",
"=",
"''",
"need_upper",
"=",
"False",
"for",
"pos",
",",
"symbol",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"symbol",
"==",
"'_'",
"and",
"po... | Transform text to camelCase or CamelCase
:param text:
:param first_upper: first symbol must be upper?
:return: | [
"Transform",
"text",
"to",
"camelCase",
"or",
"CamelCase"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/helper.py#L89-L110 |
224,797 | aiogram/aiogram | aiogram/utils/helper.py | HelperMode.apply | def apply(cls, text, mode):
"""
Apply mode for text
:param text:
:param mode:
:return:
"""
if mode == cls.SCREAMING_SNAKE_CASE:
return cls._screaming_snake_case(text)
elif mode == cls.snake_case:
return cls._snake_case(text)
elif mode == cls.lowercase:
return cls._snake_case(text).replace('_', '')
elif mode == cls.lowerCamelCase:
return cls._camel_case(text)
elif mode == cls.CamelCase:
return cls._camel_case(text, True)
elif callable(mode):
return mode(text)
return text | python | def apply(cls, text, mode):
"""
Apply mode for text
:param text:
:param mode:
:return:
"""
if mode == cls.SCREAMING_SNAKE_CASE:
return cls._screaming_snake_case(text)
elif mode == cls.snake_case:
return cls._snake_case(text)
elif mode == cls.lowercase:
return cls._snake_case(text).replace('_', '')
elif mode == cls.lowerCamelCase:
return cls._camel_case(text)
elif mode == cls.CamelCase:
return cls._camel_case(text, True)
elif callable(mode):
return mode(text)
return text | [
"def",
"apply",
"(",
"cls",
",",
"text",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"cls",
".",
"SCREAMING_SNAKE_CASE",
":",
"return",
"cls",
".",
"_screaming_snake_case",
"(",
"text",
")",
"elif",
"mode",
"==",
"cls",
".",
"snake_case",
":",
"return",
... | Apply mode for text
:param text:
:param mode:
:return: | [
"Apply",
"mode",
"for",
"text"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/helper.py#L113-L133 |
224,798 | aiogram/aiogram | aiogram/contrib/middlewares/logging.py | LoggingFilter.filter | def filter(self, record: logging.LogRecord):
"""
Extend LogRecord by data from Telegram Update object.
:param record:
:return:
"""
update = types.Update.get_current(True)
if update:
for key, value in self.make_prefix(self.prefix, self.process_update(update)):
setattr(record, key, value)
return True | python | def filter(self, record: logging.LogRecord):
"""
Extend LogRecord by data from Telegram Update object.
:param record:
:return:
"""
update = types.Update.get_current(True)
if update:
for key, value in self.make_prefix(self.prefix, self.process_update(update)):
setattr(record, key, value)
return True | [
"def",
"filter",
"(",
"self",
",",
"record",
":",
"logging",
".",
"LogRecord",
")",
":",
"update",
"=",
"types",
".",
"Update",
".",
"get_current",
"(",
"True",
")",
"if",
"update",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"make_prefix",
"... | Extend LogRecord by data from Telegram Update object.
:param record:
:return: | [
"Extend",
"LogRecord",
"by",
"data",
"from",
"Telegram",
"Update",
"object",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/logging.py#L182-L194 |
224,799 | aiogram/aiogram | aiogram/contrib/middlewares/logging.py | LoggingFilter.process_update | def process_update(self, update: types.Update):
"""
Parse Update object
:param update:
:return:
"""
yield 'update_id', update.update_id
if update.message:
yield 'update_type', 'message'
yield from self.process_message(update.message)
if update.edited_message:
yield 'update_type', 'edited_message'
yield from self.process_message(update.edited_message)
if update.channel_post:
yield 'update_type', 'channel_post'
yield from self.process_message(update.channel_post)
if update.edited_channel_post:
yield 'update_type', 'edited_channel_post'
yield from self.process_message(update.edited_channel_post)
if update.inline_query:
yield 'update_type', 'inline_query'
yield from self.process_inline_query(update.inline_query)
if update.chosen_inline_result:
yield 'update_type', 'chosen_inline_result'
yield from self.process_chosen_inline_result(update.chosen_inline_result)
if update.callback_query:
yield 'update_type', 'callback_query'
yield from self.process_callback_query(update.callback_query)
if update.shipping_query:
yield 'update_type', 'shipping_query'
yield from self.process_shipping_query(update.shipping_query)
if update.pre_checkout_query:
yield 'update_type', 'pre_checkout_query'
yield from self.process_pre_checkout_query(update.pre_checkout_query) | python | def process_update(self, update: types.Update):
"""
Parse Update object
:param update:
:return:
"""
yield 'update_id', update.update_id
if update.message:
yield 'update_type', 'message'
yield from self.process_message(update.message)
if update.edited_message:
yield 'update_type', 'edited_message'
yield from self.process_message(update.edited_message)
if update.channel_post:
yield 'update_type', 'channel_post'
yield from self.process_message(update.channel_post)
if update.edited_channel_post:
yield 'update_type', 'edited_channel_post'
yield from self.process_message(update.edited_channel_post)
if update.inline_query:
yield 'update_type', 'inline_query'
yield from self.process_inline_query(update.inline_query)
if update.chosen_inline_result:
yield 'update_type', 'chosen_inline_result'
yield from self.process_chosen_inline_result(update.chosen_inline_result)
if update.callback_query:
yield 'update_type', 'callback_query'
yield from self.process_callback_query(update.callback_query)
if update.shipping_query:
yield 'update_type', 'shipping_query'
yield from self.process_shipping_query(update.shipping_query)
if update.pre_checkout_query:
yield 'update_type', 'pre_checkout_query'
yield from self.process_pre_checkout_query(update.pre_checkout_query) | [
"def",
"process_update",
"(",
"self",
",",
"update",
":",
"types",
".",
"Update",
")",
":",
"yield",
"'update_id'",
",",
"update",
".",
"update_id",
"if",
"update",
".",
"message",
":",
"yield",
"'update_type'",
",",
"'message'",
"yield",
"from",
"self",
"... | Parse Update object
:param update:
:return: | [
"Parse",
"Update",
"object"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/logging.py#L196-L231 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.