id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
238,600 | 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]:
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 |
238,601 | 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):
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 |
238,602 | 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):
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 |
238,603 | 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):
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 |
238,604 | 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):
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 |
238,605 | 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):
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 |
238,606 | 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):
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 |
238,607 | 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:
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 |
238,608 | 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):
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 |
238,609 | 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):
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 |
238,610 | 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):
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 |
238,611 | 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):
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 |
238,612 | 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):
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 |
238,613 | 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):
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 |
238,614 | 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):
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 |
238,615 | 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):
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 |
238,616 | 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):
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 |
238,617 | 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):
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 |
238,618 | 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):
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 |
238,619 | 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):
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 |
238,620 | 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):
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 |
238,621 | 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):
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 |
238,622 | 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):
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 |
238,623 | 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):
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 |
238,624 | 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):
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 |
238,625 | 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):
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 |
238,626 | 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):
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 |
238,627 | 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):
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 |
238,628 | 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):
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 |
238,629 | 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):
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 |
238,630 | 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):
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 |
238,631 | 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):
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 |
238,632 | 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):
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 |
238,633 | 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):
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 |
238,634 | 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):
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 |
238,635 | 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):
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 |
238,636 | 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):
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 |
238,637 | 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):
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 |
238,638 | 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):
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 |
238,639 | 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):
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 |
238,640 | 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):
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 |
238,641 | 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):
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 |
238,642 | 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):
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 |
238,643 | 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:
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 |
238,644 | 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:
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 |
238,645 | 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):
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 |
238,646 | 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):
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 |
238,647 | 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:
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 |
238,648 | 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):
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 |
238,649 | 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):
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 |
238,650 | 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:
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 |
238,651 | 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):
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 |
238,652 | 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):
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 |
238,653 | 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):
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 |
238,654 | 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):
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 |
238,655 | 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):
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 |
238,656 | 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:
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 |
238,657 | 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):
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 |
238,658 | 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:
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 |
238,659 | 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:
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 |
238,660 | 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:
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 |
238,661 | 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":
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 |
238,662 | niklasf/python-chess | chess/pgn.py | GameNode.end | def end(self) -> "GameNode":
"""Follows the main variation to the end and returns the last node."""
node = self
while node.variations:
node = node.variations[0]
return node | python | def end(self) -> "GameNode":
node = self
while node.variations:
node = node.variations[0]
return node | [
"def",
"end",
"(",
"self",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
"while",
"node",
".",
"variations",
":",
"node",
"=",
"node",
".",
"variations",
"[",
"0",
"]",
"return",
"node"
] | Follows the main variation to the end and returns the last node. | [
"Follows",
"the",
"main",
"variation",
"to",
"the",
"end",
"and",
"returns",
"the",
"last",
"node",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L186-L193 |
238,663 | niklasf/python-chess | chess/pgn.py | GameNode.is_mainline | def is_mainline(self) -> bool:
"""Checks if the node is in the mainline of the game."""
node = self
while node.parent:
parent = node.parent
if not parent.variations or parent.variations[0] != node:
return False
node = parent
return True | python | def is_mainline(self) -> bool:
node = self
while node.parent:
parent = node.parent
if not parent.variations or parent.variations[0] != node:
return False
node = parent
return True | [
"def",
"is_mainline",
"(",
"self",
")",
"->",
"bool",
":",
"node",
"=",
"self",
"while",
"node",
".",
"parent",
":",
"parent",
"=",
"node",
".",
"parent",
"if",
"not",
"parent",
".",
"variations",
"or",
"parent",
".",
"variations",
"[",
"0",
"]",
"!=... | Checks if the node is in the mainline of the game. | [
"Checks",
"if",
"the",
"node",
"is",
"in",
"the",
"mainline",
"of",
"the",
"game",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L213-L225 |
238,664 | niklasf/python-chess | chess/pgn.py | GameNode.is_main_variation | def is_main_variation(self) -> bool:
"""
Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation.
"""
if not self.parent:
return True
return not self.parent.variations or self.parent.variations[0] == self | python | def is_main_variation(self) -> bool:
if not self.parent:
return True
return not self.parent.variations or self.parent.variations[0] == self | [
"def",
"is_main_variation",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"True",
"return",
"not",
"self",
".",
"parent",
".",
"variations",
"or",
"self",
".",
"parent",
".",
"variations",
"[",
"0",
"]",
"==",
... | Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation. | [
"Checks",
"if",
"this",
"node",
"is",
"the",
"first",
"variation",
"from",
"the",
"point",
"of",
"view",
"of",
"its",
"parent",
".",
"The",
"root",
"node",
"is",
"also",
"in",
"the",
"main",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L227-L235 |
238,665 | niklasf/python-chess | chess/pgn.py | GameNode.promote | def promote(self, move: chess.Move) -> None:
"""Moves a variation one up in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i > 0:
self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1] | python | def promote(self, move: chess.Move) -> None:
variation = self[move]
i = self.variations.index(variation)
if i > 0:
self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1] | [
"def",
"promote",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"variation",
"=",
"self",
"[",
"move",
"]",
"i",
"=",
"self",
".",
"variations",
".",
"index",
"(",
"variation",
")",
"if",
"i",
">",
"0",
":",
"self",... | Moves a variation one up in the list of variations. | [
"Moves",
"a",
"variation",
"one",
"up",
"in",
"the",
"list",
"of",
"variations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L263-L268 |
238,666 | niklasf/python-chess | chess/pgn.py | GameNode.demote | def demote(self, move: chess.Move) -> None:
"""Moves a variation one down in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i < len(self.variations) - 1:
self.variations[i + 1], self.variations[i] = self.variations[i], self.variations[i + 1] | python | def demote(self, move: chess.Move) -> None:
variation = self[move]
i = self.variations.index(variation)
if i < len(self.variations) - 1:
self.variations[i + 1], self.variations[i] = self.variations[i], self.variations[i + 1] | [
"def",
"demote",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"variation",
"=",
"self",
"[",
"move",
"]",
"i",
"=",
"self",
".",
"variations",
".",
"index",
"(",
"variation",
")",
"if",
"i",
"<",
"len",
"(",
"self"... | Moves a variation one down in the list of variations. | [
"Moves",
"a",
"variation",
"one",
"down",
"in",
"the",
"list",
"of",
"variations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L270-L275 |
238,667 | niklasf/python-chess | chess/pgn.py | GameNode.remove_variation | def remove_variation(self, move: chess.Move) -> None:
"""Removes a variation."""
self.variations.remove(self.variation(move)) | python | def remove_variation(self, move: chess.Move) -> None:
self.variations.remove(self.variation(move)) | [
"def",
"remove_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"self",
".",
"variations",
".",
"remove",
"(",
"self",
".",
"variation",
"(",
"move",
")",
")"
] | Removes a variation. | [
"Removes",
"a",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L277-L279 |
238,668 | niklasf/python-chess | chess/pgn.py | GameNode.add_variation | def add_variation(self, move: chess.Move, *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode":
"""Creates a child node with the given attributes."""
node = type(self).dangling_node()
node.move = move
node.nags = set(nags)
node.comment = comment
node.starting_comment = starting_comment
node.parent = self
self.variations.append(node)
return node | python | def add_variation(self, move: chess.Move, *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode":
node = type(self).dangling_node()
node.move = move
node.nags = set(nags)
node.comment = comment
node.starting_comment = starting_comment
node.parent = self
self.variations.append(node)
return node | [
"def",
"add_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
",",
"*",
",",
"comment",
":",
"str",
"=",
"\"\"",
",",
"starting_comment",
":",
"str",
"=",
"\"\"",
",",
"nags",
":",
"Iterable",
"[",
"int",
"]",
"=",
"(",
")",
")",
"... | Creates a child node with the given attributes. | [
"Creates",
"a",
"child",
"node",
"with",
"the",
"given",
"attributes",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L281-L291 |
238,669 | niklasf/python-chess | chess/pgn.py | GameNode.add_main_variation | def add_main_variation(self, move: chess.Move, *, comment: str = "") -> "GameNode":
"""
Creates a child node with the given attributes and promotes it to the
main variation.
"""
node = self.add_variation(move, comment=comment)
self.variations.remove(node)
self.variations.insert(0, node)
return node | python | def add_main_variation(self, move: chess.Move, *, comment: str = "") -> "GameNode":
node = self.add_variation(move, comment=comment)
self.variations.remove(node)
self.variations.insert(0, node)
return node | [
"def",
"add_main_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
",",
"*",
",",
"comment",
":",
"str",
"=",
"\"\"",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
".",
"add_variation",
"(",
"move",
",",
"comment",
"=",
"comment",... | Creates a child node with the given attributes and promotes it to the
main variation. | [
"Creates",
"a",
"child",
"node",
"with",
"the",
"given",
"attributes",
"and",
"promotes",
"it",
"to",
"the",
"main",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L293-L301 |
238,670 | niklasf/python-chess | chess/pgn.py | Game.board | def board(self, *, _cache: bool = False) -> chess.Board:
"""
Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``).
"""
return self.headers.board() | python | def board(self, *, _cache: bool = False) -> chess.Board:
return self.headers.board() | [
"def",
"board",
"(",
"self",
",",
"*",
",",
"_cache",
":",
"bool",
"=",
"False",
")",
"->",
"chess",
".",
"Board",
":",
"return",
"self",
".",
"headers",
".",
"board",
"(",
")"
] | Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``). | [
"Gets",
"the",
"starting",
"position",
"of",
"the",
"game",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L432-L439 |
238,671 | niklasf/python-chess | chess/pgn.py | BaseVisitor.parse_san | def parse_san(self, board: chess.Board, san: str) -> chess.Move:
"""
When the visitor is used by a parser, this is called to parse a move
in standard algebraic notation.
You can override the default implementation to work around specific
quirks of your input format.
"""
# Replace zeros with correct castling notation.
if san == "0-0":
san = "O-O"
elif san == "0-0-0":
san = "O-O-O"
return board.parse_san(san) | python | def parse_san(self, board: chess.Board, san: str) -> chess.Move:
# Replace zeros with correct castling notation.
if san == "0-0":
san = "O-O"
elif san == "0-0-0":
san = "O-O-O"
return board.parse_san(san) | [
"def",
"parse_san",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
",",
"san",
":",
"str",
")",
"->",
"chess",
".",
"Move",
":",
"# Replace zeros with correct castling notation.",
"if",
"san",
"==",
"\"0-0\"",
":",
"san",
"=",
"\"O-O\"",
"elif",
"s... | When the visitor is used by a parser, this is called to parse a move
in standard algebraic notation.
You can override the default implementation to work around specific
quirks of your input format. | [
"When",
"the",
"visitor",
"is",
"used",
"by",
"a",
"parser",
"this",
"is",
"called",
"to",
"parse",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L710-L724 |
238,672 | niklasf/python-chess | setup.py | read_description | def read_description():
"""
Reads the description from README.rst and substitutes mentions of the
latest version with a concrete version number.
"""
with open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8") as f:
description = f.read()
# Link to the documentation of the specific version.
description = description.replace(
"//python-chess.readthedocs.io/en/latest/",
"//python-chess.readthedocs.io/en/v{}/".format(chess.__version__))
# Use documentation badge for the specific version.
description = description.replace(
"//readthedocs.org/projects/python-chess/badge/?version=latest",
"//readthedocs.org/projects/python-chess/badge/?version=v{}".format(chess.__version__))
# Show Travis CI build status of the concrete version.
description = description.replace(
"//travis-ci.org/niklasf/python-chess.svg?branch=master",
"//travis-ci.org/niklasf/python-chess.svg?branch=v{}".format(chess.__version__))
# Show Appveyor build status of the concrete version.
description = description.replace(
"/y9k3hdbm0f0nbum9/branch/master",
"/y9k3hdbm0f0nbum9/branch/v{}".format(chess.__version__))
# Remove doctest comments.
description = re.sub(r"\s*# doctest:.*", "", description)
return description | python | def read_description():
with open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8") as f:
description = f.read()
# Link to the documentation of the specific version.
description = description.replace(
"//python-chess.readthedocs.io/en/latest/",
"//python-chess.readthedocs.io/en/v{}/".format(chess.__version__))
# Use documentation badge for the specific version.
description = description.replace(
"//readthedocs.org/projects/python-chess/badge/?version=latest",
"//readthedocs.org/projects/python-chess/badge/?version=v{}".format(chess.__version__))
# Show Travis CI build status of the concrete version.
description = description.replace(
"//travis-ci.org/niklasf/python-chess.svg?branch=master",
"//travis-ci.org/niklasf/python-chess.svg?branch=v{}".format(chess.__version__))
# Show Appveyor build status of the concrete version.
description = description.replace(
"/y9k3hdbm0f0nbum9/branch/master",
"/y9k3hdbm0f0nbum9/branch/v{}".format(chess.__version__))
# Remove doctest comments.
description = re.sub(r"\s*# doctest:.*", "", description)
return description | [
"def",
"read_description",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"README.rst\"",
")",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"descript... | Reads the description from README.rst and substitutes mentions of the
latest version with a concrete version number. | [
"Reads",
"the",
"description",
"from",
"README",
".",
"rst",
"and",
"substitutes",
"mentions",
"of",
"the",
"latest",
"version",
"with",
"a",
"concrete",
"version",
"number",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/setup.py#L40-L71 |
238,673 | niklasf/python-chess | chess/engine.py | popen_uci | async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]:
"""
Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, loop=loop, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | python | async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]:
transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, loop=loop, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | [
"async",
"def",
"popen_uci",
"(",
"command",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"*",
",",
"setpgrp",
":",
"bool",
"=",
"False",
",",
"loop",
"=",
"None",
",",
"*",
"*",
"popen_args",
":",
"Any",
")",
"->",
"Tuple",
... | Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair. | [
"Spawns",
"and",
"initializes",
"an",
"UCI",
"engine",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2158-L2180 |
238,674 | niklasf/python-chess | chess/engine.py | popen_xboard | async def popen_xboard(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, XBoardProtocol]:
"""
Spawns and initializes an XBoard engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await XBoardProtocol.popen(command, setpgrp=setpgrp, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | python | async def popen_xboard(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, XBoardProtocol]:
transport, protocol = await XBoardProtocol.popen(command, setpgrp=setpgrp, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | [
"async",
"def",
"popen_xboard",
"(",
"command",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"*",
",",
"setpgrp",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"popen_args",
":",
"Any",
")",
"->",
"Tuple",
"[",
"asyncio",
".",
"S... | Spawns and initializes an XBoard engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair. | [
"Spawns",
"and",
"initializes",
"an",
"XBoard",
"engine",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2183-L2205 |
238,675 | niklasf/python-chess | chess/engine.py | UciProtocol.debug | def debug(self, on: bool = True) -> None:
"""
Switches debug mode of the engine on or off. This does not interrupt
other ongoing operations.
"""
if on:
self.send_line("debug on")
else:
self.send_line("debug off") | python | def debug(self, on: bool = True) -> None:
if on:
self.send_line("debug on")
else:
self.send_line("debug off") | [
"def",
"debug",
"(",
"self",
",",
"on",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"on",
":",
"self",
".",
"send_line",
"(",
"\"debug on\"",
")",
"else",
":",
"self",
".",
"send_line",
"(",
"\"debug off\"",
")"
] | Switches debug mode of the engine on or off. This does not interrupt
other ongoing operations. | [
"Switches",
"debug",
"mode",
"of",
"the",
"engine",
"on",
"or",
"off",
".",
"This",
"does",
"not",
"interrupt",
"other",
"ongoing",
"operations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L1024-L1032 |
238,676 | niklasf/python-chess | chess/engine.py | AnalysisResult.stop | def stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = None | python | def stop(self) -> None:
if self._stop and not self._posted_kork:
self._stop()
self._stop = None | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_stop",
"and",
"not",
"self",
".",
"_posted_kork",
":",
"self",
".",
"_stop",
"(",
")",
"self",
".",
"_stop",
"=",
"None"
] | Stops the analysis as soon as possible. | [
"Stops",
"the",
"analysis",
"as",
"soon",
"as",
"possible",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2090-L2094 |
238,677 | niklasf/python-chess | chess/engine.py | AnalysisResult.get | async def get(self) -> InfoDict:
"""
Waits for the next dictionary of information from the engine and
returns it.
It might be more convenient to use ``async for info in analysis: ...``.
:raises: :exc:`chess.engine.AnalysisComplete` if the analysis is
complete (or has been stopped) and all information has been
consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you
prefer to get ``None`` instead of an exception.
"""
if self._seen_kork:
raise AnalysisComplete()
info = await self._queue.get()
if not info:
# Empty dictionary marks end.
self._seen_kork = True
await self._finished
raise AnalysisComplete()
return info | python | async def get(self) -> InfoDict:
if self._seen_kork:
raise AnalysisComplete()
info = await self._queue.get()
if not info:
# Empty dictionary marks end.
self._seen_kork = True
await self._finished
raise AnalysisComplete()
return info | [
"async",
"def",
"get",
"(",
"self",
")",
"->",
"InfoDict",
":",
"if",
"self",
".",
"_seen_kork",
":",
"raise",
"AnalysisComplete",
"(",
")",
"info",
"=",
"await",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"if",
"not",
"info",
":",
"# Empty dictionar... | Waits for the next dictionary of information from the engine and
returns it.
It might be more convenient to use ``async for info in analysis: ...``.
:raises: :exc:`chess.engine.AnalysisComplete` if the analysis is
complete (or has been stopped) and all information has been
consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you
prefer to get ``None`` instead of an exception. | [
"Waits",
"for",
"the",
"next",
"dictionary",
"of",
"information",
"from",
"the",
"engine",
"and",
"returns",
"it",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2100-L2122 |
238,678 | niklasf/python-chess | chess/engine.py | AnalysisResult.empty | def empty(self) -> bool:
"""
Checks if all information has been consumed.
If the queue is empty, but the analysis is still ongoing, then further
information can become available in the future.
If the queue is not empty, then the next call to
:func:`~chess.engine.AnalysisResult.get()` will return instantly.
"""
return self._seen_kork or self._queue.qsize() <= self._posted_kork | python | def empty(self) -> bool:
return self._seen_kork or self._queue.qsize() <= self._posted_kork | [
"def",
"empty",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_seen_kork",
"or",
"self",
".",
"_queue",
".",
"qsize",
"(",
")",
"<=",
"self",
".",
"_posted_kork"
] | Checks if all information has been consumed.
If the queue is empty, but the analysis is still ongoing, then further
information can become available in the future.
If the queue is not empty, then the next call to
:func:`~chess.engine.AnalysisResult.get()` will return instantly. | [
"Checks",
"if",
"all",
"information",
"has",
"been",
"consumed",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2124-L2134 |
238,679 | niklasf/python-chess | chess/engine.py | SimpleEngine.close | def close(self) -> None:
"""
Closes the transport and the background event loop as soon as possible.
"""
def _shutdown() -> None:
self.transport.close()
self.shutdown_event.set()
with self._shutdown_lock:
if not self._shutdown:
self._shutdown = True
self.protocol.loop.call_soon_threadsafe(_shutdown) | python | def close(self) -> None:
def _shutdown() -> None:
self.transport.close()
self.shutdown_event.set()
with self._shutdown_lock:
if not self._shutdown:
self._shutdown = True
self.protocol.loop.call_soon_threadsafe(_shutdown) | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"def",
"_shutdown",
"(",
")",
"->",
"None",
":",
"self",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"shutdown_event",
".",
"set",
"(",
")",
"with",
"self",
".",
"_shutdown_lock",
":",
... | Closes the transport and the background event loop as soon as possible. | [
"Closes",
"the",
"transport",
"and",
"the",
"background",
"event",
"loop",
"as",
"soon",
"as",
"possible",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2314-L2325 |
238,680 | niklasf/python-chess | chess/gaviota.py | open_tablebase_native | def open_tablebase_native(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> NativeTablebase:
"""
Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used.
"""
libgtb = libgtb or ctypes.util.find_library("gtb") or "libgtb.so.1.0.1"
tables = NativeTablebase(LibraryLoader.LoadLibrary(libgtb))
tables.add_directory(directory)
return tables | python | def open_tablebase_native(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> NativeTablebase:
libgtb = libgtb or ctypes.util.find_library("gtb") or "libgtb.so.1.0.1"
tables = NativeTablebase(LibraryLoader.LoadLibrary(libgtb))
tables.add_directory(directory)
return tables | [
"def",
"open_tablebase_native",
"(",
"directory",
":",
"PathLike",
",",
"*",
",",
"libgtb",
":",
"Any",
"=",
"None",
",",
"LibraryLoader",
":",
"Any",
"=",
"ctypes",
".",
"cdll",
")",
"->",
"NativeTablebase",
":",
"libgtb",
"=",
"libgtb",
"or",
"ctypes",
... | Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used. | [
"Opens",
"a",
"collection",
"of",
"tables",
"for",
"probing",
"using",
"libgtb",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L2083-L2096 |
238,681 | niklasf/python-chess | chess/gaviota.py | open_tablebase | def open_tablebase(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]:
"""
Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code is tried.
"""
try:
if LibraryLoader:
return open_tablebase_native(directory, libgtb=libgtb, LibraryLoader=LibraryLoader)
except (OSError, RuntimeError) as err:
LOGGER.info("Falling back to pure Python tablebase: %r", err)
tables = PythonTablebase()
tables.add_directory(directory)
return tables | python | def open_tablebase(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]:
try:
if LibraryLoader:
return open_tablebase_native(directory, libgtb=libgtb, LibraryLoader=LibraryLoader)
except (OSError, RuntimeError) as err:
LOGGER.info("Falling back to pure Python tablebase: %r", err)
tables = PythonTablebase()
tables.add_directory(directory)
return tables | [
"def",
"open_tablebase",
"(",
"directory",
":",
"PathLike",
",",
"*",
",",
"libgtb",
":",
"Any",
"=",
"None",
",",
"LibraryLoader",
":",
"Any",
"=",
"ctypes",
".",
"cdll",
")",
"->",
"Union",
"[",
"NativeTablebase",
",",
"PythonTablebase",
"]",
":",
"try... | Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code is tried. | [
"Opens",
"a",
"collection",
"of",
"tables",
"for",
"probing",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L2099-L2118 |
238,682 | niklasf/python-chess | chess/gaviota.py | PythonTablebase.probe_dtm | def probe_dtm(self, board: chess.Board) -> int:
"""
Probes for depth to mate information.
The absolute value is the number of half-moves until forced mate
(or ``0`` in drawn positions). The value is positive if the
side to move is winning, otherwise it is negative.
In the example position white to move will get mated in 10 half-moves:
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1")
... print(tablebase.probe_dtm(board))
...
-10
:raises: :exc:`KeyError` (or specifically
:exc:`chess.gaviota.MissingTableError`) if the probe fails. Use
:func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer
to get ``None`` instead of an exception.
Note that probing a corrupted table file is undefined behavior.
"""
# Can not probe positions with castling rights.
if board.castling_rights:
raise KeyError("gaviota tables do not contain positions with castling rights: {}".format(board.fen()))
# Supports only up to 5 pieces.
if chess.popcount(board.occupied) > 5:
raise KeyError("gaviota tables support up to 5 pieces, not {}: {}".format(chess.popcount(board.occupied), board.fen()))
# KvK is a draw.
if board.occupied == board.kings:
return 0
# Prepare the tablebase request.
white_squares = list(chess.SquareSet(board.occupied_co[chess.WHITE]))
white_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in white_squares]
black_squares = list(chess.SquareSet(board.occupied_co[chess.BLACK]))
black_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in black_squares]
side = 0 if (board.turn == chess.WHITE) else 1
epsq = board.ep_square if board.ep_square else NOSQUARE
req = Request(white_squares, white_types, black_squares, black_types, side, epsq)
# Probe.
dtm = self.egtb_get_dtm(req)
ply, res = unpackdist(dtm)
if res == iWMATE:
# White mates in the stored position.
if req.realside == 1:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
elif res == iBMATE:
# Black mates in the stored position.
if req.realside == 0:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
else:
# Draw.
return 0 | python | def probe_dtm(self, board: chess.Board) -> int:
# Can not probe positions with castling rights.
if board.castling_rights:
raise KeyError("gaviota tables do not contain positions with castling rights: {}".format(board.fen()))
# Supports only up to 5 pieces.
if chess.popcount(board.occupied) > 5:
raise KeyError("gaviota tables support up to 5 pieces, not {}: {}".format(chess.popcount(board.occupied), board.fen()))
# KvK is a draw.
if board.occupied == board.kings:
return 0
# Prepare the tablebase request.
white_squares = list(chess.SquareSet(board.occupied_co[chess.WHITE]))
white_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in white_squares]
black_squares = list(chess.SquareSet(board.occupied_co[chess.BLACK]))
black_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in black_squares]
side = 0 if (board.turn == chess.WHITE) else 1
epsq = board.ep_square if board.ep_square else NOSQUARE
req = Request(white_squares, white_types, black_squares, black_types, side, epsq)
# Probe.
dtm = self.egtb_get_dtm(req)
ply, res = unpackdist(dtm)
if res == iWMATE:
# White mates in the stored position.
if req.realside == 1:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
elif res == iBMATE:
# Black mates in the stored position.
if req.realside == 0:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
else:
# Draw.
return 0 | [
"def",
"probe_dtm",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
")",
"->",
"int",
":",
"# Can not probe positions with castling rights.",
"if",
"board",
".",
"castling_rights",
":",
"raise",
"KeyError",
"(",
"\"gaviota tables do not contain positions with cas... | Probes for depth to mate information.
The absolute value is the number of half-moves until forced mate
(or ``0`` in drawn positions). The value is positive if the
side to move is winning, otherwise it is negative.
In the example position white to move will get mated in 10 half-moves:
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1")
... print(tablebase.probe_dtm(board))
...
-10
:raises: :exc:`KeyError` (or specifically
:exc:`chess.gaviota.MissingTableError`) if the probe fails. Use
:func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer
to get ``None`` instead of an exception.
Note that probing a corrupted table file is undefined behavior. | [
"Probes",
"for",
"depth",
"to",
"mate",
"information",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L1556-L1633 |
238,683 | niklasf/python-chess | chess/__init__.py | Piece.symbol | def symbol(self) -> str:
"""
Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces.
"""
symbol = piece_symbol(self.piece_type)
return symbol.upper() if self.color else symbol | python | def symbol(self) -> str:
symbol = piece_symbol(self.piece_type)
return symbol.upper() if self.color else symbol | [
"def",
"symbol",
"(",
"self",
")",
"->",
"str",
":",
"symbol",
"=",
"piece_symbol",
"(",
"self",
".",
"piece_type",
")",
"return",
"symbol",
".",
"upper",
"(",
")",
"if",
"self",
".",
"color",
"else",
"symbol"
] | Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces. | [
"Gets",
"the",
"symbol",
"P",
"N",
"B",
"R",
"Q",
"or",
"K",
"for",
"white",
"pieces",
"or",
"the",
"lower",
"-",
"case",
"variants",
"for",
"the",
"black",
"pieces",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L394-L400 |
238,684 | niklasf/python-chess | chess/__init__.py | Piece.unicode_symbol | def unicode_symbol(self, *, invert_color: bool = False) -> str:
"""
Gets the Unicode character for the piece.
"""
symbol = self.symbol().swapcase() if invert_color else self.symbol()
return UNICODE_PIECE_SYMBOLS[symbol] | python | def unicode_symbol(self, *, invert_color: bool = False) -> str:
symbol = self.symbol().swapcase() if invert_color else self.symbol()
return UNICODE_PIECE_SYMBOLS[symbol] | [
"def",
"unicode_symbol",
"(",
"self",
",",
"*",
",",
"invert_color",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"symbol",
"=",
"self",
".",
"symbol",
"(",
")",
".",
"swapcase",
"(",
")",
"if",
"invert_color",
"else",
"self",
".",
"symbol",
"("... | Gets the Unicode character for the piece. | [
"Gets",
"the",
"Unicode",
"character",
"for",
"the",
"piece",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L402-L407 |
238,685 | niklasf/python-chess | chess/__init__.py | Move.uci | def uci(self) -> str:
"""
Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``.
"""
if self.drop:
return piece_symbol(self.drop).upper() + "@" + SQUARE_NAMES[self.to_square]
elif self.promotion:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + piece_symbol(self.promotion)
elif self:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square]
else:
return "0000" | python | def uci(self) -> str:
if self.drop:
return piece_symbol(self.drop).upper() + "@" + SQUARE_NAMES[self.to_square]
elif self.promotion:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + piece_symbol(self.promotion)
elif self:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square]
else:
return "0000" | [
"def",
"uci",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"drop",
":",
"return",
"piece_symbol",
"(",
"self",
".",
"drop",
")",
".",
"upper",
"(",
")",
"+",
"\"@\"",
"+",
"SQUARE_NAMES",
"[",
"self",
".",
"to_square",
"]",
"elif",
"self"... | Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``. | [
"Gets",
"an",
"UCI",
"string",
"for",
"the",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L452-L468 |
238,686 | niklasf/python-chess | chess/__init__.py | Move.from_uci | def from_uci(cls, uci: str) -> "Move":
"""
Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid.
"""
if uci == "0000":
return cls.null()
elif len(uci) == 4 and "@" == uci[1]:
drop = PIECE_SYMBOLS.index(uci[0].lower())
square = SQUARE_NAMES.index(uci[2:])
return cls(square, square, drop=drop)
elif len(uci) == 4:
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]))
elif len(uci) == 5:
promotion = PIECE_SYMBOLS.index(uci[4])
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]), promotion=promotion)
else:
raise ValueError("expected uci string to be of length 4 or 5: {!r}".format(uci)) | python | def from_uci(cls, uci: str) -> "Move":
if uci == "0000":
return cls.null()
elif len(uci) == 4 and "@" == uci[1]:
drop = PIECE_SYMBOLS.index(uci[0].lower())
square = SQUARE_NAMES.index(uci[2:])
return cls(square, square, drop=drop)
elif len(uci) == 4:
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]))
elif len(uci) == 5:
promotion = PIECE_SYMBOLS.index(uci[4])
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]), promotion=promotion)
else:
raise ValueError("expected uci string to be of length 4 or 5: {!r}".format(uci)) | [
"def",
"from_uci",
"(",
"cls",
",",
"uci",
":",
"str",
")",
"->",
"\"Move\"",
":",
"if",
"uci",
"==",
"\"0000\"",
":",
"return",
"cls",
".",
"null",
"(",
")",
"elif",
"len",
"(",
"uci",
")",
"==",
"4",
"and",
"\"@\"",
"==",
"uci",
"[",
"1",
"]"... | Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid. | [
"Parses",
"an",
"UCI",
"string",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L504-L522 |
238,687 | niklasf/python-chess | chess/__init__.py | BaseBoard.pieces | def pieces(self, piece_type: PieceType, color: Color) -> "SquareSet":
"""
Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.pieces_mask(piece_type, color)) | python | def pieces(self, piece_type: PieceType, color: Color) -> "SquareSet":
return SquareSet(self.pieces_mask(piece_type, color)) | [
"def",
"pieces",
"(",
"self",
",",
"piece_type",
":",
"PieceType",
",",
"color",
":",
"Color",
")",
"->",
"\"SquareSet\"",
":",
"return",
"SquareSet",
"(",
"self",
".",
"pieces_mask",
"(",
"piece_type",
",",
"color",
")",
")"
] | Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`. | [
"Gets",
"pieces",
"of",
"the",
"given",
"type",
"and",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L614-L620 |
238,688 | niklasf/python-chess | chess/__init__.py | BaseBoard.piece_type_at | def piece_type_at(self, square: Square) -> Optional[PieceType]:
"""Gets the piece type at the given square."""
mask = BB_SQUARES[square]
if not self.occupied & mask:
return None # Early return
elif self.pawns & mask:
return PAWN
elif self.knights & mask:
return KNIGHT
elif self.bishops & mask:
return BISHOP
elif self.rooks & mask:
return ROOK
elif self.queens & mask:
return QUEEN
else:
return KING | python | def piece_type_at(self, square: Square) -> Optional[PieceType]:
mask = BB_SQUARES[square]
if not self.occupied & mask:
return None # Early return
elif self.pawns & mask:
return PAWN
elif self.knights & mask:
return KNIGHT
elif self.bishops & mask:
return BISHOP
elif self.rooks & mask:
return ROOK
elif self.queens & mask:
return QUEEN
else:
return KING | [
"def",
"piece_type_at",
"(",
"self",
",",
"square",
":",
"Square",
")",
"->",
"Optional",
"[",
"PieceType",
"]",
":",
"mask",
"=",
"BB_SQUARES",
"[",
"square",
"]",
"if",
"not",
"self",
".",
"occupied",
"&",
"mask",
":",
"return",
"None",
"# Early return... | Gets the piece type at the given square. | [
"Gets",
"the",
"piece",
"type",
"at",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L632-L649 |
238,689 | niklasf/python-chess | chess/__init__.py | BaseBoard.king | def king(self, color: Color) -> Optional[Square]:
"""
Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered.
"""
king_mask = self.occupied_co[color] & self.kings & ~self.promoted
return msb(king_mask) if king_mask else None | python | def king(self, color: Color) -> Optional[Square]:
king_mask = self.occupied_co[color] & self.kings & ~self.promoted
return msb(king_mask) if king_mask else None | [
"def",
"king",
"(",
"self",
",",
"color",
":",
"Color",
")",
"->",
"Optional",
"[",
"Square",
"]",
":",
"king_mask",
"=",
"self",
".",
"occupied_co",
"[",
"color",
"]",
"&",
"self",
".",
"kings",
"&",
"~",
"self",
".",
"promoted",
"return",
"msb",
... | Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered. | [
"Finds",
"the",
"king",
"square",
"of",
"the",
"given",
"side",
".",
"Returns",
"None",
"if",
"there",
"is",
"no",
"king",
"of",
"that",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L651-L660 |
238,690 | niklasf/python-chess | chess/__init__.py | BaseBoard.is_attacked_by | def is_attacked_by(self, color: Color, square: Square) -> bool:
"""
Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked.
"""
return bool(self.attackers_mask(color, square)) | python | def is_attacked_by(self, color: Color, square: Square) -> bool:
return bool(self.attackers_mask(color, square)) | [
"def",
"is_attacked_by",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"attackers_mask",
"(",
"color",
",",
"square",
")",
")"
] | Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked. | [
"Checks",
"if",
"the",
"given",
"side",
"attacks",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L713-L720 |
238,691 | niklasf/python-chess | chess/__init__.py | BaseBoard.attackers | def attackers(self, color: Color, square: Square) -> "SquareSet":
"""
Gets a set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.attackers_mask(color, square)) | python | def attackers(self, color: Color, square: Square) -> "SquareSet":
return SquareSet(self.attackers_mask(color, square)) | [
"def",
"attackers",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"\"SquareSet\"",
":",
"return",
"SquareSet",
"(",
"self",
".",
"attackers_mask",
"(",
"color",
",",
"square",
")",
")"
] | Gets a set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`. | [
"Gets",
"a",
"set",
"of",
"attackers",
"of",
"the",
"given",
"color",
"for",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L722-L730 |
238,692 | niklasf/python-chess | chess/__init__.py | BaseBoard.is_pinned | def is_pinned(self, color: Color, square: Square) -> bool:
"""
Detects if the given square is pinned to the king of the given color.
"""
return self.pin_mask(color, square) != BB_ALL | python | def is_pinned(self, color: Color, square: Square) -> bool:
return self.pin_mask(color, square) != BB_ALL | [
"def",
"is_pinned",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"bool",
":",
"return",
"self",
".",
"pin_mask",
"(",
"color",
",",
"square",
")",
"!=",
"BB_ALL"
] | Detects if the given square is pinned to the king of the given color. | [
"Detects",
"if",
"the",
"given",
"square",
"is",
"pinned",
"to",
"the",
"king",
"of",
"the",
"given",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L782-L786 |
238,693 | niklasf/python-chess | chess/__init__.py | BaseBoard.set_piece_at | def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None:
"""
Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`.
"""
if piece is None:
self._remove_piece_at(square)
else:
self._set_piece_at(square, piece.piece_type, piece.color, promoted) | python | def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None:
if piece is None:
self._remove_piece_at(square)
else:
self._set_piece_at(square, piece.piece_type, piece.color, promoted) | [
"def",
"set_piece_at",
"(",
"self",
",",
"square",
":",
"Square",
",",
"piece",
":",
"Optional",
"[",
"Piece",
"]",
",",
"promoted",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"piece",
"is",
"None",
":",
"self",
".",
"_remove_piece_at",
... | Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`. | [
"Sets",
"a",
"piece",
"at",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L850-L860 |
238,694 | niklasf/python-chess | chess/__init__.py | BaseBoard.board_fen | def board_fen(self, *, promoted: Optional[bool] = False) -> str:
"""
Gets the board FEN.
"""
builder = []
empty = 0
for square in SQUARES_180:
piece = self.piece_at(square)
if not piece:
empty += 1
else:
if empty:
builder.append(str(empty))
empty = 0
builder.append(piece.symbol())
if promoted and BB_SQUARES[square] & self.promoted:
builder.append("~")
if BB_SQUARES[square] & BB_FILE_H:
if empty:
builder.append(str(empty))
empty = 0
if square != H1:
builder.append("/")
return "".join(builder) | python | def board_fen(self, *, promoted: Optional[bool] = False) -> str:
builder = []
empty = 0
for square in SQUARES_180:
piece = self.piece_at(square)
if not piece:
empty += 1
else:
if empty:
builder.append(str(empty))
empty = 0
builder.append(piece.symbol())
if promoted and BB_SQUARES[square] & self.promoted:
builder.append("~")
if BB_SQUARES[square] & BB_FILE_H:
if empty:
builder.append(str(empty))
empty = 0
if square != H1:
builder.append("/")
return "".join(builder) | [
"def",
"board_fen",
"(",
"self",
",",
"*",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"False",
")",
"->",
"str",
":",
"builder",
"=",
"[",
"]",
"empty",
"=",
"0",
"for",
"square",
"in",
"SQUARES_180",
":",
"piece",
"=",
"self",
".",
... | Gets the board FEN. | [
"Gets",
"the",
"board",
"FEN",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L862-L890 |
238,695 | niklasf/python-chess | chess/__init__.py | BaseBoard.chess960_pos | def chess960_pos(self) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 959
or ``None``.
"""
if self.occupied_co[WHITE] != BB_RANK_1 | BB_RANK_2:
return None
if self.occupied_co[BLACK] != BB_RANK_7 | BB_RANK_8:
return None
if self.pawns != BB_RANK_2 | BB_RANK_7:
return None
if self.promoted:
return None
# Piece counts.
brnqk = [self.bishops, self.rooks, self.knights, self.queens, self.kings]
if [popcount(pieces) for pieces in brnqk] != [4, 4, 4, 2, 2]:
return None
# Symmetry.
if any((BB_RANK_1 & pieces) << 56 != BB_RANK_8 & pieces for pieces in brnqk):
return None
# Algorithm from ChessX, src/database/bitboard.cpp, r2254.
x = self.bishops & (2 + 8 + 32 + 128)
if not x:
return None
bs1 = (lsb(x) - 1) // 2
cc_pos = bs1
x = self.bishops & (1 + 4 + 16 + 64)
if not x:
return None
bs2 = lsb(x) * 2
cc_pos += bs2
q = 0
qf = False
n0 = 0
n1 = 0
n0f = False
n1f = False
rf = 0
n0s = [0, 4, 7, 9]
for square in range(A1, H1 + 1):
bb = BB_SQUARES[square]
if bb & self.queens:
qf = True
elif bb & self.rooks or bb & self.kings:
if bb & self.kings:
if rf != 1:
return None
else:
rf += 1
if not qf:
q += 1
if not n0f:
n0 += 1
elif not n1f:
n1 += 1
elif bb & self.knights:
if not qf:
q += 1
if not n0f:
n0f = True
elif not n1f:
n1f = True
if n0 < 4 and n1f and qf:
cc_pos += q * 16
krn = n0s[n0] + n1
cc_pos += krn * 96
return cc_pos
else:
return None | python | def chess960_pos(self) -> Optional[int]:
if self.occupied_co[WHITE] != BB_RANK_1 | BB_RANK_2:
return None
if self.occupied_co[BLACK] != BB_RANK_7 | BB_RANK_8:
return None
if self.pawns != BB_RANK_2 | BB_RANK_7:
return None
if self.promoted:
return None
# Piece counts.
brnqk = [self.bishops, self.rooks, self.knights, self.queens, self.kings]
if [popcount(pieces) for pieces in brnqk] != [4, 4, 4, 2, 2]:
return None
# Symmetry.
if any((BB_RANK_1 & pieces) << 56 != BB_RANK_8 & pieces for pieces in brnqk):
return None
# Algorithm from ChessX, src/database/bitboard.cpp, r2254.
x = self.bishops & (2 + 8 + 32 + 128)
if not x:
return None
bs1 = (lsb(x) - 1) // 2
cc_pos = bs1
x = self.bishops & (1 + 4 + 16 + 64)
if not x:
return None
bs2 = lsb(x) * 2
cc_pos += bs2
q = 0
qf = False
n0 = 0
n1 = 0
n0f = False
n1f = False
rf = 0
n0s = [0, 4, 7, 9]
for square in range(A1, H1 + 1):
bb = BB_SQUARES[square]
if bb & self.queens:
qf = True
elif bb & self.rooks or bb & self.kings:
if bb & self.kings:
if rf != 1:
return None
else:
rf += 1
if not qf:
q += 1
if not n0f:
n0 += 1
elif not n1f:
n1 += 1
elif bb & self.knights:
if not qf:
q += 1
if not n0f:
n0f = True
elif not n1f:
n1f = True
if n0 < 4 and n1f and qf:
cc_pos += q * 16
krn = n0s[n0] + n1
cc_pos += krn * 96
return cc_pos
else:
return None | [
"def",
"chess960_pos",
"(",
"self",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"self",
".",
"occupied_co",
"[",
"WHITE",
"]",
"!=",
"BB_RANK_1",
"|",
"BB_RANK_2",
":",
"return",
"None",
"if",
"self",
".",
"occupied_co",
"[",
"BLACK",
"]",
"!=",... | Gets the Chess960 starting position index between 0 and 959
or ``None``. | [
"Gets",
"the",
"Chess960",
"starting",
"position",
"index",
"between",
"0",
"and",
"959",
"or",
"None",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1043-L1119 |
238,696 | niklasf/python-chess | chess/__init__.py | BaseBoard.mirror | def mirror(self: BaseBoardT) -> BaseBoardT:
"""
Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color.
"""
board = self.transform(flip_vertical)
board.occupied_co[WHITE], board.occupied_co[BLACK] = board.occupied_co[BLACK], board.occupied_co[WHITE]
return board | python | def mirror(self: BaseBoardT) -> BaseBoardT:
board = self.transform(flip_vertical)
board.occupied_co[WHITE], board.occupied_co[BLACK] = board.occupied_co[BLACK], board.occupied_co[WHITE]
return board | [
"def",
"mirror",
"(",
"self",
":",
"BaseBoardT",
")",
"->",
"BaseBoardT",
":",
"board",
"=",
"self",
".",
"transform",
"(",
"flip_vertical",
")",
"board",
".",
"occupied_co",
"[",
"WHITE",
"]",
",",
"board",
".",
"occupied_co",
"[",
"BLACK",
"]",
"=",
... | Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color. | [
"Returns",
"a",
"mirrored",
"copy",
"of",
"the",
"board",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1226-L1235 |
238,697 | niklasf/python-chess | chess/__init__.py | BaseBoard.from_chess960_pos | def from_chess960_pos(cls: Type[BaseBoardT], sharnagl: int) -> BaseBoardT:
"""
Creates a new board, initialized with a Chess960 starting position.
>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959))
"""
board = cls.empty()
board.set_chess960_pos(sharnagl)
return board | python | def from_chess960_pos(cls: Type[BaseBoardT], sharnagl: int) -> BaseBoardT:
board = cls.empty()
board.set_chess960_pos(sharnagl)
return board | [
"def",
"from_chess960_pos",
"(",
"cls",
":",
"Type",
"[",
"BaseBoardT",
"]",
",",
"sharnagl",
":",
"int",
")",
"->",
"BaseBoardT",
":",
"board",
"=",
"cls",
".",
"empty",
"(",
")",
"board",
".",
"set_chess960_pos",
"(",
"sharnagl",
")",
"return",
"board"... | Creates a new board, initialized with a Chess960 starting position.
>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959)) | [
"Creates",
"a",
"new",
"board",
"initialized",
"with",
"a",
"Chess960",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1272-L1283 |
238,698 | niklasf/python-chess | chess/__init__.py | Board.reset | def reset(self) -> None:
"""Restores the starting position."""
self.turn = WHITE
self.castling_rights = BB_CORNERS
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.reset_board() | python | def reset(self) -> None:
self.turn = WHITE
self.castling_rights = BB_CORNERS
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.reset_board() | [
"def",
"reset",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"turn",
"=",
"WHITE",
"self",
".",
"castling_rights",
"=",
"BB_CORNERS",
"self",
".",
"ep_square",
"=",
"None",
"self",
".",
"halfmove_clock",
"=",
"0",
"self",
".",
"fullmove_number",
"="... | Restores the starting position. | [
"Restores",
"the",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1394-L1402 |
238,699 | niklasf/python-chess | chess/__init__.py | Board.clear | def clear(self) -> None:
"""
Clears the board.
Resets move stack and move counters. The side to move is white. There
are no rooks or kings, so castling rights are removed.
In order to be in a valid :func:`~chess.Board.status()` at least kings
need to be put on the board.
"""
self.turn = WHITE
self.castling_rights = BB_EMPTY
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.clear_board() | python | def clear(self) -> None:
self.turn = WHITE
self.castling_rights = BB_EMPTY
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.clear_board() | [
"def",
"clear",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"turn",
"=",
"WHITE",
"self",
".",
"castling_rights",
"=",
"BB_EMPTY",
"self",
".",
"ep_square",
"=",
"None",
"self",
".",
"halfmove_clock",
"=",
"0",
"self",
".",
"fullmove_number",
"=",
... | Clears the board.
Resets move stack and move counters. The side to move is white. There
are no rooks or kings, so castling rights are removed.
In order to be in a valid :func:`~chess.Board.status()` at least kings
need to be put on the board. | [
"Clears",
"the",
"board",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1408-L1424 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.