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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 | train | 219,600 |
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 | train | 219,601 |
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 | train | 219,602 |
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 | train | 219,603 |
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 | train | 219,604 |
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 | train | 219,605 |
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 | train | 219,606 |
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 | train | 219,607 |
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 | train | 219,608 |
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 | train | 219,609 |
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 | train | 219,610 |
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 | train | 219,611 |
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 | train | 219,612 |
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 | train | 219,613 |
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 | train | 219,614 |
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 | train | 219,615 |
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 | train | 219,616 |
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 | train | 219,617 |
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 | train | 219,618 |
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 | train | 219,619 |
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 | train | 219,620 |
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 | train | 219,621 |
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 | train | 219,622 |
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 | train | 219,623 |
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 | train | 219,624 |
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 | train | 219,625 |
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 | train | 219,626 |
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 | train | 219,627 |
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 | train | 219,628 |
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 | train | 219,629 |
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 | train | 219,630 |
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 | train | 219,631 |
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 | train | 219,632 |
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 | train | 219,633 |
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 | train | 219,634 |
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 | train | 219,635 |
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 | train | 219,636 |
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 | train | 219,637 |
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 | train | 219,638 |
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 | train | 219,639 |
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 | train | 219,640 |
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 | train | 219,641 |
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 | train | 219,642 |
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 | train | 219,643 |
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 | train | 219,644 |
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 | train | 219,645 |
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 | train | 219,646 |
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 | train | 219,647 |
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 | train | 219,648 |
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 | train | 219,649 |
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 | train | 219,650 |
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 | train | 219,651 |
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 | train | 219,652 |
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 | train | 219,653 |
aiogram/aiogram | aiogram/contrib/middlewares/logging.py | LoggingFilter.make_prefix | def make_prefix(self, prefix, iterable):
"""
Add prefix to the label
:param prefix:
:param iterable:
:return:
"""
if not prefix:
yield from iterable
for key, value in iterable:
yield f"{prefix}_{key}", value | python | def make_prefix(self, prefix, iterable):
"""
Add prefix to the label
:param prefix:
:param iterable:
:return:
"""
if not prefix:
yield from iterable
for key, value in iterable:
yield f"{prefix}_{key}", value | [
"def",
"make_prefix",
"(",
"self",
",",
"prefix",
",",
"iterable",
")",
":",
"if",
"not",
"prefix",
":",
"yield",
"from",
"iterable",
"for",
"key",
",",
"value",
"in",
"iterable",
":",
"yield",
"f\"{prefix}_{key}\"",
",",
"value"
] | Add prefix to the label
:param prefix:
:param iterable:
:return: | [
"Add",
"prefix",
"to",
"the",
"label"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/logging.py#L233-L245 | train | 219,654 |
aiogram/aiogram | aiogram/contrib/middlewares/logging.py | LoggingFilter.process_user | def process_user(self, user: types.User):
"""
Generate user data
:param user:
:return:
"""
if not user:
return
yield 'user_id', user.id
if self.include_content:
yield 'user_full_name', user.full_name
if user.username:
yield 'user_name', f"@{user.username}" | python | def process_user(self, user: types.User):
"""
Generate user data
:param user:
:return:
"""
if not user:
return
yield 'user_id', user.id
if self.include_content:
yield 'user_full_name', user.full_name
if user.username:
yield 'user_name', f"@{user.username}" | [
"def",
"process_user",
"(",
"self",
",",
"user",
":",
"types",
".",
"User",
")",
":",
"if",
"not",
"user",
":",
"return",
"yield",
"'user_id'",
",",
"user",
".",
"id",
"if",
"self",
".",
"include_content",
":",
"yield",
"'user_full_name'",
",",
"user",
... | Generate user data
:param user:
:return: | [
"Generate",
"user",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/logging.py#L247-L261 | train | 219,655 |
aiogram/aiogram | aiogram/contrib/middlewares/logging.py | LoggingFilter.process_chat | def process_chat(self, chat: types.Chat):
"""
Generate chat data
:param chat:
:return:
"""
if not chat:
return
yield 'chat_id', chat.id
yield 'chat_type', chat.type
if self.include_content:
yield 'chat_title', chat.full_name
if chat.username:
yield 'chat_name', f"@{chat.username}" | python | def process_chat(self, chat: types.Chat):
"""
Generate chat data
:param chat:
:return:
"""
if not chat:
return
yield 'chat_id', chat.id
yield 'chat_type', chat.type
if self.include_content:
yield 'chat_title', chat.full_name
if chat.username:
yield 'chat_name', f"@{chat.username}" | [
"def",
"process_chat",
"(",
"self",
",",
"chat",
":",
"types",
".",
"Chat",
")",
":",
"if",
"not",
"chat",
":",
"return",
"yield",
"'chat_id'",
",",
"chat",
".",
"id",
"yield",
"'chat_type'",
",",
"chat",
".",
"type",
"if",
"self",
".",
"include_conten... | Generate chat data
:param chat:
:return: | [
"Generate",
"chat",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/logging.py#L263-L278 | train | 219,656 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.process_updates | async def process_updates(self, updates, fast: typing.Optional[bool] = True):
"""
Process list of updates
:param updates:
:param fast:
:return:
"""
if fast:
tasks = []
for update in updates:
tasks.append(self.updates_handler.notify(update))
return await asyncio.gather(*tasks)
results = []
for update in updates:
results.append(await self.updates_handler.notify(update))
return results | python | async def process_updates(self, updates, fast: typing.Optional[bool] = True):
"""
Process list of updates
:param updates:
:param fast:
:return:
"""
if fast:
tasks = []
for update in updates:
tasks.append(self.updates_handler.notify(update))
return await asyncio.gather(*tasks)
results = []
for update in updates:
results.append(await self.updates_handler.notify(update))
return results | [
"async",
"def",
"process_updates",
"(",
"self",
",",
"updates",
",",
"fast",
":",
"typing",
".",
"Optional",
"[",
"bool",
"]",
"=",
"True",
")",
":",
"if",
"fast",
":",
"tasks",
"=",
"[",
"]",
"for",
"update",
"in",
"updates",
":",
"tasks",
".",
"a... | Process list of updates
:param updates:
:param fast:
:return: | [
"Process",
"list",
"of",
"updates"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L130-L147 | train | 219,657 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.process_update | async def process_update(self, update: types.Update):
"""
Process single update object
:param update:
:return:
"""
types.Update.set_current(update)
try:
if update.message:
types.User.set_current(update.message.from_user)
types.Chat.set_current(update.message.chat)
return await self.message_handlers.notify(update.message)
if update.edited_message:
types.User.set_current(update.edited_message.from_user)
types.Chat.set_current(update.edited_message.chat)
return await self.edited_message_handlers.notify(update.edited_message)
if update.channel_post:
types.Chat.set_current(update.channel_post.chat)
return await self.channel_post_handlers.notify(update.channel_post)
if update.edited_channel_post:
types.Chat.set_current(update.edited_channel_post.chat)
return await self.edited_channel_post_handlers.notify(update.edited_channel_post)
if update.inline_query:
types.User.set_current(update.inline_query.from_user)
return await self.inline_query_handlers.notify(update.inline_query)
if update.chosen_inline_result:
types.User.set_current(update.chosen_inline_result.from_user)
return await self.chosen_inline_result_handlers.notify(update.chosen_inline_result)
if update.callback_query:
if update.callback_query.message:
types.Chat.set_current(update.callback_query.message.chat)
types.User.set_current(update.callback_query.from_user)
return await self.callback_query_handlers.notify(update.callback_query)
if update.shipping_query:
types.User.set_current(update.shipping_query.from_user)
return await self.shipping_query_handlers.notify(update.shipping_query)
if update.pre_checkout_query:
types.User.set_current(update.pre_checkout_query.from_user)
return await self.pre_checkout_query_handlers.notify(update.pre_checkout_query)
if update.poll:
return await self.poll_handlers.notify(update.poll)
except Exception as e:
err = await self.errors_handlers.notify(update, e)
if err:
return err
raise | python | async def process_update(self, update: types.Update):
"""
Process single update object
:param update:
:return:
"""
types.Update.set_current(update)
try:
if update.message:
types.User.set_current(update.message.from_user)
types.Chat.set_current(update.message.chat)
return await self.message_handlers.notify(update.message)
if update.edited_message:
types.User.set_current(update.edited_message.from_user)
types.Chat.set_current(update.edited_message.chat)
return await self.edited_message_handlers.notify(update.edited_message)
if update.channel_post:
types.Chat.set_current(update.channel_post.chat)
return await self.channel_post_handlers.notify(update.channel_post)
if update.edited_channel_post:
types.Chat.set_current(update.edited_channel_post.chat)
return await self.edited_channel_post_handlers.notify(update.edited_channel_post)
if update.inline_query:
types.User.set_current(update.inline_query.from_user)
return await self.inline_query_handlers.notify(update.inline_query)
if update.chosen_inline_result:
types.User.set_current(update.chosen_inline_result.from_user)
return await self.chosen_inline_result_handlers.notify(update.chosen_inline_result)
if update.callback_query:
if update.callback_query.message:
types.Chat.set_current(update.callback_query.message.chat)
types.User.set_current(update.callback_query.from_user)
return await self.callback_query_handlers.notify(update.callback_query)
if update.shipping_query:
types.User.set_current(update.shipping_query.from_user)
return await self.shipping_query_handlers.notify(update.shipping_query)
if update.pre_checkout_query:
types.User.set_current(update.pre_checkout_query.from_user)
return await self.pre_checkout_query_handlers.notify(update.pre_checkout_query)
if update.poll:
return await self.poll_handlers.notify(update.poll)
except Exception as e:
err = await self.errors_handlers.notify(update, e)
if err:
return err
raise | [
"async",
"def",
"process_update",
"(",
"self",
",",
"update",
":",
"types",
".",
"Update",
")",
":",
"types",
".",
"Update",
".",
"set_current",
"(",
"update",
")",
"try",
":",
"if",
"update",
".",
"message",
":",
"types",
".",
"User",
".",
"set_curren... | Process single update object
:param update:
:return: | [
"Process",
"single",
"update",
"object"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L149-L196 | train | 219,658 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.start_polling | async def start_polling(self,
timeout=20,
relax=0.1,
limit=None,
reset_webhook=None,
fast: typing.Optional[bool] = True,
error_sleep: int = 5):
"""
Start long-polling
:param timeout:
:param relax:
:param limit:
:param reset_webhook:
:param fast:
:return:
"""
if self._polling:
raise RuntimeError('Polling already started')
log.info('Start polling.')
# context.set_value(MODE, LONG_POLLING)
Dispatcher.set_current(self)
Bot.set_current(self.bot)
if reset_webhook is None:
await self.reset_webhook(check=False)
if reset_webhook:
await self.reset_webhook(check=True)
self._polling = True
offset = None
try:
current_request_timeout = self.bot.timeout
if current_request_timeout is not sentinel and timeout is not None:
request_timeout = aiohttp.ClientTimeout(total=current_request_timeout.total + timeout or 1)
else:
request_timeout = None
while self._polling:
try:
with self.bot.request_timeout(request_timeout):
updates = await self.bot.get_updates(limit=limit, offset=offset, timeout=timeout)
except:
log.exception('Cause exception while getting updates.')
await asyncio.sleep(error_sleep)
continue
if updates:
log.debug(f"Received {len(updates)} updates.")
offset = updates[-1].update_id + 1
self.loop.create_task(self._process_polling_updates(updates, fast))
if relax:
await asyncio.sleep(relax)
finally:
self._close_waiter._set_result(None)
log.warning('Polling is stopped.') | python | async def start_polling(self,
timeout=20,
relax=0.1,
limit=None,
reset_webhook=None,
fast: typing.Optional[bool] = True,
error_sleep: int = 5):
"""
Start long-polling
:param timeout:
:param relax:
:param limit:
:param reset_webhook:
:param fast:
:return:
"""
if self._polling:
raise RuntimeError('Polling already started')
log.info('Start polling.')
# context.set_value(MODE, LONG_POLLING)
Dispatcher.set_current(self)
Bot.set_current(self.bot)
if reset_webhook is None:
await self.reset_webhook(check=False)
if reset_webhook:
await self.reset_webhook(check=True)
self._polling = True
offset = None
try:
current_request_timeout = self.bot.timeout
if current_request_timeout is not sentinel and timeout is not None:
request_timeout = aiohttp.ClientTimeout(total=current_request_timeout.total + timeout or 1)
else:
request_timeout = None
while self._polling:
try:
with self.bot.request_timeout(request_timeout):
updates = await self.bot.get_updates(limit=limit, offset=offset, timeout=timeout)
except:
log.exception('Cause exception while getting updates.')
await asyncio.sleep(error_sleep)
continue
if updates:
log.debug(f"Received {len(updates)} updates.")
offset = updates[-1].update_id + 1
self.loop.create_task(self._process_polling_updates(updates, fast))
if relax:
await asyncio.sleep(relax)
finally:
self._close_waiter._set_result(None)
log.warning('Polling is stopped.') | [
"async",
"def",
"start_polling",
"(",
"self",
",",
"timeout",
"=",
"20",
",",
"relax",
"=",
"0.1",
",",
"limit",
"=",
"None",
",",
"reset_webhook",
"=",
"None",
",",
"fast",
":",
"typing",
".",
"Optional",
"[",
"bool",
"]",
"=",
"True",
",",
"error_s... | Start long-polling
:param timeout:
:param relax:
:param limit:
:param reset_webhook:
:param fast:
:return: | [
"Start",
"long",
"-",
"polling"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L212-L272 | train | 219,659 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher._process_polling_updates | async def _process_polling_updates(self, updates, fast: typing.Optional[bool] = True):
"""
Process updates received from long-polling.
:param updates: list of updates.
:param fast:
"""
need_to_call = []
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
for response in responses:
if not isinstance(response, BaseResponse):
continue
need_to_call.append(response.execute_response(self.bot))
if need_to_call:
try:
asyncio.gather(*need_to_call)
except TelegramAPIError:
log.exception('Cause exception while processing updates.') | python | async def _process_polling_updates(self, updates, fast: typing.Optional[bool] = True):
"""
Process updates received from long-polling.
:param updates: list of updates.
:param fast:
"""
need_to_call = []
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
for response in responses:
if not isinstance(response, BaseResponse):
continue
need_to_call.append(response.execute_response(self.bot))
if need_to_call:
try:
asyncio.gather(*need_to_call)
except TelegramAPIError:
log.exception('Cause exception while processing updates.') | [
"async",
"def",
"_process_polling_updates",
"(",
"self",
",",
"updates",
",",
"fast",
":",
"typing",
".",
"Optional",
"[",
"bool",
"]",
"=",
"True",
")",
":",
"need_to_call",
"=",
"[",
"]",
"for",
"responses",
"in",
"itertools",
".",
"chain",
".",
"from_... | Process updates received from long-polling.
:param updates: list of updates.
:param fast: | [
"Process",
"updates",
"received",
"from",
"long",
"-",
"polling",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L274-L291 | train | 219,660 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.stop_polling | def stop_polling(self):
"""
Break long-polling process.
:return:
"""
if hasattr(self, '_polling') and self._polling:
log.info('Stop polling...')
self._polling = False | python | def stop_polling(self):
"""
Break long-polling process.
:return:
"""
if hasattr(self, '_polling') and self._polling:
log.info('Stop polling...')
self._polling = False | [
"def",
"stop_polling",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_polling'",
")",
"and",
"self",
".",
"_polling",
":",
"log",
".",
"info",
"(",
"'Stop polling...'",
")",
"self",
".",
"_polling",
"=",
"False"
] | Break long-polling process.
:return: | [
"Break",
"long",
"-",
"polling",
"process",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L293-L301 | train | 219,661 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_message_handler | def register_message_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for message
.. code-block:: python3
# This handler works only if state is None (by default).
dp.register_message_handler(cmd_start, commands=['start', 'about'])
dp.register_message_handler(entry_point, commands=['setup'])
# This handler works only if current state is "first_step"
dp.register_message_handler(step_handler_1, state="first_step")
# If you want to handle all states by one handler, use `state="*"`.
dp.register_message_handler(cancel_handler, commands=['cancel'], state="*")
dp.register_message_handler(cancel_handler, lambda msg: msg.text.lower() == 'cancel', state="*")
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.message_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.message_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_message_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for message
.. code-block:: python3
# This handler works only if state is None (by default).
dp.register_message_handler(cmd_start, commands=['start', 'about'])
dp.register_message_handler(entry_point, commands=['setup'])
# This handler works only if current state is "first_step"
dp.register_message_handler(step_handler_1, state="first_step")
# If you want to handle all states by one handler, use `state="*"`.
dp.register_message_handler(cancel_handler, commands=['cancel'], state="*")
dp.register_message_handler(cancel_handler, lambda msg: msg.text.lower() == 'cancel', state="*")
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.message_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.message_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_message_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"... | Register handler for message
.. code-block:: python3
# This handler works only if state is None (by default).
dp.register_message_handler(cmd_start, commands=['start', 'about'])
dp.register_message_handler(entry_point, commands=['setup'])
# This handler works only if current state is "first_step"
dp.register_message_handler(step_handler_1, state="first_step")
# If you want to handle all states by one handler, use `state="*"`.
dp.register_message_handler(cancel_handler, commands=['cancel'], state="*")
dp.register_message_handler(cancel_handler, lambda msg: msg.text.lower() == 'cancel', state="*")
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:return: decorated function | [
"Register",
"handler",
"for",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L319-L353 | train | 219,662 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.message_handler | def message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, state=None,
run_task=None, **kwargs):
"""
Decorator for message handler
Examples:
Simple commands handler:
.. code-block:: python3
@dp.message_handler(commands=['start', 'welcome', 'about'])
async def cmd_handler(message: types.Message):
Filter messages by regular expression:
.. code-block:: python3
@dp.message_handler(rexexp='^[a-z]+-[0-9]+')
async def msg_handler(message: types.Message):
Filter messages by command regular expression:
.. code-block:: python3
@dp.message_handler(filters.RegexpCommandsFilter(regexp_commands=['item_([0-9]*)']))
async def send_welcome(message: types.Message):
Filter by content type:
.. code-block:: python3
@dp.message_handler(content_types=ContentType.PHOTO | ContentType.DOCUMENT)
async def audio_handler(message: types.Message):
Filter by custom function:
.. code-block:: python3
@dp.message_handler(lambda message: message.text and 'hello' in message.text.lower())
async def text_handler(message: types.Message):
Use multiple filters:
.. code-block:: python3
@dp.message_handler(commands=['command'], content_types=ContentType.TEXT)
async def text_handler(message: types.Message):
Register multiple filters set for one handler:
.. code-block:: python3
@dp.message_handler(commands=['command'])
@dp.message_handler(lambda message: demojize(message.text) == ':new_moon_with_face:')
async def text_handler(message: types.Message):
This handler will be called if the message starts with '/command' OR is some emoji
By default content_type is :class:`ContentType.TEXT`
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:param run_task: run callback in task (no wait results)
:return: decorated function
"""
def decorator(callback):
self.register_message_handler(callback, *custom_filters,
commands=commands, regexp=regexp, content_types=content_types,
state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, state=None,
run_task=None, **kwargs):
"""
Decorator for message handler
Examples:
Simple commands handler:
.. code-block:: python3
@dp.message_handler(commands=['start', 'welcome', 'about'])
async def cmd_handler(message: types.Message):
Filter messages by regular expression:
.. code-block:: python3
@dp.message_handler(rexexp='^[a-z]+-[0-9]+')
async def msg_handler(message: types.Message):
Filter messages by command regular expression:
.. code-block:: python3
@dp.message_handler(filters.RegexpCommandsFilter(regexp_commands=['item_([0-9]*)']))
async def send_welcome(message: types.Message):
Filter by content type:
.. code-block:: python3
@dp.message_handler(content_types=ContentType.PHOTO | ContentType.DOCUMENT)
async def audio_handler(message: types.Message):
Filter by custom function:
.. code-block:: python3
@dp.message_handler(lambda message: message.text and 'hello' in message.text.lower())
async def text_handler(message: types.Message):
Use multiple filters:
.. code-block:: python3
@dp.message_handler(commands=['command'], content_types=ContentType.TEXT)
async def text_handler(message: types.Message):
Register multiple filters set for one handler:
.. code-block:: python3
@dp.message_handler(commands=['command'])
@dp.message_handler(lambda message: demojize(message.text) == ':new_moon_with_face:')
async def text_handler(message: types.Message):
This handler will be called if the message starts with '/command' OR is some emoji
By default content_type is :class:`ContentType.TEXT`
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:param run_task: run callback in task (no wait results)
:return: decorated function
"""
def decorator(callback):
self.register_message_handler(callback, *custom_filters,
commands=commands, regexp=regexp, content_types=content_types,
state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"message_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
... | Decorator for message handler
Examples:
Simple commands handler:
.. code-block:: python3
@dp.message_handler(commands=['start', 'welcome', 'about'])
async def cmd_handler(message: types.Message):
Filter messages by regular expression:
.. code-block:: python3
@dp.message_handler(rexexp='^[a-z]+-[0-9]+')
async def msg_handler(message: types.Message):
Filter messages by command regular expression:
.. code-block:: python3
@dp.message_handler(filters.RegexpCommandsFilter(regexp_commands=['item_([0-9]*)']))
async def send_welcome(message: types.Message):
Filter by content type:
.. code-block:: python3
@dp.message_handler(content_types=ContentType.PHOTO | ContentType.DOCUMENT)
async def audio_handler(message: types.Message):
Filter by custom function:
.. code-block:: python3
@dp.message_handler(lambda message: message.text and 'hello' in message.text.lower())
async def text_handler(message: types.Message):
Use multiple filters:
.. code-block:: python3
@dp.message_handler(commands=['command'], content_types=ContentType.TEXT)
async def text_handler(message: types.Message):
Register multiple filters set for one handler:
.. code-block:: python3
@dp.message_handler(commands=['command'])
@dp.message_handler(lambda message: demojize(message.text) == ':new_moon_with_face:')
async def text_handler(message: types.Message):
This handler will be called if the message starts with '/command' OR is some emoji
By default content_type is :class:`ContentType.TEXT`
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:param run_task: run callback in task (no wait results)
:return: decorated function | [
"Decorator",
"for",
"message",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L355-L432 | train | 219,663 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.edited_message_handler | def edited_message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited message handler
You can use combination of different handlers
.. code-block:: python3
@dp.message_handler()
@dp.edited_message_handler()
async def msg_handler(message: types.Message):
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_edited_message_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def edited_message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited message handler
You can use combination of different handlers
.. code-block:: python3
@dp.message_handler()
@dp.edited_message_handler()
async def msg_handler(message: types.Message):
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_edited_message_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"edited_message_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
... | Decorator for edited message handler
You can use combination of different handlers
.. code-block:: python3
@dp.message_handler()
@dp.edited_message_handler()
async def msg_handler(message: types.Message):
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Decorator",
"for",
"edited",
"message",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L458-L486 | train | 219,664 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_channel_post_handler | def register_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.channel_post_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.channel_post_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_channel_post_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*"... | Register handler for channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Register",
"handler",
"for",
"channel",
"post"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L488-L510 | train | 219,665 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.channel_post_handler | def channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"channel_post_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
... | Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Decorator",
"for",
"channel",
"post",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L512-L532 | train | 219,666 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_edited_channel_post_handler | def register_edited_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None,
content_types=None, state=None, run_task=None, **kwargs):
"""
Register handler for edited channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.edited_message_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.edited_channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_edited_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None,
content_types=None, state=None, run_task=None, **kwargs):
"""
Register handler for edited channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.edited_message_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.edited_channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_edited_channel_post_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
","... | Register handler for edited channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Register",
"handler",
"for",
"edited",
"channel",
"post"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L534-L556 | train | 219,667 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.edited_channel_post_handler | def edited_channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_edited_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task,
**kwargs)
return callback
return decorator | python | def edited_channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_edited_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task,
**kwargs)
return callback
return decorator | [
"def",
"edited_channel_post_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
... | Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Decorator",
"for",
"edited",
"channel",
"post",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L558-L579 | train | 219,668 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_inline_handler | def register_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for inline query
Example:
.. code-block:: python3
dp.register_inline_handler(some_inline_handler, lambda inline_query: True)
:param callback:
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.inline_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.inline_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for inline query
Example:
.. code-block:: python3
dp.register_inline_handler(some_inline_handler, lambda inline_query: True)
:param callback:
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.inline_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.inline_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_inline_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"custom_filters",
"is",
"None",
":",
"custom_filters",
"=",
"[",
... | Register handler for inline query
Example:
.. code-block:: python3
dp.register_inline_handler(some_inline_handler, lambda inline_query: True)
:param callback:
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Register",
"handler",
"for",
"inline",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L581-L604 | train | 219,669 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.inline_handler | def inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for inline query handler
Example:
.. code-block:: python3
@dp.inline_handler(lambda inline_query: True)
async def some_inline_handler(inline_query: types.InlineQuery)
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for inline query handler
Example:
.. code-block:: python3
@dp.inline_handler(lambda inline_query: True)
async def some_inline_handler(inline_query: types.InlineQuery)
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"inline_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_inline_handler",
"(",
"cal... | Decorator for inline query handler
Example:
.. code-block:: python3
@dp.inline_handler(lambda inline_query: True)
async def some_inline_handler(inline_query: types.InlineQuery)
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Decorator",
"for",
"inline",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L606-L628 | train | 219,670 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_chosen_inline_handler | def register_chosen_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for chosen inline query
Example:
.. code-block:: python3
dp.register_chosen_inline_handler(some_chosen_inline_handler, lambda chosen_inline_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return:
"""
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.chosen_inline_result_handlers,
*custom_filters,
state=state,
**kwargs)
self.chosen_inline_result_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_chosen_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for chosen inline query
Example:
.. code-block:: python3
dp.register_chosen_inline_handler(some_chosen_inline_handler, lambda chosen_inline_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return:
"""
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.chosen_inline_result_handlers,
*custom_filters,
state=state,
**kwargs)
self.chosen_inline_result_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_chosen_inline_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"custom_filters",
"is",
"None",
":",
"custom_filters",
"=",
... | Register handler for chosen inline query
Example:
.. code-block:: python3
dp.register_chosen_inline_handler(some_chosen_inline_handler, lambda chosen_inline_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: | [
"Register",
"handler",
"for",
"chosen",
"inline",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L630-L653 | train | 219,671 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.chosen_inline_handler | def chosen_inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for chosen inline query handler
Example:
.. code-block:: python3
@dp.chosen_inline_handler(lambda chosen_inline_query: True)
async def some_chosen_inline_handler(chosen_inline_query: types.ChosenInlineResult)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return:
"""
def decorator(callback):
self.register_chosen_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def chosen_inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for chosen inline query handler
Example:
.. code-block:: python3
@dp.chosen_inline_handler(lambda chosen_inline_query: True)
async def some_chosen_inline_handler(chosen_inline_query: types.ChosenInlineResult)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return:
"""
def decorator(callback):
self.register_chosen_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"chosen_inline_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_chosen_inline_handler",... | Decorator for chosen inline query handler
Example:
.. code-block:: python3
@dp.chosen_inline_handler(lambda chosen_inline_query: True)
async def some_chosen_inline_handler(chosen_inline_query: types.ChosenInlineResult)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: | [
"Decorator",
"for",
"chosen",
"inline",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L655-L677 | train | 219,672 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_callback_query_handler | def register_callback_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for callback query
Example:
.. code-block:: python3
dp.register_callback_query_handler(some_callback_handler, lambda callback_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.callback_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.callback_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_callback_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for callback query
Example:
.. code-block:: python3
dp.register_callback_query_handler(some_callback_handler, lambda callback_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.callback_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.callback_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_callback_query_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"resolve"... | Register handler for callback query
Example:
.. code-block:: python3
dp.register_callback_query_handler(some_callback_handler, lambda callback_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Register",
"handler",
"for",
"callback",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L679-L699 | train | 219,673 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.callback_query_handler | def callback_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for callback query handler
Example:
.. code-block:: python3
@dp.callback_query_handler(lambda callback_query: True)
async def some_callback_handler(callback_query: types.CallbackQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_callback_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def callback_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for callback query handler
Example:
.. code-block:: python3
@dp.callback_query_handler(lambda callback_query: True)
async def some_callback_handler(callback_query: types.CallbackQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_callback_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"callback_query_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_callback_query_handler... | Decorator for callback query handler
Example:
.. code-block:: python3
@dp.callback_query_handler(lambda callback_query: True)
async def some_callback_handler(callback_query: types.CallbackQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Decorator",
"for",
"callback",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L701-L722 | train | 219,674 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_shipping_query_handler | def register_shipping_query_handler(self, callback, *custom_filters, state=None, run_task=None,
**kwargs):
"""
Register handler for shipping query
Example:
.. code-block:: python3
dp.register_shipping_query_handler(some_shipping_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.shipping_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.shipping_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_shipping_query_handler(self, callback, *custom_filters, state=None, run_task=None,
**kwargs):
"""
Register handler for shipping query
Example:
.. code-block:: python3
dp.register_shipping_query_handler(some_shipping_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.shipping_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.shipping_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_shipping_query_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"resolve"... | Register handler for shipping query
Example:
.. code-block:: python3
dp.register_shipping_query_handler(some_shipping_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Register",
"handler",
"for",
"shipping",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L724-L745 | train | 219,675 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.shipping_query_handler | def shipping_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for shipping query handler
Example:
.. code-block:: python3
@dp.shipping_query_handler(lambda shipping_query: True)
async def some_shipping_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_shipping_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def shipping_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for shipping query handler
Example:
.. code-block:: python3
@dp.shipping_query_handler(lambda shipping_query: True)
async def some_shipping_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_shipping_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"shipping_query_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_shipping_query_handler... | Decorator for shipping query handler
Example:
.. code-block:: python3
@dp.shipping_query_handler(lambda shipping_query: True)
async def some_shipping_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Decorator",
"for",
"shipping",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L747-L768 | train | 219,676 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_pre_checkout_query_handler | def register_pre_checkout_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for pre-checkout query
Example:
.. code-block:: python3
dp.register_pre_checkout_query_handler(some_pre_checkout_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.pre_checkout_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.pre_checkout_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_pre_checkout_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for pre-checkout query
Example:
.. code-block:: python3
dp.register_pre_checkout_query_handler(some_pre_checkout_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.pre_checkout_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.pre_checkout_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_pre_checkout_query_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"reso... | Register handler for pre-checkout query
Example:
.. code-block:: python3
dp.register_pre_checkout_query_handler(some_pre_checkout_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Register",
"handler",
"for",
"pre",
"-",
"checkout",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L770-L790 | train | 219,677 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.pre_checkout_query_handler | def pre_checkout_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for pre-checkout query handler
Example:
.. code-block:: python3
@dp.pre_checkout_query_handler(lambda shipping_query: True)
async def some_pre_checkout_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_pre_checkout_query_handler(callback, *custom_filters, state=state, run_task=run_task,
**kwargs)
return callback
return decorator | python | def pre_checkout_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for pre-checkout query handler
Example:
.. code-block:: python3
@dp.pre_checkout_query_handler(lambda shipping_query: True)
async def some_pre_checkout_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_pre_checkout_query_handler(callback, *custom_filters, state=state, run_task=run_task,
**kwargs)
return callback
return decorator | [
"def",
"pre_checkout_query_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_pre_checkout_query... | Decorator for pre-checkout query handler
Example:
.. code-block:: python3
@dp.pre_checkout_query_handler(lambda shipping_query: True)
async def some_pre_checkout_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Decorator",
"for",
"pre",
"-",
"checkout",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L792-L814 | train | 219,678 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_errors_handler | def register_errors_handler(self, callback, *custom_filters, exception=None, run_task=None, **kwargs):
"""
Register handler for errors
:param callback:
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
"""
filters_set = self.filters_factory.resolve(self.errors_handlers,
*custom_filters,
exception=exception,
**kwargs)
self.errors_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_errors_handler(self, callback, *custom_filters, exception=None, run_task=None, **kwargs):
"""
Register handler for errors
:param callback:
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
"""
filters_set = self.filters_factory.resolve(self.errors_handlers,
*custom_filters,
exception=exception,
**kwargs)
self.errors_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_errors_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"exception",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"resolve",
... | Register handler for errors
:param callback:
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results) | [
"Register",
"handler",
"for",
"errors"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L830-L842 | train | 219,679 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.errors_handler | def errors_handler(self, *custom_filters, exception=None, run_task=None, **kwargs):
"""
Decorator for errors handler
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
:return:
"""
def decorator(callback):
self.register_errors_handler(self._wrap_async_task(callback, run_task),
*custom_filters, exception=exception, **kwargs)
return callback
return decorator | python | def errors_handler(self, *custom_filters, exception=None, run_task=None, **kwargs):
"""
Decorator for errors handler
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
:return:
"""
def decorator(callback):
self.register_errors_handler(self._wrap_async_task(callback, run_task),
*custom_filters, exception=exception, **kwargs)
return callback
return decorator | [
"def",
"errors_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"exception",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_errors_handler",
"(",
... | Decorator for errors handler
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
:return: | [
"Decorator",
"for",
"errors",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L844-L858 | train | 219,680 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.current_state | def current_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> FSMContext:
"""
Get current state for user in chat as context
.. code-block:: python3
with dp.current_state(chat=message.chat.id, user=message.user.id) as state:
pass
state = dp.current_state()
state.set_state('my_state')
:param chat:
:param user:
:return:
"""
if chat is None:
chat_obj = types.Chat.get_current()
chat = chat_obj.id if chat_obj else None
if user is None:
user_obj = types.User.get_current()
user = user_obj.id if user_obj else None
return FSMContext(storage=self.storage, chat=chat, user=user) | python | def current_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> FSMContext:
"""
Get current state for user in chat as context
.. code-block:: python3
with dp.current_state(chat=message.chat.id, user=message.user.id) as state:
pass
state = dp.current_state()
state.set_state('my_state')
:param chat:
:param user:
:return:
"""
if chat is None:
chat_obj = types.Chat.get_current()
chat = chat_obj.id if chat_obj else None
if user is None:
user_obj = types.User.get_current()
user = user_obj.id if user_obj else None
return FSMContext(storage=self.storage, chat=chat, user=user) | [
"def",
"current_state",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
")"... | Get current state for user in chat as context
.. code-block:: python3
with dp.current_state(chat=message.chat.id, user=message.user.id) as state:
pass
state = dp.current_state()
state.set_state('my_state')
:param chat:
:param user:
:return: | [
"Get",
"current",
"state",
"for",
"user",
"in",
"chat",
"as",
"context"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L860-L885 | train | 219,681 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.throttle | async def throttle(self, key, *, rate=None, user=None, chat=None, no_error=None) -> bool:
"""
Execute throttling manager.
Returns True if limit has not exceeded otherwise raises ThrottleError or returns False
:param key: key in storage
:param rate: limit (by default is equal to default rate limit)
:param user: user id
:param chat: chat id
:param no_error: return boolean value instead of raising error
:return: bool
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if no_error is None:
no_error = self.no_throttle_error
if rate is None:
rate = self.throttling_rate_limit
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
# Detect current time
now = time.time()
bucket = await self.storage.get_bucket(chat=chat, user=user)
# Fix bucket
if bucket is None:
bucket = {key: {}}
if key not in bucket:
bucket[key] = {}
data = bucket[key]
# Calculate
called = data.get(LAST_CALL, now)
delta = now - called
result = delta >= rate or delta <= 0
# Save results
data[RESULT] = result
data[RATE_LIMIT] = rate
data[LAST_CALL] = now
data[DELTA] = delta
if not result:
data[EXCEEDED_COUNT] += 1
else:
data[EXCEEDED_COUNT] = 1
bucket[key].update(data)
await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
if not result and not no_error:
# Raise if it is allowed
raise Throttled(key=key, chat=chat, user=user, **data)
return result | python | async def throttle(self, key, *, rate=None, user=None, chat=None, no_error=None) -> bool:
"""
Execute throttling manager.
Returns True if limit has not exceeded otherwise raises ThrottleError or returns False
:param key: key in storage
:param rate: limit (by default is equal to default rate limit)
:param user: user id
:param chat: chat id
:param no_error: return boolean value instead of raising error
:return: bool
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if no_error is None:
no_error = self.no_throttle_error
if rate is None:
rate = self.throttling_rate_limit
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
# Detect current time
now = time.time()
bucket = await self.storage.get_bucket(chat=chat, user=user)
# Fix bucket
if bucket is None:
bucket = {key: {}}
if key not in bucket:
bucket[key] = {}
data = bucket[key]
# Calculate
called = data.get(LAST_CALL, now)
delta = now - called
result = delta >= rate or delta <= 0
# Save results
data[RESULT] = result
data[RATE_LIMIT] = rate
data[LAST_CALL] = now
data[DELTA] = delta
if not result:
data[EXCEEDED_COUNT] += 1
else:
data[EXCEEDED_COUNT] = 1
bucket[key].update(data)
await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
if not result and not no_error:
# Raise if it is allowed
raise Throttled(key=key, chat=chat, user=user, **data)
return result | [
"async",
"def",
"throttle",
"(",
"self",
",",
"key",
",",
"*",
",",
"rate",
"=",
"None",
",",
"user",
"=",
"None",
",",
"chat",
"=",
"None",
",",
"no_error",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"storage",
".",
"has_buck... | Execute throttling manager.
Returns True if limit has not exceeded otherwise raises ThrottleError or returns False
:param key: key in storage
:param rate: limit (by default is equal to default rate limit)
:param user: user id
:param chat: chat id
:param no_error: return boolean value instead of raising error
:return: bool | [
"Execute",
"throttling",
"manager",
".",
"Returns",
"True",
"if",
"limit",
"has",
"not",
"exceeded",
"otherwise",
"raises",
"ThrottleError",
"or",
"returns",
"False"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L887-L942 | train | 219,682 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.check_key | async def check_key(self, key, chat=None, user=None):
"""
Get information about key in bucket
:param key:
:param chat:
:param user:
:return:
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
bucket = await self.storage.get_bucket(chat=chat, user=user)
data = bucket.get(key, {})
return Throttled(key=key, chat=chat, user=user, **data) | python | async def check_key(self, key, chat=None, user=None):
"""
Get information about key in bucket
:param key:
:param chat:
:param user:
:return:
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
bucket = await self.storage.get_bucket(chat=chat, user=user)
data = bucket.get(key, {})
return Throttled(key=key, chat=chat, user=user, **data) | [
"async",
"def",
"check_key",
"(",
"self",
",",
"key",
",",
"chat",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"storage",
".",
"has_bucket",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'This storage does not provide Leaky B... | Get information about key in bucket
:param key:
:param chat:
:param user:
:return: | [
"Get",
"information",
"about",
"key",
"in",
"bucket"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L944-L962 | train | 219,683 |
aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.release_key | async def release_key(self, key, chat=None, user=None):
"""
Release blocked key
:param key:
:param chat:
:param user:
:return:
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
bucket = await self.storage.get_bucket(chat=chat, user=user)
if bucket and key in bucket:
del bucket['key']
await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
return True
return False | python | async def release_key(self, key, chat=None, user=None):
"""
Release blocked key
:param key:
:param chat:
:param user:
:return:
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
bucket = await self.storage.get_bucket(chat=chat, user=user)
if bucket and key in bucket:
del bucket['key']
await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
return True
return False | [
"async",
"def",
"release_key",
"(",
"self",
",",
"key",
",",
"chat",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"storage",
".",
"has_bucket",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'This storage does not provide Leaky... | Release blocked key
:param key:
:param chat:
:param user:
:return: | [
"Release",
"blocked",
"key"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L964-L985 | train | 219,684 |
aiogram/aiogram | aiogram/bot/api.py | check_token | def check_token(token: str) -> bool:
"""
Validate BOT token
:param token:
:return:
"""
if any(x.isspace() for x in token):
raise exceptions.ValidationError('Token is invalid!')
left, sep, right = token.partition(':')
if (not sep) or (not left.isdigit()) or (len(left) < 3):
raise exceptions.ValidationError('Token is invalid!')
return True | python | def check_token(token: str) -> bool:
"""
Validate BOT token
:param token:
:return:
"""
if any(x.isspace() for x in token):
raise exceptions.ValidationError('Token is invalid!')
left, sep, right = token.partition(':')
if (not sep) or (not left.isdigit()) or (len(left) < 3):
raise exceptions.ValidationError('Token is invalid!')
return True | [
"def",
"check_token",
"(",
"token",
":",
"str",
")",
"->",
"bool",
":",
"if",
"any",
"(",
"x",
".",
"isspace",
"(",
")",
"for",
"x",
"in",
"token",
")",
":",
"raise",
"exceptions",
".",
"ValidationError",
"(",
"'Token is invalid!'",
")",
"left",
",",
... | Validate BOT token
:param token:
:return: | [
"Validate",
"BOT",
"token"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/api.py#L20-L34 | train | 219,685 |
aiogram/aiogram | aiogram/bot/api.py | compose_data | def compose_data(params=None, files=None):
"""
Prepare request data
:param params:
:param files:
:return:
"""
data = aiohttp.formdata.FormData(quote_fields=False)
if params:
for key, value in params.items():
data.add_field(key, str(value))
if files:
for key, f in files.items():
if isinstance(f, tuple):
if len(f) == 2:
filename, fileobj = f
else:
raise ValueError('Tuple must have exactly 2 elements: filename, fileobj')
elif isinstance(f, types.InputFile):
filename, fileobj = f.filename, f.file
else:
filename, fileobj = guess_filename(f) or key, f
data.add_field(key, fileobj, filename=filename)
return data | python | def compose_data(params=None, files=None):
"""
Prepare request data
:param params:
:param files:
:return:
"""
data = aiohttp.formdata.FormData(quote_fields=False)
if params:
for key, value in params.items():
data.add_field(key, str(value))
if files:
for key, f in files.items():
if isinstance(f, tuple):
if len(f) == 2:
filename, fileobj = f
else:
raise ValueError('Tuple must have exactly 2 elements: filename, fileobj')
elif isinstance(f, types.InputFile):
filename, fileobj = f.filename, f.file
else:
filename, fileobj = guess_filename(f) or key, f
data.add_field(key, fileobj, filename=filename)
return data | [
"def",
"compose_data",
"(",
"params",
"=",
"None",
",",
"files",
"=",
"None",
")",
":",
"data",
"=",
"aiohttp",
".",
"formdata",
".",
"FormData",
"(",
"quote_fields",
"=",
"False",
")",
"if",
"params",
":",
"for",
"key",
",",
"value",
"in",
"params",
... | Prepare request data
:param params:
:param files:
:return: | [
"Prepare",
"request",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/api.py#L115-L143 | train | 219,686 |
aiogram/aiogram | aiogram/types/user.py | User.full_name | def full_name(self):
"""
You can get full name of user.
:return: str
"""
full_name = self.first_name
if self.last_name:
full_name += ' ' + self.last_name
return full_name | python | def full_name(self):
"""
You can get full name of user.
:return: str
"""
full_name = self.first_name
if self.last_name:
full_name += ' ' + self.last_name
return full_name | [
"def",
"full_name",
"(",
"self",
")",
":",
"full_name",
"=",
"self",
".",
"first_name",
"if",
"self",
".",
"last_name",
":",
"full_name",
"+=",
"' '",
"+",
"self",
".",
"last_name",
"return",
"full_name"
] | You can get full name of user.
:return: str | [
"You",
"can",
"get",
"full",
"name",
"of",
"user",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/user.py#L24-L33 | train | 219,687 |
aiogram/aiogram | aiogram/types/user.py | User.locale | def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_code:
return None
if not hasattr(self, '_locale'):
setattr(self, '_locale', babel.core.Locale.parse(self.language_code, sep='-'))
return getattr(self, '_locale') | python | def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_code:
return None
if not hasattr(self, '_locale'):
setattr(self, '_locale', babel.core.Locale.parse(self.language_code, sep='-'))
return getattr(self, '_locale') | [
"def",
"locale",
"(",
"self",
")",
"->",
"babel",
".",
"core",
".",
"Locale",
"or",
"None",
":",
"if",
"not",
"self",
".",
"language_code",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_locale'",
")",
":",
"setattr",
"(",
"self"... | Get user's locale
:return: :class:`babel.core.Locale` | [
"Get",
"user",
"s",
"locale"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/user.py#L48-L58 | train | 219,688 |
aiogram/aiogram | aiogram/types/mixins.py | Downloadable.get_file | async def get_file(self):
"""
Get file information
:return: :obj:`aiogram.types.File`
"""
if hasattr(self, 'file_path'):
return self
else:
return await self.bot.get_file(self.file_id) | python | async def get_file(self):
"""
Get file information
:return: :obj:`aiogram.types.File`
"""
if hasattr(self, 'file_path'):
return self
else:
return await self.bot.get_file(self.file_id) | [
"async",
"def",
"get_file",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'file_path'",
")",
":",
"return",
"self",
"else",
":",
"return",
"await",
"self",
".",
"bot",
".",
"get_file",
"(",
"self",
".",
"file_id",
")"
] | Get file information
:return: :obj:`aiogram.types.File` | [
"Get",
"file",
"information"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/mixins.py#L37-L46 | train | 219,689 |
aiogram/aiogram | aiogram/dispatcher/middlewares.py | MiddlewareManager.trigger | async def trigger(self, action: str, args: typing.Iterable):
"""
Call action to middlewares with args lilt.
:param action:
:param args:
:return:
"""
for app in self.applications:
await app.trigger(action, args) | python | async def trigger(self, action: str, args: typing.Iterable):
"""
Call action to middlewares with args lilt.
:param action:
:param args:
:return:
"""
for app in self.applications:
await app.trigger(action, args) | [
"async",
"def",
"trigger",
"(",
"self",
",",
"action",
":",
"str",
",",
"args",
":",
"typing",
".",
"Iterable",
")",
":",
"for",
"app",
"in",
"self",
".",
"applications",
":",
"await",
"app",
".",
"trigger",
"(",
"action",
",",
"args",
")"
] | Call action to middlewares with args lilt.
:param action:
:param args:
:return: | [
"Call",
"action",
"to",
"middlewares",
"with",
"args",
"lilt",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/middlewares.py#L41-L50 | train | 219,690 |
aiogram/aiogram | aiogram/dispatcher/middlewares.py | BaseMiddleware.trigger | async def trigger(self, action, args):
"""
Trigger action.
:param action:
:param args:
:return:
"""
handler_name = f"on_{action}"
handler = getattr(self, handler_name, None)
if not handler:
return None
await handler(*args) | python | async def trigger(self, action, args):
"""
Trigger action.
:param action:
:param args:
:return:
"""
handler_name = f"on_{action}"
handler = getattr(self, handler_name, None)
if not handler:
return None
await handler(*args) | [
"async",
"def",
"trigger",
"(",
"self",
",",
"action",
",",
"args",
")",
":",
"handler_name",
"=",
"f\"on_{action}\"",
"handler",
"=",
"getattr",
"(",
"self",
",",
"handler_name",
",",
"None",
")",
"if",
"not",
"handler",
":",
"return",
"None",
"await",
... | Trigger action.
:param action:
:param args:
:return: | [
"Trigger",
"action",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/middlewares.py#L91-L103 | train | 219,691 |
aiogram/aiogram | aiogram/utils/markdown.py | quote_html | def quote_html(content):
"""
Quote HTML symbols
All <, >, & and " symbols that are not a part of a tag or
an HTML entity must be replaced with the corresponding HTML entities
(< with < > with > & with & and " with ").
:param content: str
:return: str
"""
new_content = ''
for symbol in content:
new_content += HTML_QUOTES_MAP[symbol] if symbol in _HQS else symbol
return new_content | python | def quote_html(content):
"""
Quote HTML symbols
All <, >, & and " symbols that are not a part of a tag or
an HTML entity must be replaced with the corresponding HTML entities
(< with < > with > & with & and " with ").
:param content: str
:return: str
"""
new_content = ''
for symbol in content:
new_content += HTML_QUOTES_MAP[symbol] if symbol in _HQS else symbol
return new_content | [
"def",
"quote_html",
"(",
"content",
")",
":",
"new_content",
"=",
"''",
"for",
"symbol",
"in",
"content",
":",
"new_content",
"+=",
"HTML_QUOTES_MAP",
"[",
"symbol",
"]",
"if",
"symbol",
"in",
"_HQS",
"else",
"symbol",
"return",
"new_content"
] | Quote HTML symbols
All <, >, & and " symbols that are not a part of a tag or
an HTML entity must be replaced with the corresponding HTML entities
(< with < > with > & with & and " with ").
:param content: str
:return: str | [
"Quote",
"HTML",
"symbols"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/markdown.py#L39-L53 | train | 219,692 |
aiogram/aiogram | aiogram/contrib/fsm_storage/redis.py | migrate_redis1_to_redis2 | async def migrate_redis1_to_redis2(storage1: RedisStorage, storage2: RedisStorage2):
"""
Helper for migrating from RedisStorage to RedisStorage2
:param storage1: instance of RedisStorage
:param storage2: instance of RedisStorage2
:return:
"""
if not isinstance(storage1, RedisStorage): # better than assertion
raise TypeError(f"{type(storage1)} is not RedisStorage instance.")
if not isinstance(storage2, RedisStorage):
raise TypeError(f"{type(storage2)} is not RedisStorage instance.")
log = logging.getLogger('aiogram.RedisStorage')
for chat, user in await storage1.get_states_list():
state = await storage1.get_state(chat=chat, user=user)
await storage2.set_state(chat=chat, user=user, state=state)
data = await storage1.get_data(chat=chat, user=user)
await storage2.set_data(chat=chat, user=user, data=data)
bucket = await storage1.get_bucket(chat=chat, user=user)
await storage2.set_bucket(chat=chat, user=user, bucket=bucket)
log.info(f"Migrated user {user} in chat {chat}") | python | async def migrate_redis1_to_redis2(storage1: RedisStorage, storage2: RedisStorage2):
"""
Helper for migrating from RedisStorage to RedisStorage2
:param storage1: instance of RedisStorage
:param storage2: instance of RedisStorage2
:return:
"""
if not isinstance(storage1, RedisStorage): # better than assertion
raise TypeError(f"{type(storage1)} is not RedisStorage instance.")
if not isinstance(storage2, RedisStorage):
raise TypeError(f"{type(storage2)} is not RedisStorage instance.")
log = logging.getLogger('aiogram.RedisStorage')
for chat, user in await storage1.get_states_list():
state = await storage1.get_state(chat=chat, user=user)
await storage2.set_state(chat=chat, user=user, state=state)
data = await storage1.get_data(chat=chat, user=user)
await storage2.set_data(chat=chat, user=user, data=data)
bucket = await storage1.get_bucket(chat=chat, user=user)
await storage2.set_bucket(chat=chat, user=user, bucket=bucket)
log.info(f"Migrated user {user} in chat {chat}") | [
"async",
"def",
"migrate_redis1_to_redis2",
"(",
"storage1",
":",
"RedisStorage",
",",
"storage2",
":",
"RedisStorage2",
")",
":",
"if",
"not",
"isinstance",
"(",
"storage1",
",",
"RedisStorage",
")",
":",
"# better than assertion",
"raise",
"TypeError",
"(",
"f\"... | Helper for migrating from RedisStorage to RedisStorage2
:param storage1: instance of RedisStorage
:param storage2: instance of RedisStorage2
:return: | [
"Helper",
"for",
"migrating",
"from",
"RedisStorage",
"to",
"RedisStorage2"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/fsm_storage/redis.py#L378-L403 | train | 219,693 |
aiogram/aiogram | aiogram/contrib/fsm_storage/redis.py | RedisStorage.get_record | async def get_record(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> typing.Dict:
"""
Get record from storage
:param chat:
:param user:
:return:
"""
chat, user = self.check_address(chat=chat, user=user)
addr = f"fsm:{chat}:{user}"
conn = await self.redis()
data = await conn.execute('GET', addr)
if data is None:
return {'state': None, 'data': {}}
return json.loads(data) | python | async def get_record(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> typing.Dict:
"""
Get record from storage
:param chat:
:param user:
:return:
"""
chat, user = self.check_address(chat=chat, user=user)
addr = f"fsm:{chat}:{user}"
conn = await self.redis()
data = await conn.execute('GET', addr)
if data is None:
return {'state': None, 'data': {}}
return json.loads(data) | [
"async",
"def",
"get_record",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None... | Get record from storage
:param chat:
:param user:
:return: | [
"Get",
"record",
"from",
"storage"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/fsm_storage/redis.py#L77-L94 | train | 219,694 |
aiogram/aiogram | aiogram/contrib/fsm_storage/redis.py | RedisStorage.set_record | async def set_record(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None,
state=None, data=None, bucket=None):
"""
Write record to storage
:param bucket:
:param chat:
:param user:
:param state:
:param data:
:return:
"""
if data is None:
data = {}
if bucket is None:
bucket = {}
chat, user = self.check_address(chat=chat, user=user)
addr = f"fsm:{chat}:{user}"
record = {'state': state, 'data': data, 'bucket': bucket}
conn = await self.redis()
await conn.execute('SET', addr, json.dumps(record)) | python | async def set_record(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None,
state=None, data=None, bucket=None):
"""
Write record to storage
:param bucket:
:param chat:
:param user:
:param state:
:param data:
:return:
"""
if data is None:
data = {}
if bucket is None:
bucket = {}
chat, user = self.check_address(chat=chat, user=user)
addr = f"fsm:{chat}:{user}"
record = {'state': state, 'data': data, 'bucket': bucket}
conn = await self.redis()
await conn.execute('SET', addr, json.dumps(record)) | [
"async",
"def",
"set_record",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None... | Write record to storage
:param bucket:
:param chat:
:param user:
:param state:
:param data:
:return: | [
"Write",
"record",
"to",
"storage"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/fsm_storage/redis.py#L96-L119 | train | 219,695 |
niklasf/python-chess | chess/syzygy.py | Tablebase.add_directory | def add_directory(self, directory: PathLike, *, load_wdl: bool = True, load_dtz: bool = True) -> int:
"""
Adds tables from a directory.
By default all available tables with the correct file names
(e.g. WDL files like ``KQvKN.rtbw`` and DTZ files like ``KRBvK.rtbz``)
are added.
The relevant files are lazily opened when the tablebase is actually
probed.
Returns the number of table files that were found.
"""
num = 0
directory = os.path.abspath(directory)
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
tablename, ext = os.path.splitext(filename)
if is_table_name(tablename) and os.path.isfile(path):
if load_wdl:
if ext == self.variant.tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
if load_dtz:
if ext == self.variant.tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
return num | python | def add_directory(self, directory: PathLike, *, load_wdl: bool = True, load_dtz: bool = True) -> int:
"""
Adds tables from a directory.
By default all available tables with the correct file names
(e.g. WDL files like ``KQvKN.rtbw`` and DTZ files like ``KRBvK.rtbz``)
are added.
The relevant files are lazily opened when the tablebase is actually
probed.
Returns the number of table files that were found.
"""
num = 0
directory = os.path.abspath(directory)
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
tablename, ext = os.path.splitext(filename)
if is_table_name(tablename) and os.path.isfile(path):
if load_wdl:
if ext == self.variant.tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
if load_dtz:
if ext == self.variant.tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
return num | [
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
",",
"*",
",",
"load_wdl",
":",
"bool",
"=",
"True",
",",
"load_dtz",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"num",
"=",
"0",
"directory",
"=",
"os",
".",
"path",
"."... | Adds tables from a directory.
By default all available tables with the correct file names
(e.g. WDL files like ``KQvKN.rtbw`` and DTZ files like ``KRBvK.rtbz``)
are added.
The relevant files are lazily opened when the tablebase is actually
probed.
Returns the number of table files that were found. | [
"Adds",
"tables",
"from",
"a",
"directory",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/syzygy.py#L1506-L1539 | train | 219,696 |
niklasf/python-chess | chess/syzygy.py | Tablebase.probe_dtz | def probe_dtz(self, board: chess.Board) -> int:
"""
Probes DTZ tables for distance to zero information.
Both DTZ and WDL tables are required in order to probe for DTZ.
Returns a positive value if the side to move is winning, ``0`` if the
position is a draw and a negative value if the side to move is losing.
More precisely:
+-----+------------------+--------------------------------------------+
| WDL | DTZ | |
+=====+==================+============================================+
| -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in -n plies. |
+-----+------------------+--------------------------------------------+
| -1 | n < -100 | Loss, but draw under the 50-move rule. |
| | | A zeroing move can be forced in -n plies |
| | | or -n - 100 plies (if a later phase is |
| | | responsible for the blessed loss). |
+-----+------------------+--------------------------------------------+
| 0 | 0 | Draw. |
+-----+------------------+--------------------------------------------+
| 1 | 100 < n | Win, but draw under the 50-move rule. |
| | | A zeroing move can be forced in n plies or |
| | | n - 100 plies (if a later phase is |
| | | responsible for the cursed win). |
+-----+------------------+--------------------------------------------+
| 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in n plies. |
+-----+------------------+--------------------------------------------+
The return value can be off by one: a return value -n can mean a
losing zeroing move in in n + 1 plies and a return value +n can mean a
winning zeroing move in n + 1 plies.
This is guaranteed not to happen for positions exactly on the edge of
the 50-move rule, so that (with some care) this never impacts the
result of practical play.
Minmaxing the DTZ values guarantees winning a won position (and drawing
a drawn position), because it makes progress keeping the win in hand.
However the lines are not always the most straightforward ways to win.
Engines like Stockfish calculate themselves, checking with DTZ, but
only play according to DTZ if they can not manage on their own.
>>> import chess
>>> import chess.syzygy
>>>
>>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase:
... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
... print(tablebase.probe_dtz(board))
...
-53
Probing is thread-safe when done with different *board* objects and
if *board* objects are not modified during probing.
:raises: :exc:`KeyError` (or specifically
:exc:`chess.syzygy.MissingTableError`) if the position could not
be found in the tablebase. Use
:func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get
``None`` instead of an exception.
Note that probing corrupted table files is undefined behavior.
"""
v = self.probe_dtz_no_ep(board)
if not board.ep_square or self.variant.captures_compulsory:
return v
v1 = -3
# Generate all en-passant moves.
for move in board.generate_legal_ep():
board.push(move)
try:
v0_plus, _ = self.probe_ab(board, -2, 2)
v0 = -v0_plus
finally:
board.pop()
if v0 > v1:
v1 = v0
if v1 > -3:
v1 = WDL_TO_DTZ[v1 + 2]
if v < -100:
if v1 >= 0:
v = v1
elif v < 0:
if v1 >= 0 or v1 < -100:
v = v1
elif v > 100:
if v1 > 0:
v = v1
elif v > 0:
if v1 == 1:
v = v1
elif v1 >= 0:
v = v1
else:
if all(board.is_en_passant(move) for move in board.generate_legal_moves()):
v = v1
return v | python | def probe_dtz(self, board: chess.Board) -> int:
"""
Probes DTZ tables for distance to zero information.
Both DTZ and WDL tables are required in order to probe for DTZ.
Returns a positive value if the side to move is winning, ``0`` if the
position is a draw and a negative value if the side to move is losing.
More precisely:
+-----+------------------+--------------------------------------------+
| WDL | DTZ | |
+=====+==================+============================================+
| -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in -n plies. |
+-----+------------------+--------------------------------------------+
| -1 | n < -100 | Loss, but draw under the 50-move rule. |
| | | A zeroing move can be forced in -n plies |
| | | or -n - 100 plies (if a later phase is |
| | | responsible for the blessed loss). |
+-----+------------------+--------------------------------------------+
| 0 | 0 | Draw. |
+-----+------------------+--------------------------------------------+
| 1 | 100 < n | Win, but draw under the 50-move rule. |
| | | A zeroing move can be forced in n plies or |
| | | n - 100 plies (if a later phase is |
| | | responsible for the cursed win). |
+-----+------------------+--------------------------------------------+
| 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in n plies. |
+-----+------------------+--------------------------------------------+
The return value can be off by one: a return value -n can mean a
losing zeroing move in in n + 1 plies and a return value +n can mean a
winning zeroing move in n + 1 plies.
This is guaranteed not to happen for positions exactly on the edge of
the 50-move rule, so that (with some care) this never impacts the
result of practical play.
Minmaxing the DTZ values guarantees winning a won position (and drawing
a drawn position), because it makes progress keeping the win in hand.
However the lines are not always the most straightforward ways to win.
Engines like Stockfish calculate themselves, checking with DTZ, but
only play according to DTZ if they can not manage on their own.
>>> import chess
>>> import chess.syzygy
>>>
>>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase:
... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
... print(tablebase.probe_dtz(board))
...
-53
Probing is thread-safe when done with different *board* objects and
if *board* objects are not modified during probing.
:raises: :exc:`KeyError` (or specifically
:exc:`chess.syzygy.MissingTableError`) if the position could not
be found in the tablebase. Use
:func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get
``None`` instead of an exception.
Note that probing corrupted table files is undefined behavior.
"""
v = self.probe_dtz_no_ep(board)
if not board.ep_square or self.variant.captures_compulsory:
return v
v1 = -3
# Generate all en-passant moves.
for move in board.generate_legal_ep():
board.push(move)
try:
v0_plus, _ = self.probe_ab(board, -2, 2)
v0 = -v0_plus
finally:
board.pop()
if v0 > v1:
v1 = v0
if v1 > -3:
v1 = WDL_TO_DTZ[v1 + 2]
if v < -100:
if v1 >= 0:
v = v1
elif v < 0:
if v1 >= 0 or v1 < -100:
v = v1
elif v > 100:
if v1 > 0:
v = v1
elif v > 0:
if v1 == 1:
v = v1
elif v1 >= 0:
v = v1
else:
if all(board.is_en_passant(move) for move in board.generate_legal_moves()):
v = v1
return v | [
"def",
"probe_dtz",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
")",
"->",
"int",
":",
"v",
"=",
"self",
".",
"probe_dtz_no_ep",
"(",
"board",
")",
"if",
"not",
"board",
".",
"ep_square",
"or",
"self",
".",
"variant",
".",
"captures_compulso... | Probes DTZ tables for distance to zero information.
Both DTZ and WDL tables are required in order to probe for DTZ.
Returns a positive value if the side to move is winning, ``0`` if the
position is a draw and a negative value if the side to move is losing.
More precisely:
+-----+------------------+--------------------------------------------+
| WDL | DTZ | |
+=====+==================+============================================+
| -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in -n plies. |
+-----+------------------+--------------------------------------------+
| -1 | n < -100 | Loss, but draw under the 50-move rule. |
| | | A zeroing move can be forced in -n plies |
| | | or -n - 100 plies (if a later phase is |
| | | responsible for the blessed loss). |
+-----+------------------+--------------------------------------------+
| 0 | 0 | Draw. |
+-----+------------------+--------------------------------------------+
| 1 | 100 < n | Win, but draw under the 50-move rule. |
| | | A zeroing move can be forced in n plies or |
| | | n - 100 plies (if a later phase is |
| | | responsible for the cursed win). |
+-----+------------------+--------------------------------------------+
| 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in n plies. |
+-----+------------------+--------------------------------------------+
The return value can be off by one: a return value -n can mean a
losing zeroing move in in n + 1 plies and a return value +n can mean a
winning zeroing move in n + 1 plies.
This is guaranteed not to happen for positions exactly on the edge of
the 50-move rule, so that (with some care) this never impacts the
result of practical play.
Minmaxing the DTZ values guarantees winning a won position (and drawing
a drawn position), because it makes progress keeping the win in hand.
However the lines are not always the most straightforward ways to win.
Engines like Stockfish calculate themselves, checking with DTZ, but
only play according to DTZ if they can not manage on their own.
>>> import chess
>>> import chess.syzygy
>>>
>>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase:
... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
... print(tablebase.probe_dtz(board))
...
-53
Probing is thread-safe when done with different *board* objects and
if *board* objects are not modified during probing.
:raises: :exc:`KeyError` (or specifically
:exc:`chess.syzygy.MissingTableError`) if the position could not
be found in the tablebase. Use
:func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get
``None`` instead of an exception.
Note that probing corrupted table files is undefined behavior. | [
"Probes",
"DTZ",
"tables",
"for",
"distance",
"to",
"zero",
"information",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/syzygy.py#L1809-L1915 | train | 219,697 |
niklasf/python-chess | chess/pgn.py | GameNode.board | def board(self, *, _cache: bool = True) -> chess.Board:
"""
Gets a board with the position of the node.
It's a copy, so modifying the board will not alter the game.
"""
if self.board_cached is not None:
board = self.board_cached()
if board is not None:
return board.copy()
board = self.parent.board(_cache=False)
board.push(self.move)
if _cache:
self.board_cached = weakref.ref(board)
return board.copy()
else:
return board | python | def board(self, *, _cache: bool = True) -> chess.Board:
"""
Gets a board with the position of the node.
It's a copy, so modifying the board will not alter the game.
"""
if self.board_cached is not None:
board = self.board_cached()
if board is not None:
return board.copy()
board = self.parent.board(_cache=False)
board.push(self.move)
if _cache:
self.board_cached = weakref.ref(board)
return board.copy()
else:
return board | [
"def",
"board",
"(",
"self",
",",
"*",
",",
"_cache",
":",
"bool",
"=",
"True",
")",
"->",
"chess",
".",
"Board",
":",
"if",
"self",
".",
"board_cached",
"is",
"not",
"None",
":",
"board",
"=",
"self",
".",
"board_cached",
"(",
")",
"if",
"board",
... | Gets a board with the position of the node.
It's a copy, so modifying the board will not alter the game. | [
"Gets",
"a",
"board",
"with",
"the",
"position",
"of",
"the",
"node",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L139-L157 | train | 219,698 |
niklasf/python-chess | chess/pgn.py | GameNode.root | def root(self) -> "GameNode":
"""Gets the root node, i.e., the game."""
node = self
while node.parent:
node = node.parent
return node | python | def root(self) -> "GameNode":
"""Gets the root node, i.e., the game."""
node = self
while node.parent:
node = node.parent
return node | [
"def",
"root",
"(",
"self",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
"while",
"node",
".",
"parent",
":",
"node",
"=",
"node",
".",
"parent",
"return",
"node"
] | Gets the root node, i.e., the game. | [
"Gets",
"the",
"root",
"node",
"i",
".",
"e",
".",
"the",
"game",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L177-L184 | train | 219,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.