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,500
pytest-dev/pytest-xdist
xdist/workermanage.py
WorkerController.process_from_remote
def process_from_remote(self, eventcall): # noqa too complex """ this gets called for each object we receive from the other side and if the channel closes. Note that channel callbacks run in the receiver thread of execnet gateways - we need to avoid raising exceptions or doing heavy work. """ try: if eventcall == self.ENDMARK: err = self.channel._getremoteerror() if not self._down: if not err or isinstance(err, EOFError): err = "Not properly terminated" # lost connection? self.notify_inproc("errordown", node=self, error=err) self._down = True return eventname, kwargs = eventcall if eventname in ("collectionstart",): self.log("ignoring %s(%s)" % (eventname, kwargs)) elif eventname == "workerready": self.notify_inproc(eventname, node=self, **kwargs) elif eventname == "workerfinished": self._down = True self.workeroutput = self.slaveoutput = kwargs["workeroutput"] self.notify_inproc("workerfinished", node=self) elif eventname in ("logstart", "logfinish"): self.notify_inproc(eventname, node=self, **kwargs) elif eventname in ("testreport", "collectreport", "teardownreport"): item_index = kwargs.pop("item_index", None) rep = self.config.hook.pytest_report_from_serializable( config=self.config, data=kwargs["data"] ) if item_index is not None: rep.item_index = item_index self.notify_inproc(eventname, node=self, rep=rep) elif eventname == "collectionfinish": self.notify_inproc(eventname, node=self, ids=kwargs["ids"]) elif eventname == "runtest_protocol_complete": self.notify_inproc(eventname, node=self, **kwargs) elif eventname == "logwarning": self.notify_inproc( eventname, message=kwargs["message"], code=kwargs["code"], nodeid=kwargs["nodeid"], fslocation=kwargs["nodeid"], ) elif eventname == "warning_captured": warning_message = unserialize_warning_message( kwargs["warning_message_data"] ) self.notify_inproc( eventname, warning_message=warning_message, when=kwargs["when"], item=kwargs["item"], ) else: raise ValueError("unknown event: %s" % (eventname,)) except KeyboardInterrupt: # should not land in receiver-thread raise except: # noqa from _pytest._code import ExceptionInfo # ExceptionInfo API changed in pytest 4.1 if hasattr(ExceptionInfo, "from_current"): excinfo = ExceptionInfo.from_current() else: excinfo = ExceptionInfo() print("!" * 20, excinfo) self.config.notify_exception(excinfo) self.shutdown() self.notify_inproc("errordown", node=self, error=excinfo)
python
def process_from_remote(self, eventcall): # noqa too complex try: if eventcall == self.ENDMARK: err = self.channel._getremoteerror() if not self._down: if not err or isinstance(err, EOFError): err = "Not properly terminated" # lost connection? self.notify_inproc("errordown", node=self, error=err) self._down = True return eventname, kwargs = eventcall if eventname in ("collectionstart",): self.log("ignoring %s(%s)" % (eventname, kwargs)) elif eventname == "workerready": self.notify_inproc(eventname, node=self, **kwargs) elif eventname == "workerfinished": self._down = True self.workeroutput = self.slaveoutput = kwargs["workeroutput"] self.notify_inproc("workerfinished", node=self) elif eventname in ("logstart", "logfinish"): self.notify_inproc(eventname, node=self, **kwargs) elif eventname in ("testreport", "collectreport", "teardownreport"): item_index = kwargs.pop("item_index", None) rep = self.config.hook.pytest_report_from_serializable( config=self.config, data=kwargs["data"] ) if item_index is not None: rep.item_index = item_index self.notify_inproc(eventname, node=self, rep=rep) elif eventname == "collectionfinish": self.notify_inproc(eventname, node=self, ids=kwargs["ids"]) elif eventname == "runtest_protocol_complete": self.notify_inproc(eventname, node=self, **kwargs) elif eventname == "logwarning": self.notify_inproc( eventname, message=kwargs["message"], code=kwargs["code"], nodeid=kwargs["nodeid"], fslocation=kwargs["nodeid"], ) elif eventname == "warning_captured": warning_message = unserialize_warning_message( kwargs["warning_message_data"] ) self.notify_inproc( eventname, warning_message=warning_message, when=kwargs["when"], item=kwargs["item"], ) else: raise ValueError("unknown event: %s" % (eventname,)) except KeyboardInterrupt: # should not land in receiver-thread raise except: # noqa from _pytest._code import ExceptionInfo # ExceptionInfo API changed in pytest 4.1 if hasattr(ExceptionInfo, "from_current"): excinfo = ExceptionInfo.from_current() else: excinfo = ExceptionInfo() print("!" * 20, excinfo) self.config.notify_exception(excinfo) self.shutdown() self.notify_inproc("errordown", node=self, error=excinfo)
[ "def", "process_from_remote", "(", "self", ",", "eventcall", ")", ":", "# noqa too complex", "try", ":", "if", "eventcall", "==", "self", ".", "ENDMARK", ":", "err", "=", "self", ".", "channel", ".", "_getremoteerror", "(", ")", "if", "not", "self", ".", ...
this gets called for each object we receive from the other side and if the channel closes. Note that channel callbacks run in the receiver thread of execnet gateways - we need to avoid raising exceptions or doing heavy work.
[ "this", "gets", "called", "for", "each", "object", "we", "receive", "from", "the", "other", "side", "and", "if", "the", "channel", "closes", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L293-L367
238,501
pytest-dev/pytest-xdist
xdist/report.py
report_collection_diff
def report_collection_diff(from_collection, to_collection, from_id, to_id): """Report the collected test difference between two nodes. :returns: detailed message describing the difference between the given collections, or None if they are equal. """ if from_collection == to_collection: return None diff = unified_diff(from_collection, to_collection, fromfile=from_id, tofile=to_id) error_message = ( u"Different tests were collected between {from_id} and {to_id}. " u"The difference is:\n" u"{diff}" ).format(from_id=from_id, to_id=to_id, diff="\n".join(diff)) msg = "\n".join([x.rstrip() for x in error_message.split("\n")]) return msg
python
def report_collection_diff(from_collection, to_collection, from_id, to_id): if from_collection == to_collection: return None diff = unified_diff(from_collection, to_collection, fromfile=from_id, tofile=to_id) error_message = ( u"Different tests were collected between {from_id} and {to_id}. " u"The difference is:\n" u"{diff}" ).format(from_id=from_id, to_id=to_id, diff="\n".join(diff)) msg = "\n".join([x.rstrip() for x in error_message.split("\n")]) return msg
[ "def", "report_collection_diff", "(", "from_collection", ",", "to_collection", ",", "from_id", ",", "to_id", ")", ":", "if", "from_collection", "==", "to_collection", ":", "return", "None", "diff", "=", "unified_diff", "(", "from_collection", ",", "to_collection", ...
Report the collected test difference between two nodes. :returns: detailed message describing the difference between the given collections, or None if they are equal.
[ "Report", "the", "collected", "test", "difference", "between", "two", "nodes", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/report.py#L5-L21
238,502
ivelum/djangoql
djangoql/queryset.py
apply_search
def apply_search(queryset, search, schema=None): """ Applies search written in DjangoQL mini-language to given queryset """ ast = DjangoQLParser().parse(search) schema = schema or DjangoQLSchema schema_instance = schema(queryset.model) schema_instance.validate(ast) return queryset.filter(build_filter(ast, schema_instance))
python
def apply_search(queryset, search, schema=None): ast = DjangoQLParser().parse(search) schema = schema or DjangoQLSchema schema_instance = schema(queryset.model) schema_instance.validate(ast) return queryset.filter(build_filter(ast, schema_instance))
[ "def", "apply_search", "(", "queryset", ",", "search", ",", "schema", "=", "None", ")", ":", "ast", "=", "DjangoQLParser", "(", ")", ".", "parse", "(", "search", ")", "schema", "=", "schema", "or", "DjangoQLSchema", "schema_instance", "=", "schema", "(", ...
Applies search written in DjangoQL mini-language to given queryset
[ "Applies", "search", "written", "in", "DjangoQL", "mini", "-", "language", "to", "given", "queryset" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/queryset.py#L32-L40
238,503
ivelum/djangoql
djangoql/schema.py
DjangoQLField.get_options
def get_options(self): """ Override this method to provide custom suggestion options """ choices = self._field_choices() if choices: return [c[1] for c in choices] else: return self.model.objects.\ order_by(self.name).\ values_list(self.name, flat=True)
python
def get_options(self): choices = self._field_choices() if choices: return [c[1] for c in choices] else: return self.model.objects.\ order_by(self.name).\ values_list(self.name, flat=True)
[ "def", "get_options", "(", "self", ")", ":", "choices", "=", "self", ".", "_field_choices", "(", ")", "if", "choices", ":", "return", "[", "c", "[", "1", "]", "for", "c", "in", "choices", "]", "else", ":", "return", "self", ".", "model", ".", "obje...
Override this method to provide custom suggestion options
[ "Override", "this", "method", "to", "provide", "custom", "suggestion", "options" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L55-L65
238,504
ivelum/djangoql
djangoql/schema.py
DjangoQLField.get_lookup_value
def get_lookup_value(self, value): """ Override this method to convert displayed values to lookup values """ choices = self._field_choices() if choices: if isinstance(value, list): return [c[0] for c in choices if c[1] in value] else: for c in choices: if c[1] == value: return c[0] return value
python
def get_lookup_value(self, value): choices = self._field_choices() if choices: if isinstance(value, list): return [c[0] for c in choices if c[1] in value] else: for c in choices: if c[1] == value: return c[0] return value
[ "def", "get_lookup_value", "(", "self", ",", "value", ")", ":", "choices", "=", "self", ".", "_field_choices", "(", ")", "if", "choices", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "[", "c", "[", "0", "]", "for", "c", "...
Override this method to convert displayed values to lookup values
[ "Override", "this", "method", "to", "convert", "displayed", "values", "to", "lookup", "values" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L73-L85
238,505
ivelum/djangoql
djangoql/schema.py
DjangoQLField.get_operator
def get_operator(self, operator): """ Get a comparison suffix to be used in Django ORM & inversion flag for it :param operator: string, DjangoQL comparison operator :return: (suffix, invert) - a tuple with 2 values: suffix - suffix to be used in ORM query, for example '__gt' for '>' invert - boolean, True if this comparison needs to be inverted """ op = { '=': '', '>': '__gt', '>=': '__gte', '<': '__lt', '<=': '__lte', '~': '__icontains', 'in': '__in', }.get(operator) if op is not None: return op, False op = { '!=': '', '!~': '__icontains', 'not in': '__in', }[operator] return op, True
python
def get_operator(self, operator): op = { '=': '', '>': '__gt', '>=': '__gte', '<': '__lt', '<=': '__lte', '~': '__icontains', 'in': '__in', }.get(operator) if op is not None: return op, False op = { '!=': '', '!~': '__icontains', 'not in': '__in', }[operator] return op, True
[ "def", "get_operator", "(", "self", ",", "operator", ")", ":", "op", "=", "{", "'='", ":", "''", ",", "'>'", ":", "'__gt'", ",", "'>='", ":", "'__gte'", ",", "'<'", ":", "'__lt'", ",", "'<='", ":", "'__lte'", ",", "'~'", ":", "'__icontains'", ",", ...
Get a comparison suffix to be used in Django ORM & inversion flag for it :param operator: string, DjangoQL comparison operator :return: (suffix, invert) - a tuple with 2 values: suffix - suffix to be used in ORM query, for example '__gt' for '>' invert - boolean, True if this comparison needs to be inverted
[ "Get", "a", "comparison", "suffix", "to", "be", "used", "in", "Django", "ORM", "&", "inversion", "flag", "for", "it" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L87-L112
238,506
ivelum/djangoql
djangoql/schema.py
DjangoQLSchema.introspect
def introspect(self, model, exclude=()): """ Start with given model and recursively walk through its relationships. Returns a dict with all model labels and their fields found. """ result = {} open_set = deque([model]) closed_set = list(exclude) while open_set: model = open_set.popleft() model_label = self.model_label(model) if model_label in closed_set: continue model_fields = OrderedDict() for field in self.get_fields(model): if not isinstance(field, DjangoQLField): field = self.get_field_instance(model, field) if not field: continue if isinstance(field, RelationField): if field.relation not in closed_set: model_fields[field.name] = field open_set.append(field.related_model) else: model_fields[field.name] = field result[model_label] = model_fields closed_set.append(model_label) return result
python
def introspect(self, model, exclude=()): result = {} open_set = deque([model]) closed_set = list(exclude) while open_set: model = open_set.popleft() model_label = self.model_label(model) if model_label in closed_set: continue model_fields = OrderedDict() for field in self.get_fields(model): if not isinstance(field, DjangoQLField): field = self.get_field_instance(model, field) if not field: continue if isinstance(field, RelationField): if field.relation not in closed_set: model_fields[field.name] = field open_set.append(field.related_model) else: model_fields[field.name] = field result[model_label] = model_fields closed_set.append(model_label) return result
[ "def", "introspect", "(", "self", ",", "model", ",", "exclude", "=", "(", ")", ")", ":", "result", "=", "{", "}", "open_set", "=", "deque", "(", "[", "model", "]", ")", "closed_set", "=", "list", "(", "exclude", ")", "while", "open_set", ":", "mode...
Start with given model and recursively walk through its relationships. Returns a dict with all model labels and their fields found.
[ "Start", "with", "given", "model", "and", "recursively", "walk", "through", "its", "relationships", "." ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L332-L365
238,507
ivelum/djangoql
djangoql/schema.py
DjangoQLSchema.get_fields
def get_fields(self, model): """ By default, returns all field names of a given model. Override this method to limit field options. You can either return a plain list of field names from it, like ['id', 'name'], or call .super() and exclude unwanted fields from its result. """ return sorted( [f.name for f in model._meta.get_fields() if f.name != 'password'] )
python
def get_fields(self, model): return sorted( [f.name for f in model._meta.get_fields() if f.name != 'password'] )
[ "def", "get_fields", "(", "self", ",", "model", ")", ":", "return", "sorted", "(", "[", "f", ".", "name", "for", "f", "in", "model", ".", "_meta", ".", "get_fields", "(", ")", "if", "f", ".", "name", "!=", "'password'", "]", ")" ]
By default, returns all field names of a given model. Override this method to limit field options. You can either return a plain list of field names from it, like ['id', 'name'], or call .super() and exclude unwanted fields from its result.
[ "By", "default", "returns", "all", "field", "names", "of", "a", "given", "model", "." ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L367-L377
238,508
ivelum/djangoql
djangoql/schema.py
DjangoQLSchema.validate
def validate(self, node): """ Validate DjangoQL AST tree vs. current schema """ assert isinstance(node, Node) if isinstance(node.operator, Logical): self.validate(node.left) self.validate(node.right) return assert isinstance(node.left, Name) assert isinstance(node.operator, Comparison) assert isinstance(node.right, (Const, List)) # Check that field and value types are compatible field = self.resolve_name(node.left) value = node.right.value if field is None: if value is not None: raise DjangoQLSchemaError( 'Related model %s can be compared to None only, but not to ' '%s' % (node.left.value, type(value).__name__) ) else: values = value if isinstance(node.right, List) else [value] for v in values: field.validate(v)
python
def validate(self, node): assert isinstance(node, Node) if isinstance(node.operator, Logical): self.validate(node.left) self.validate(node.right) return assert isinstance(node.left, Name) assert isinstance(node.operator, Comparison) assert isinstance(node.right, (Const, List)) # Check that field and value types are compatible field = self.resolve_name(node.left) value = node.right.value if field is None: if value is not None: raise DjangoQLSchemaError( 'Related model %s can be compared to None only, but not to ' '%s' % (node.left.value, type(value).__name__) ) else: values = value if isinstance(node.right, List) else [value] for v in values: field.validate(v)
[ "def", "validate", "(", "self", ",", "node", ")", ":", "assert", "isinstance", "(", "node", ",", "Node", ")", "if", "isinstance", "(", "node", ".", "operator", ",", "Logical", ")", ":", "self", ".", "validate", "(", "node", ".", "left", ")", "self", ...
Validate DjangoQL AST tree vs. current schema
[ "Validate", "DjangoQL", "AST", "tree", "vs", ".", "current", "schema" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L454-L479
238,509
ivelum/djangoql
djangoql/lexer.py
DjangoQLLexer.find_column
def find_column(self, t): """ Returns token position in current text, starting from 1 """ cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators) if cr == -1: return t.lexpos + 1 return t.lexpos - cr
python
def find_column(self, t): cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators) if cr == -1: return t.lexpos + 1 return t.lexpos - cr
[ "def", "find_column", "(", "self", ",", "t", ")", ":", "cr", "=", "max", "(", "self", ".", "text", ".", "rfind", "(", "l", ",", "0", ",", "t", ".", "lexpos", ")", "for", "l", "in", "self", ".", "line_terminators", ")", "if", "cr", "==", "-", ...
Returns token position in current text, starting from 1
[ "Returns", "token", "position", "in", "current", "text", "starting", "from", "1" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/lexer.py#L40-L47
238,510
aiogram/aiogram
aiogram/dispatcher/filters/filters.py
execute_filter
async def execute_filter(filter_: FilterObj, args): """ Helper for executing filter :param filter_: :param args: :return: """ if filter_.is_async: return await filter_.filter(*args, **filter_.kwargs) else: return filter_.filter(*args, **filter_.kwargs)
python
async def execute_filter(filter_: FilterObj, args): if filter_.is_async: return await filter_.filter(*args, **filter_.kwargs) else: return filter_.filter(*args, **filter_.kwargs)
[ "async", "def", "execute_filter", "(", "filter_", ":", "FilterObj", ",", "args", ")", ":", "if", "filter_", ".", "is_async", ":", "return", "await", "filter_", ".", "filter", "(", "*", "args", ",", "*", "*", "filter_", ".", "kwargs", ")", "else", ":", ...
Helper for executing filter :param filter_: :param args: :return:
[ "Helper", "for", "executing", "filter" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L47-L58
238,511
aiogram/aiogram
aiogram/dispatcher/filters/filters.py
check_filters
async def check_filters(filters: typing.Iterable[FilterObj], args): """ Check list of filters :param filters: :param args: :return: """ data = {} if filters is not None: for filter_ in filters: f = await execute_filter(filter_, args) if not f: raise FilterNotPassed() elif isinstance(f, dict): data.update(f) return data
python
async def check_filters(filters: typing.Iterable[FilterObj], args): data = {} if filters is not None: for filter_ in filters: f = await execute_filter(filter_, args) if not f: raise FilterNotPassed() elif isinstance(f, dict): data.update(f) return data
[ "async", "def", "check_filters", "(", "filters", ":", "typing", ".", "Iterable", "[", "FilterObj", "]", ",", "args", ")", ":", "data", "=", "{", "}", "if", "filters", "is", "not", "None", ":", "for", "filter_", "in", "filters", ":", "f", "=", "await"...
Check list of filters :param filters: :param args: :return:
[ "Check", "list", "of", "filters" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L61-L77
238,512
aiogram/aiogram
aiogram/dispatcher/filters/filters.py
AbstractFilter.validate
def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]: """ Validate and parse config. This method will be called by the filters factory when you bind this filter. Must be overridden. :param full_config: dict with arguments passed to handler registrar :return: Current filter config """ pass
python
def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]: pass
[ "def", "validate", "(", "cls", ",", "full_config", ":", "typing", ".", "Dict", "[", "str", ",", "typing", ".", "Any", "]", ")", "->", "typing", ".", "Optional", "[", "typing", ".", "Dict", "[", "str", ",", "typing", ".", "Any", "]", "]", ":", "pa...
Validate and parse config. This method will be called by the filters factory when you bind this filter. Must be overridden. :param full_config: dict with arguments passed to handler registrar :return: Current filter config
[ "Validate", "and", "parse", "config", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L136-L146
238,513
aiogram/aiogram
aiogram/dispatcher/filters/filters.py
AndFilter.check
async def check(self, *args): """ All filters must return a positive result :param args: :return: """ data = {} for target in self.targets: result = await target(*args) if not result: return False if isinstance(result, dict): data.update(result) if not data: return True return data
python
async def check(self, *args): data = {} for target in self.targets: result = await target(*args) if not result: return False if isinstance(result, dict): data.update(result) if not data: return True return data
[ "async", "def", "check", "(", "self", ",", "*", "args", ")", ":", "data", "=", "{", "}", "for", "target", "in", "self", ".", "targets", ":", "result", "=", "await", "target", "(", "*", "args", ")", "if", "not", "result", ":", "return", "False", "...
All filters must return a positive result :param args: :return:
[ "All", "filters", "must", "return", "a", "positive", "result" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L247-L263
238,514
aiogram/aiogram
examples/broadcast_example.py
send_message
async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool: """ Safe messages sender :param user_id: :param text: :param disable_notification: :return: """ try: await bot.send_message(user_id, text, disable_notification=disable_notification) except exceptions.BotBlocked: log.error(f"Target [ID:{user_id}]: blocked by user") except exceptions.ChatNotFound: log.error(f"Target [ID:{user_id}]: invalid user ID") except exceptions.RetryAfter as e: log.error(f"Target [ID:{user_id}]: Flood limit is exceeded. Sleep {e.timeout} seconds.") await asyncio.sleep(e.timeout) return await send_message(user_id, text) # Recursive call except exceptions.UserDeactivated: log.error(f"Target [ID:{user_id}]: user is deactivated") except exceptions.TelegramAPIError: log.exception(f"Target [ID:{user_id}]: failed") else: log.info(f"Target [ID:{user_id}]: success") return True return False
python
async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool: try: await bot.send_message(user_id, text, disable_notification=disable_notification) except exceptions.BotBlocked: log.error(f"Target [ID:{user_id}]: blocked by user") except exceptions.ChatNotFound: log.error(f"Target [ID:{user_id}]: invalid user ID") except exceptions.RetryAfter as e: log.error(f"Target [ID:{user_id}]: Flood limit is exceeded. Sleep {e.timeout} seconds.") await asyncio.sleep(e.timeout) return await send_message(user_id, text) # Recursive call except exceptions.UserDeactivated: log.error(f"Target [ID:{user_id}]: user is deactivated") except exceptions.TelegramAPIError: log.exception(f"Target [ID:{user_id}]: failed") else: log.info(f"Target [ID:{user_id}]: success") return True return False
[ "async", "def", "send_message", "(", "user_id", ":", "int", ",", "text", ":", "str", ",", "disable_notification", ":", "bool", "=", "False", ")", "->", "bool", ":", "try", ":", "await", "bot", ".", "send_message", "(", "user_id", ",", "text", ",", "dis...
Safe messages sender :param user_id: :param text: :param disable_notification: :return:
[ "Safe", "messages", "sender" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/broadcast_example.py#L26-L52
238,515
aiogram/aiogram
aiogram/types/message.py
Message.get_full_command
def get_full_command(self): """ Split command and args :return: tuple of (command, args) """ if self.is_command(): command, _, args = self.text.partition(' ') return command, args
python
def get_full_command(self): if self.is_command(): command, _, args = self.text.partition(' ') return command, args
[ "def", "get_full_command", "(", "self", ")", ":", "if", "self", ".", "is_command", "(", ")", ":", "command", ",", "_", ",", "args", "=", "self", ".", "text", ".", "partition", "(", "' '", ")", "return", "command", ",", "args" ]
Split command and args :return: tuple of (command, args)
[ "Split", "command", "and", "args" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L156-L164
238,516
aiogram/aiogram
aiogram/types/message.py
Message.get_command
def get_command(self, pure=False): """ Get command from message :return: """ command = self.get_full_command() if command: command = command[0] if pure: command, _, _ = command[1:].partition('@') return command
python
def get_command(self, pure=False): command = self.get_full_command() if command: command = command[0] if pure: command, _, _ = command[1:].partition('@') return command
[ "def", "get_command", "(", "self", ",", "pure", "=", "False", ")", ":", "command", "=", "self", ".", "get_full_command", "(", ")", "if", "command", ":", "command", "=", "command", "[", "0", "]", "if", "pure", ":", "command", ",", "_", ",", "_", "="...
Get command from message :return:
[ "Get", "command", "from", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L166-L177
238,517
aiogram/aiogram
aiogram/types/message.py
Message.parse_entities
def parse_entities(self, as_html=True): """ Text or caption formatted as HTML or Markdown. :return: str """ text = self.text or self.caption if text is None: raise TypeError("This message doesn't have any text.") quote_fn = md.quote_html if as_html else md.escape_md entities = self.entities or self.caption_entities if not entities: return quote_fn(text) if not sys.maxunicode == 0xffff: text = text.encode('utf-16-le') result = '' offset = 0 for entity in sorted(entities, key=lambda item: item.offset): entity_text = entity.parse(text, as_html=as_html) if sys.maxunicode == 0xffff: part = text[offset:entity.offset] result += quote_fn(part) + entity_text else: part = text[offset * 2:entity.offset * 2] result += quote_fn(part.decode('utf-16-le')) + entity_text offset = entity.offset + entity.length if sys.maxunicode == 0xffff: part = text[offset:] result += quote_fn(part) else: part = text[offset * 2:] result += quote_fn(part.decode('utf-16-le')) return result
python
def parse_entities(self, as_html=True): text = self.text or self.caption if text is None: raise TypeError("This message doesn't have any text.") quote_fn = md.quote_html if as_html else md.escape_md entities = self.entities or self.caption_entities if not entities: return quote_fn(text) if not sys.maxunicode == 0xffff: text = text.encode('utf-16-le') result = '' offset = 0 for entity in sorted(entities, key=lambda item: item.offset): entity_text = entity.parse(text, as_html=as_html) if sys.maxunicode == 0xffff: part = text[offset:entity.offset] result += quote_fn(part) + entity_text else: part = text[offset * 2:entity.offset * 2] result += quote_fn(part.decode('utf-16-le')) + entity_text offset = entity.offset + entity.length if sys.maxunicode == 0xffff: part = text[offset:] result += quote_fn(part) else: part = text[offset * 2:] result += quote_fn(part.decode('utf-16-le')) return result
[ "def", "parse_entities", "(", "self", ",", "as_html", "=", "True", ")", ":", "text", "=", "self", ".", "text", "or", "self", ".", "caption", "if", "text", "is", "None", ":", "raise", "TypeError", "(", "\"This message doesn't have any text.\"", ")", "quote_fn...
Text or caption formatted as HTML or Markdown. :return: str
[ "Text", "or", "caption", "formatted", "as", "HTML", "or", "Markdown", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L189-L231
238,518
aiogram/aiogram
aiogram/types/message.py
Message.url
def url(self) -> str: """ Get URL for the message :return: str """ if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]: raise TypeError('Invalid chat type!') elif not self.chat.username: raise TypeError('This chat does not have @username') return f"https://t.me/{self.chat.username}/{self.message_id}"
python
def url(self) -> str: if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]: raise TypeError('Invalid chat type!') elif not self.chat.username: raise TypeError('This chat does not have @username') return f"https://t.me/{self.chat.username}/{self.message_id}"
[ "def", "url", "(", "self", ")", "->", "str", ":", "if", "self", ".", "chat", ".", "type", "not", "in", "[", "ChatType", ".", "SUPER_GROUP", ",", "ChatType", ".", "CHANNEL", "]", ":", "raise", "TypeError", "(", "'Invalid chat type!'", ")", "elif", "not"...
Get URL for the message :return: str
[ "Get", "URL", "for", "the", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L252-L263
238,519
aiogram/aiogram
aiogram/types/message.py
Message.link
def link(self, text, as_html=True) -> str: """ Generate URL for using in text messages with HTML or MD parse mode :param text: link label :param as_html: generate as HTML :return: str """ try: url = self.url except TypeError: # URL is not accessible if as_html: return md.quote_html(text) return md.escape_md(text) if as_html: return md.hlink(text, url) return md.link(text, url)
python
def link(self, text, as_html=True) -> str: try: url = self.url except TypeError: # URL is not accessible if as_html: return md.quote_html(text) return md.escape_md(text) if as_html: return md.hlink(text, url) return md.link(text, url)
[ "def", "link", "(", "self", ",", "text", ",", "as_html", "=", "True", ")", "->", "str", ":", "try", ":", "url", "=", "self", ".", "url", "except", "TypeError", ":", "# URL is not accessible", "if", "as_html", ":", "return", "md", ".", "quote_html", "("...
Generate URL for using in text messages with HTML or MD parse mode :param text: link label :param as_html: generate as HTML :return: str
[ "Generate", "URL", "for", "using", "in", "text", "messages", "with", "HTML", "or", "MD", "parse", "mode" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L265-L282
238,520
aiogram/aiogram
aiogram/types/message.py
Message.answer
async def answer(self, text, parse_mode=None, disable_web_page_preview=None, disable_notification=None, reply_markup=None, reply=False) -> Message: """ Answer to this message :param text: str :param parse_mode: str :param disable_web_page_preview: bool :param disable_notification: bool :param reply_markup: :param reply: fill 'reply_to_message_id' :return: :class:`aiogram.types.Message` """ return await self.bot.send_message(chat_id=self.chat.id, text=text, parse_mode=parse_mode, disable_web_page_preview=disable_web_page_preview, disable_notification=disable_notification, reply_to_message_id=self.message_id if reply else None, reply_markup=reply_markup)
python
async def answer(self, text, parse_mode=None, disable_web_page_preview=None, disable_notification=None, reply_markup=None, reply=False) -> Message: return await self.bot.send_message(chat_id=self.chat.id, text=text, parse_mode=parse_mode, disable_web_page_preview=disable_web_page_preview, disable_notification=disable_notification, reply_to_message_id=self.message_id if reply else None, reply_markup=reply_markup)
[ "async", "def", "answer", "(", "self", ",", "text", ",", "parse_mode", "=", "None", ",", "disable_web_page_preview", "=", "None", ",", "disable_notification", "=", "None", ",", "reply_markup", "=", "None", ",", "reply", "=", "False", ")", "->", "Message", ...
Answer to this message :param text: str :param parse_mode: str :param disable_web_page_preview: bool :param disable_notification: bool :param reply_markup: :param reply: fill 'reply_to_message_id' :return: :class:`aiogram.types.Message`
[ "Answer", "to", "this", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L284-L302
238,521
aiogram/aiogram
aiogram/types/message.py
Message.answer_photo
async def answer_photo(self, photo: typing.Union[base.InputFile, base.String], caption: typing.Union[base.String, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, reply_markup=None, reply=False) -> Message: """ Use this method to send photos. Source: https://core.telegram.org/bots/api#sendphoto :param photo: Photo to send. :type photo: :obj:`typing.Union[base.InputFile, base.String]` :param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters :type caption: :obj:`typing.Union[base.String, None]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: :obj:`typing.Union[base.Boolean, None]` :param reply_markup: Additional interface options. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]` :param reply: fill 'reply_to_message_id' :return: On success, the sent Message is returned. :rtype: :obj:`types.Message` """ return await self.bot.send_photo(chat_id=self.chat.id, photo=photo, caption=caption, disable_notification=disable_notification, reply_to_message_id=self.message_id if reply else None, reply_markup=reply_markup)
python
async def answer_photo(self, photo: typing.Union[base.InputFile, base.String], caption: typing.Union[base.String, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, reply_markup=None, reply=False) -> Message: return await self.bot.send_photo(chat_id=self.chat.id, photo=photo, caption=caption, disable_notification=disable_notification, reply_to_message_id=self.message_id if reply else None, reply_markup=reply_markup)
[ "async", "def", "answer_photo", "(", "self", ",", "photo", ":", "typing", ".", "Union", "[", "base", ".", "InputFile", ",", "base", ".", "String", "]", ",", "caption", ":", "typing", ".", "Union", "[", "base", ".", "String", ",", "None", "]", "=", ...
Use this method to send photos. Source: https://core.telegram.org/bots/api#sendphoto :param photo: Photo to send. :type photo: :obj:`typing.Union[base.InputFile, base.String]` :param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters :type caption: :obj:`typing.Union[base.String, None]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: :obj:`typing.Union[base.Boolean, None]` :param reply_markup: Additional interface options. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]` :param reply: fill 'reply_to_message_id' :return: On success, the sent Message is returned. :rtype: :obj:`types.Message`
[ "Use", "this", "method", "to", "send", "photos", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L304-L329
238,522
aiogram/aiogram
aiogram/types/message.py
Message.forward
async def forward(self, chat_id, disable_notification=None) -> Message: """ Forward this message :param chat_id: :param disable_notification: :return: """ return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification)
python
async def forward(self, chat_id, disable_notification=None) -> Message: return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification)
[ "async", "def", "forward", "(", "self", ",", "chat_id", ",", "disable_notification", "=", "None", ")", "->", "Message", ":", "return", "await", "self", ".", "bot", ".", "forward_message", "(", "chat_id", ",", "self", ".", "chat", ".", "id", ",", "self", ...
Forward this message :param chat_id: :param disable_notification: :return:
[ "Forward", "this", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L1322-L1330
238,523
aiogram/aiogram
aiogram/types/message.py
Message.delete
async def delete(self): """ Delete this message :return: bool """ return await self.bot.delete_message(self.chat.id, self.message_id)
python
async def delete(self): return await self.bot.delete_message(self.chat.id, self.message_id)
[ "async", "def", "delete", "(", "self", ")", ":", "return", "await", "self", ".", "bot", ".", "delete_message", "(", "self", ".", "chat", ".", "id", ",", "self", ".", "message_id", ")" ]
Delete this message :return: bool
[ "Delete", "this", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L1470-L1476
238,524
aiogram/aiogram
aiogram/utils/callback_data.py
CallbackData.new
def new(self, *args, **kwargs) -> str: """ Generate callback data :param args: :param kwargs: :return: """ args = list(args) data = [self.prefix] for part in self._part_names: value = kwargs.pop(part, None) if value is None: if args: value = args.pop(0) else: raise ValueError(f"Value for '{part}' is not passed!") if value is not None and not isinstance(value, str): value = str(value) if not value: raise ValueError(f"Value for part {part} can't be empty!'") elif self.sep in value: raise ValueError(f"Symbol defined as separator can't be used in values of parts") data.append(value) if args or kwargs: raise TypeError('Too many arguments is passed!') callback_data = self.sep.join(data) if len(callback_data) > 64: raise ValueError('Resulted callback data is too long!') return callback_data
python
def new(self, *args, **kwargs) -> str: args = list(args) data = [self.prefix] for part in self._part_names: value = kwargs.pop(part, None) if value is None: if args: value = args.pop(0) else: raise ValueError(f"Value for '{part}' is not passed!") if value is not None and not isinstance(value, str): value = str(value) if not value: raise ValueError(f"Value for part {part} can't be empty!'") elif self.sep in value: raise ValueError(f"Symbol defined as separator can't be used in values of parts") data.append(value) if args or kwargs: raise TypeError('Too many arguments is passed!') callback_data = self.sep.join(data) if len(callback_data) > 64: raise ValueError('Resulted callback data is too long!') return callback_data
[ "def", "new", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "str", ":", "args", "=", "list", "(", "args", ")", "data", "=", "[", "self", ".", "prefix", "]", "for", "part", "in", "self", ".", "_part_names", ":", "value", "="...
Generate callback data :param args: :param kwargs: :return:
[ "Generate", "callback", "data" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/callback_data.py#L44-L81
238,525
aiogram/aiogram
examples/webhook_example.py
cmd_id
async def cmd_id(message: types.Message): """ Return info about user. """ if message.reply_to_message: target = message.reply_to_message.from_user chat = message.chat elif message.forward_from and message.chat.type == ChatType.PRIVATE: target = message.forward_from chat = message.forward_from or message.chat else: target = message.from_user chat = message.chat result_msg = [hbold('Info about user:'), f"First name: {target.first_name}"] if target.last_name: result_msg.append(f"Last name: {target.last_name}") if target.username: result_msg.append(f"Username: {target.mention}") result_msg.append(f"User ID: {target.id}") result_msg.extend([hbold('Chat:'), f"Type: {chat.type}", f"Chat ID: {chat.id}"]) if chat.type != ChatType.PRIVATE: result_msg.append(f"Title: {chat.title}") else: result_msg.append(f"Title: {chat.full_name}") return SendMessage(message.chat.id, '\n'.join(result_msg), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML)
python
async def cmd_id(message: types.Message): if message.reply_to_message: target = message.reply_to_message.from_user chat = message.chat elif message.forward_from and message.chat.type == ChatType.PRIVATE: target = message.forward_from chat = message.forward_from or message.chat else: target = message.from_user chat = message.chat result_msg = [hbold('Info about user:'), f"First name: {target.first_name}"] if target.last_name: result_msg.append(f"Last name: {target.last_name}") if target.username: result_msg.append(f"Username: {target.mention}") result_msg.append(f"User ID: {target.id}") result_msg.extend([hbold('Chat:'), f"Type: {chat.type}", f"Chat ID: {chat.id}"]) if chat.type != ChatType.PRIVATE: result_msg.append(f"Title: {chat.title}") else: result_msg.append(f"Title: {chat.full_name}") return SendMessage(message.chat.id, '\n'.join(result_msg), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML)
[ "async", "def", "cmd_id", "(", "message", ":", "types", ".", "Message", ")", ":", "if", "message", ".", "reply_to_message", ":", "target", "=", "message", ".", "reply_to_message", ".", "from_user", "chat", "=", "message", ".", "chat", "elif", "message", "....
Return info about user.
[ "Return", "info", "about", "user", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/webhook_example.py#L83-L113
238,526
aiogram/aiogram
examples/webhook_example.py
on_shutdown
async def on_shutdown(app): """ Graceful shutdown. This method is recommended by aiohttp docs. """ # Remove webhook. await bot.delete_webhook() # Close Redis connection. await dp.storage.close() await dp.storage.wait_closed()
python
async def on_shutdown(app): # Remove webhook. await bot.delete_webhook() # Close Redis connection. await dp.storage.close() await dp.storage.wait_closed()
[ "async", "def", "on_shutdown", "(", "app", ")", ":", "# Remove webhook.", "await", "bot", ".", "delete_webhook", "(", ")", "# Close Redis connection.", "await", "dp", ".", "storage", ".", "close", "(", ")", "await", "dp", ".", "storage", ".", "wait_closed", ...
Graceful shutdown. This method is recommended by aiohttp docs.
[ "Graceful", "shutdown", ".", "This", "method", "is", "recommended", "by", "aiohttp", "docs", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/webhook_example.py#L149-L158
238,527
aiogram/aiogram
aiogram/types/input_file.py
InputFile.from_url
def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE): """ Download file from URL Manually is not required action. You can send urls instead! :param url: target URL :param filename: optional. set custom file name :param chunk_size: :return: InputFile """ pipe = _WebPipe(url, chunk_size=chunk_size) if filename is None: filename = pipe.name return cls(pipe, filename, chunk_size)
python
def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE): pipe = _WebPipe(url, chunk_size=chunk_size) if filename is None: filename = pipe.name return cls(pipe, filename, chunk_size)
[ "def", "from_url", "(", "cls", ",", "url", ",", "filename", "=", "None", ",", "chunk_size", "=", "CHUNK_SIZE", ")", ":", "pipe", "=", "_WebPipe", "(", "url", ",", "chunk_size", "=", "chunk_size", ")", "if", "filename", "is", "None", ":", "filename", "=...
Download file from URL Manually is not required action. You can send urls instead! :param url: target URL :param filename: optional. set custom file name :param chunk_size: :return: InputFile
[ "Download", "file", "from", "URL" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_file.py#L101-L117
238,528
aiogram/aiogram
aiogram/types/input_file.py
InputFile.save
def save(self, filename, chunk_size=CHUNK_SIZE): """ Write file to disk :param filename: :param chunk_size: """ with open(filename, 'wb') as fp: while True: # Chunk writer data = self.file.read(chunk_size) if not data: break fp.write(data) # Flush all data fp.flush() # Go to start of file. if self.file.seekable(): self.file.seek(0)
python
def save(self, filename, chunk_size=CHUNK_SIZE): with open(filename, 'wb') as fp: while True: # Chunk writer data = self.file.read(chunk_size) if not data: break fp.write(data) # Flush all data fp.flush() # Go to start of file. if self.file.seekable(): self.file.seek(0)
[ "def", "save", "(", "self", ",", "filename", ",", "chunk_size", "=", "CHUNK_SIZE", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "fp", ":", "while", "True", ":", "# Chunk writer", "data", "=", "self", ".", "file", ".", "read", "(...
Write file to disk :param filename: :param chunk_size:
[ "Write", "file", "to", "disk" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_file.py#L119-L138
238,529
aiogram/aiogram
aiogram/types/force_reply.py
ForceReply.create
def create(cls, selective: typing.Optional[base.Boolean] = None): """ Create new force reply :param selective: :return: """ return cls(selective=selective)
python
def create(cls, selective: typing.Optional[base.Boolean] = None): return cls(selective=selective)
[ "def", "create", "(", "cls", ",", "selective", ":", "typing", ".", "Optional", "[", "base", ".", "Boolean", "]", "=", "None", ")", ":", "return", "cls", "(", "selective", "=", "selective", ")" ]
Create new force reply :param selective: :return:
[ "Create", "new", "force", "reply" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/force_reply.py#L29-L36
238,530
aiogram/aiogram
examples/finite_state_machine_example.py
cancel_handler
async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None): """ Allow user to cancel any action """ if raw_state is None: return # Cancel state and inform user about it await state.finish() # And remove keyboard (just in case) await message.reply('Canceled.', reply_markup=types.ReplyKeyboardRemove())
python
async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None): if raw_state is None: return # Cancel state and inform user about it await state.finish() # And remove keyboard (just in case) await message.reply('Canceled.', reply_markup=types.ReplyKeyboardRemove())
[ "async", "def", "cancel_handler", "(", "message", ":", "types", ".", "Message", ",", "state", ":", "FSMContext", ",", "raw_state", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "if", "raw_state", "is", "None", ":", "return", "# Cancel state and ...
Allow user to cancel any action
[ "Allow", "user", "to", "cancel", "any", "action" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/finite_state_machine_example.py#L44-L54
238,531
aiogram/aiogram
examples/finite_state_machine_example.py
process_name
async def process_name(message: types.Message, state: FSMContext): """ Process user name """ async with state.proxy() as data: data['name'] = message.text await Form.next() await message.reply("How old are you?")
python
async def process_name(message: types.Message, state: FSMContext): async with state.proxy() as data: data['name'] = message.text await Form.next() await message.reply("How old are you?")
[ "async", "def", "process_name", "(", "message", ":", "types", ".", "Message", ",", "state", ":", "FSMContext", ")", ":", "async", "with", "state", ".", "proxy", "(", ")", "as", "data", ":", "data", "[", "'name'", "]", "=", "message", ".", "text", "aw...
Process user name
[ "Process", "user", "name" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/finite_state_machine_example.py#L58-L66
238,532
aiogram/aiogram
examples/middleware_and_antiflood.py
rate_limit
def rate_limit(limit: int, key=None): """ Decorator for configuring rate limit and key in different functions. :param limit: :param key: :return: """ def decorator(func): setattr(func, 'throttling_rate_limit', limit) if key: setattr(func, 'throttling_key', key) return func return decorator
python
def rate_limit(limit: int, key=None): def decorator(func): setattr(func, 'throttling_rate_limit', limit) if key: setattr(func, 'throttling_key', key) return func return decorator
[ "def", "rate_limit", "(", "limit", ":", "int", ",", "key", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "setattr", "(", "func", ",", "'throttling_rate_limit'", ",", "limit", ")", "if", "key", ":", "setattr", "(", "func", ",", "'t...
Decorator for configuring rate limit and key in different functions. :param limit: :param key: :return:
[ "Decorator", "for", "configuring", "rate", "limit", "and", "key", "in", "different", "functions", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L21-L36
238,533
aiogram/aiogram
examples/middleware_and_antiflood.py
ThrottlingMiddleware.on_process_message
async def on_process_message(self, message: types.Message, data: dict): """ This handler is called when dispatcher receives a message :param message: """ # Get current handler handler = current_handler.get() # Get dispatcher from context dispatcher = Dispatcher.get_current() # If handler was configured, get rate limit and key from handler if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" # Use Dispatcher.throttle method. try: await dispatcher.throttle(key, rate=limit) except Throttled as t: # Execute action await self.message_throttled(message, t) # Cancel current handler raise CancelHandler()
python
async def on_process_message(self, message: types.Message, data: dict): # Get current handler handler = current_handler.get() # Get dispatcher from context dispatcher = Dispatcher.get_current() # If handler was configured, get rate limit and key from handler if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" # Use Dispatcher.throttle method. try: await dispatcher.throttle(key, rate=limit) except Throttled as t: # Execute action await self.message_throttled(message, t) # Cancel current handler raise CancelHandler()
[ "async", "def", "on_process_message", "(", "self", ",", "message", ":", "types", ".", "Message", ",", "data", ":", "dict", ")", ":", "# Get current handler", "handler", "=", "current_handler", ".", "get", "(", ")", "# Get dispatcher from context", "dispatcher", ...
This handler is called when dispatcher receives a message :param message:
[ "This", "handler", "is", "called", "when", "dispatcher", "receives", "a", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L49-L76
238,534
aiogram/aiogram
examples/middleware_and_antiflood.py
ThrottlingMiddleware.message_throttled
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: await message.reply('Too many requests! ') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
python
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: await message.reply('Too many requests! ') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
[ "async", "def", "message_throttled", "(", "self", ",", "message", ":", "types", ".", "Message", ",", "throttled", ":", "Throttled", ")", ":", "handler", "=", "current_handler", ".", "get", "(", ")", "dispatcher", "=", "Dispatcher", ".", "get_current", "(", ...
Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled:
[ "Notify", "user", "only", "on", "first", "exceed", "and", "notify", "about", "unlocking", "only", "on", "last", "exceed" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L78-L107
238,535
aiogram/aiogram
aiogram/utils/auth_widget.py
generate_hash
def generate_hash(data: dict, token: str) -> str: """ Generate secret hash :param data: :param token: :return: """ secret = hashlib.sha256() secret.update(token.encode('utf-8')) sorted_params = collections.OrderedDict(sorted(data.items())) msg = '\n'.join("{}={}".format(k, v) for k, v in sorted_params.items() if k != 'hash') return hmac.new(secret.digest(), msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
python
def generate_hash(data: dict, token: str) -> str: secret = hashlib.sha256() secret.update(token.encode('utf-8')) sorted_params = collections.OrderedDict(sorted(data.items())) msg = '\n'.join("{}={}".format(k, v) for k, v in sorted_params.items() if k != 'hash') return hmac.new(secret.digest(), msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
[ "def", "generate_hash", "(", "data", ":", "dict", ",", "token", ":", "str", ")", "->", "str", ":", "secret", "=", "hashlib", ".", "sha256", "(", ")", "secret", ".", "update", "(", "token", ".", "encode", "(", "'utf-8'", ")", ")", "sorted_params", "="...
Generate secret hash :param data: :param token: :return:
[ "Generate", "secret", "hash" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L12-L24
238,536
aiogram/aiogram
aiogram/utils/auth_widget.py
check_token
def check_token(data: dict, token: str) -> bool: """ Validate auth token :param data: :param token: :return: """ param_hash = data.get('hash', '') or '' return param_hash == generate_hash(data, token)
python
def check_token(data: dict, token: str) -> bool: param_hash = data.get('hash', '') or '' return param_hash == generate_hash(data, token)
[ "def", "check_token", "(", "data", ":", "dict", ",", "token", ":", "str", ")", "->", "bool", ":", "param_hash", "=", "data", ".", "get", "(", "'hash'", ",", "''", ")", "or", "''", "return", "param_hash", "==", "generate_hash", "(", "data", ",", "toke...
Validate auth token :param data: :param token: :return:
[ "Validate", "auth", "token" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L27-L36
238,537
aiogram/aiogram
aiogram/dispatcher/filters/factory.py
FiltersFactory.resolve
def resolve(self, event_handler, *custom_filters, **full_config ) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]: """ Resolve filters to filters-set :param event_handler: :param custom_filters: :param full_config: :return: """ filters_set = [] filters_set.extend(self._resolve_registered(event_handler, {k: v for k, v in full_config.items() if v is not None})) if custom_filters: filters_set.extend(custom_filters) return filters_set
python
def resolve(self, event_handler, *custom_filters, **full_config ) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]: filters_set = [] filters_set.extend(self._resolve_registered(event_handler, {k: v for k, v in full_config.items() if v is not None})) if custom_filters: filters_set.extend(custom_filters) return filters_set
[ "def", "resolve", "(", "self", ",", "event_handler", ",", "*", "custom_filters", ",", "*", "*", "full_config", ")", "->", "typing", ".", "List", "[", "typing", ".", "Union", "[", "typing", ".", "Callable", ",", "AbstractFilter", "]", "]", ":", "filters_s...
Resolve filters to filters-set :param event_handler: :param custom_filters: :param full_config: :return:
[ "Resolve", "filters", "to", "filters", "-", "set" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/factory.py#L41-L57
238,538
aiogram/aiogram
aiogram/dispatcher/filters/factory.py
FiltersFactory._resolve_registered
def _resolve_registered(self, event_handler, full_config) -> typing.Generator: """ Resolve registered filters :param event_handler: :param full_config: :return: """ for record in self._registered: filter_ = record.resolve(self._dispatcher, event_handler, full_config) if filter_: yield filter_ if full_config: raise NameError('Invalid filter name(s): \'' + '\', '.join(full_config.keys()) + '\'')
python
def _resolve_registered(self, event_handler, full_config) -> typing.Generator: for record in self._registered: filter_ = record.resolve(self._dispatcher, event_handler, full_config) if filter_: yield filter_ if full_config: raise NameError('Invalid filter name(s): \'' + '\', '.join(full_config.keys()) + '\'')
[ "def", "_resolve_registered", "(", "self", ",", "event_handler", ",", "full_config", ")", "->", "typing", ".", "Generator", ":", "for", "record", "in", "self", ".", "_registered", ":", "filter_", "=", "record", ".", "resolve", "(", "self", ".", "_dispatcher"...
Resolve registered filters :param event_handler: :param full_config: :return:
[ "Resolve", "registered", "filters" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/factory.py#L59-L73
238,539
aiogram/aiogram
aiogram/types/auth_widget_data.py
AuthWidgetData.parse
def parse(cls, request: web.Request) -> AuthWidgetData: """ Parse request as Telegram auth widget data. :param request: :return: :obj:`AuthWidgetData` :raise: :obj:`aiohttp.web.HTTPBadRequest` """ try: query = dict(request.query) query['id'] = int(query['id']) query['auth_date'] = int(query['auth_date']) widget = AuthWidgetData(**query) except (ValueError, KeyError): raise web.HTTPBadRequest(text='Invalid auth data') else: return widget
python
def parse(cls, request: web.Request) -> AuthWidgetData: try: query = dict(request.query) query['id'] = int(query['id']) query['auth_date'] = int(query['auth_date']) widget = AuthWidgetData(**query) except (ValueError, KeyError): raise web.HTTPBadRequest(text='Invalid auth data') else: return widget
[ "def", "parse", "(", "cls", ",", "request", ":", "web", ".", "Request", ")", "->", "AuthWidgetData", ":", "try", ":", "query", "=", "dict", "(", "request", ".", "query", ")", "query", "[", "'id'", "]", "=", "int", "(", "query", "[", "'id'", "]", ...
Parse request as Telegram auth widget data. :param request: :return: :obj:`AuthWidgetData` :raise: :obj:`aiohttp.web.HTTPBadRequest`
[ "Parse", "request", "as", "Telegram", "auth", "widget", "data", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/auth_widget_data.py#L19-L35
238,540
aiogram/aiogram
aiogram/dispatcher/webhook.py
_check_ip
def _check_ip(ip: str) -> bool: """ Check IP in range :param ip: :return: """ address = ipaddress.IPv4Address(ip) return address in allowed_ips
python
def _check_ip(ip: str) -> bool: address = ipaddress.IPv4Address(ip) return address in allowed_ips
[ "def", "_check_ip", "(", "ip", ":", "str", ")", "->", "bool", ":", "address", "=", "ipaddress", ".", "IPv4Address", "(", "ip", ")", "return", "address", "in", "allowed_ips" ]
Check IP in range :param ip: :return:
[ "Check", "IP", "in", "range" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L39-L47
238,541
aiogram/aiogram
aiogram/dispatcher/webhook.py
allow_ip
def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]): """ Allow ip address. :param ips: :return: """ for ip in ips: if isinstance(ip, ipaddress.IPv4Address): allowed_ips.add(ip) elif isinstance(ip, str): allowed_ips.add(ipaddress.IPv4Address(ip)) elif isinstance(ip, ipaddress.IPv4Network): allowed_ips.update(ip.hosts()) else: raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')")
python
def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]): for ip in ips: if isinstance(ip, ipaddress.IPv4Address): allowed_ips.add(ip) elif isinstance(ip, str): allowed_ips.add(ipaddress.IPv4Address(ip)) elif isinstance(ip, ipaddress.IPv4Network): allowed_ips.update(ip.hosts()) else: raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')")
[ "def", "allow_ip", "(", "*", "ips", ":", "typing", ".", "Union", "[", "str", ",", "ipaddress", ".", "IPv4Network", ",", "ipaddress", ".", "IPv4Address", "]", ")", ":", "for", "ip", "in", "ips", ":", "if", "isinstance", "(", "ip", ",", "ipaddress", "....
Allow ip address. :param ips: :return:
[ "Allow", "ip", "address", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L50-L65
238,542
aiogram/aiogram
aiogram/dispatcher/webhook.py
configure_app
def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME): """ You can prepare web.Application for working with webhook handler. :param dispatcher: Dispatcher instance :param app: :class:`aiohttp.web.Application` :param path: Path to your webhook. :param route_name: Name of webhook handler route :return: """ app.router.add_route('*', path, WebhookRequestHandler, name=route_name) app[BOT_DISPATCHER_KEY] = dispatcher
python
def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME): app.router.add_route('*', path, WebhookRequestHandler, name=route_name) app[BOT_DISPATCHER_KEY] = dispatcher
[ "def", "configure_app", "(", "dispatcher", ",", "app", ":", "web", ".", "Application", ",", "path", "=", "DEFAULT_WEB_PATH", ",", "route_name", "=", "DEFAULT_ROUTE_NAME", ")", ":", "app", ".", "router", ".", "add_route", "(", "'*'", ",", "path", ",", "Webh...
You can prepare web.Application for working with webhook handler. :param dispatcher: Dispatcher instance :param app: :class:`aiohttp.web.Application` :param path: Path to your webhook. :param route_name: Name of webhook handler route :return:
[ "You", "can", "prepare", "web", ".", "Application", "for", "working", "with", "webhook", "handler", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L278-L289
238,543
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.get_dispatcher
def get_dispatcher(self): """ Get Dispatcher instance from environment :return: :class:`aiogram.Dispatcher` """ dp = self.request.app[BOT_DISPATCHER_KEY] try: from aiogram import Bot, Dispatcher Dispatcher.set_current(dp) Bot.set_current(dp.bot) except RuntimeError: pass return dp
python
def get_dispatcher(self): dp = self.request.app[BOT_DISPATCHER_KEY] try: from aiogram import Bot, Dispatcher Dispatcher.set_current(dp) Bot.set_current(dp.bot) except RuntimeError: pass return dp
[ "def", "get_dispatcher", "(", "self", ")", ":", "dp", "=", "self", ".", "request", ".", "app", "[", "BOT_DISPATCHER_KEY", "]", "try", ":", "from", "aiogram", "import", "Bot", ",", "Dispatcher", "Dispatcher", ".", "set_current", "(", "dp", ")", "Bot", "."...
Get Dispatcher instance from environment :return: :class:`aiogram.Dispatcher`
[ "Get", "Dispatcher", "instance", "from", "environment" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L93-L106
238,544
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.parse_update
async def parse_update(self, bot): """ Read update from stream and deserialize it. :param bot: bot instance. You an get it from Dispatcher :return: :class:`aiogram.types.Update` """ data = await self.request.json() update = types.Update(**data) return update
python
async def parse_update(self, bot): data = await self.request.json() update = types.Update(**data) return update
[ "async", "def", "parse_update", "(", "self", ",", "bot", ")", ":", "data", "=", "await", "self", ".", "request", ".", "json", "(", ")", "update", "=", "types", ".", "Update", "(", "*", "*", "data", ")", "return", "update" ]
Read update from stream and deserialize it. :param bot: bot instance. You an get it from Dispatcher :return: :class:`aiogram.types.Update`
[ "Read", "update", "from", "stream", "and", "deserialize", "it", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L108-L117
238,545
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.post
async def post(self): """ Process POST request if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook. Otherwise do nothing (return 'ok') :return: :class:`aiohttp.web.Response` """ self.validate_ip() # context.update_state({'CALLER': WEBHOOK, # WEBHOOK_CONNECTION: True, # WEBHOOK_REQUEST: self.request}) dispatcher = self.get_dispatcher() update = await self.parse_update(dispatcher.bot) results = await self.process_update(update) response = self.get_response(results) if response: web_response = response.get_web_response() else: web_response = web.Response(text='ok') if self.request.app.get('RETRY_AFTER', None): web_response.headers['Retry-After'] = self.request.app['RETRY_AFTER'] return web_response
python
async def post(self): self.validate_ip() # context.update_state({'CALLER': WEBHOOK, # WEBHOOK_CONNECTION: True, # WEBHOOK_REQUEST: self.request}) dispatcher = self.get_dispatcher() update = await self.parse_update(dispatcher.bot) results = await self.process_update(update) response = self.get_response(results) if response: web_response = response.get_web_response() else: web_response = web.Response(text='ok') if self.request.app.get('RETRY_AFTER', None): web_response.headers['Retry-After'] = self.request.app['RETRY_AFTER'] return web_response
[ "async", "def", "post", "(", "self", ")", ":", "self", ".", "validate_ip", "(", ")", "# context.update_state({'CALLER': WEBHOOK,", "# WEBHOOK_CONNECTION: True,", "# WEBHOOK_REQUEST: self.request})", "dispatcher", "=", "self", ".", "ge...
Process POST request if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook. Otherwise do nothing (return 'ok') :return: :class:`aiohttp.web.Response`
[ "Process", "POST", "request" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L119-L148
238,546
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.process_update
async def process_update(self, update): """ Need respond in less than 60 seconds in to webhook. So... If you respond greater than 55 seconds webhook automatically respond 'ok' and execute callback response via simple HTTP request. :param update: :return: """ dispatcher = self.get_dispatcher() loop = dispatcher.loop # Analog of `asyncio.wait_for` but without cancelling task waiter = loop.create_future() timeout_handle = loop.call_later(RESPONSE_TIMEOUT, asyncio.tasks._release_waiter, waiter) cb = functools.partial(asyncio.tasks._release_waiter, waiter) fut = asyncio.ensure_future(dispatcher.updates_handler.notify(update), loop=loop) fut.add_done_callback(cb) try: try: await waiter except asyncio.futures.CancelledError: fut.remove_done_callback(cb) fut.cancel() raise if fut.done(): return fut.result() else: # context.set_value(WEBHOOK_CONNECTION, False) fut.remove_done_callback(cb) fut.add_done_callback(self.respond_via_request) finally: timeout_handle.cancel()
python
async def process_update(self, update): dispatcher = self.get_dispatcher() loop = dispatcher.loop # Analog of `asyncio.wait_for` but without cancelling task waiter = loop.create_future() timeout_handle = loop.call_later(RESPONSE_TIMEOUT, asyncio.tasks._release_waiter, waiter) cb = functools.partial(asyncio.tasks._release_waiter, waiter) fut = asyncio.ensure_future(dispatcher.updates_handler.notify(update), loop=loop) fut.add_done_callback(cb) try: try: await waiter except asyncio.futures.CancelledError: fut.remove_done_callback(cb) fut.cancel() raise if fut.done(): return fut.result() else: # context.set_value(WEBHOOK_CONNECTION, False) fut.remove_done_callback(cb) fut.add_done_callback(self.respond_via_request) finally: timeout_handle.cancel()
[ "async", "def", "process_update", "(", "self", ",", "update", ")", ":", "dispatcher", "=", "self", ".", "get_dispatcher", "(", ")", "loop", "=", "dispatcher", ".", "loop", "# Analog of `asyncio.wait_for` but without cancelling task", "waiter", "=", "loop", ".", "c...
Need respond in less than 60 seconds in to webhook. So... If you respond greater than 55 seconds webhook automatically respond 'ok' and execute callback response via simple HTTP request. :param update: :return:
[ "Need", "respond", "in", "less", "than", "60", "seconds", "in", "to", "webhook", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L158-L194
238,547
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.respond_via_request
def respond_via_request(self, task): """ Handle response after 55 second. :param task: :return: """ warn(f"Detected slow response into webhook. " f"(Greater than {RESPONSE_TIMEOUT} seconds)\n" f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.", TimeoutWarning) dispatcher = self.get_dispatcher() loop = dispatcher.loop try: results = task.result() except Exception as e: loop.create_task( dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e)) else: response = self.get_response(results) if response is not None: asyncio.ensure_future(response.execute_response(dispatcher.bot), loop=loop)
python
def respond_via_request(self, task): warn(f"Detected slow response into webhook. " f"(Greater than {RESPONSE_TIMEOUT} seconds)\n" f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.", TimeoutWarning) dispatcher = self.get_dispatcher() loop = dispatcher.loop try: results = task.result() except Exception as e: loop.create_task( dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e)) else: response = self.get_response(results) if response is not None: asyncio.ensure_future(response.execute_response(dispatcher.bot), loop=loop)
[ "def", "respond_via_request", "(", "self", ",", "task", ")", ":", "warn", "(", "f\"Detected slow response into webhook. \"", "f\"(Greater than {RESPONSE_TIMEOUT} seconds)\\n\"", "f\"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.\"", ",", "Timeou...
Handle response after 55 second. :param task: :return:
[ "Handle", "response", "after", "55", "second", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L196-L219
238,548
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.get_response
def get_response(self, results): """ Get response object from results. :param results: list :return: """ if results is None: return None for result in itertools.chain.from_iterable(results): if isinstance(result, BaseResponse): return result
python
def get_response(self, results): if results is None: return None for result in itertools.chain.from_iterable(results): if isinstance(result, BaseResponse): return result
[ "def", "get_response", "(", "self", ",", "results", ")", ":", "if", "results", "is", "None", ":", "return", "None", "for", "result", "in", "itertools", ".", "chain", ".", "from_iterable", "(", "results", ")", ":", "if", "isinstance", "(", "result", ",", ...
Get response object from results. :param results: list :return:
[ "Get", "response", "object", "from", "results", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L221-L232
238,549
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.check_ip
def check_ip(self): """ Check client IP. Accept requests only from telegram servers. :return: """ # For reverse proxy (nginx) forwarded_for = self.request.headers.get('X-Forwarded-For', None) if forwarded_for: return forwarded_for, _check_ip(forwarded_for) # For default method peer_name = self.request.transport.get_extra_info('peername') if peer_name is not None: host, _ = peer_name return host, _check_ip(host) # Not allowed and can't get client IP return None, False
python
def check_ip(self): # For reverse proxy (nginx) forwarded_for = self.request.headers.get('X-Forwarded-For', None) if forwarded_for: return forwarded_for, _check_ip(forwarded_for) # For default method peer_name = self.request.transport.get_extra_info('peername') if peer_name is not None: host, _ = peer_name return host, _check_ip(host) # Not allowed and can't get client IP return None, False
[ "def", "check_ip", "(", "self", ")", ":", "# For reverse proxy (nginx)", "forwarded_for", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "'X-Forwarded-For'", ",", "None", ")", "if", "forwarded_for", ":", "return", "forwarded_for", ",", "_check_ip"...
Check client IP. Accept requests only from telegram servers. :return:
[ "Check", "client", "IP", ".", "Accept", "requests", "only", "from", "telegram", "servers", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L234-L252
238,550
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.validate_ip
def validate_ip(self): """ Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts. """ if self.request.app.get('_check_ip', False): ip_address, accept = self.check_ip() if not accept: raise web.HTTPUnauthorized()
python
def validate_ip(self): if self.request.app.get('_check_ip', False): ip_address, accept = self.check_ip() if not accept: raise web.HTTPUnauthorized()
[ "def", "validate_ip", "(", "self", ")", ":", "if", "self", ".", "request", ".", "app", ".", "get", "(", "'_check_ip'", ",", "False", ")", ":", "ip_address", ",", "accept", "=", "self", ".", "check_ip", "(", ")", "if", "not", "accept", ":", "raise", ...
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
[ "Check", "ip", "if", "that", "is", "needed", ".", "Raise", "web", ".", "HTTPUnauthorized", "for", "not", "allowed", "hosts", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L254-L261
238,551
aiogram/aiogram
aiogram/dispatcher/webhook.py
BaseResponse.cleanup
def cleanup(self) -> typing.Dict: """ Cleanup response after preparing. Remove empty fields. :return: response parameters dict """ return {k: v for k, v in self.prepare().items() if v is not None}
python
def cleanup(self) -> typing.Dict: return {k: v for k, v in self.prepare().items() if v is not None}
[ "def", "cleanup", "(", "self", ")", "->", "typing", ".", "Dict", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "prepare", "(", ")", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}" ]
Cleanup response after preparing. Remove empty fields. :return: response parameters dict
[ "Cleanup", "response", "after", "preparing", ".", "Remove", "empty", "fields", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L327-L333
238,552
aiogram/aiogram
aiogram/dispatcher/webhook.py
BaseResponse.execute_response
async def execute_response(self, bot): """ Use this method if you want to execute response as simple HTTP request. :param bot: Bot instance. :return: """ method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case) method = getattr(bot, method_name, None) if method: return await method(**self.cleanup()) return await bot.request(self.method, self.cleanup())
python
async def execute_response(self, bot): method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case) method = getattr(bot, method_name, None) if method: return await method(**self.cleanup()) return await bot.request(self.method, self.cleanup())
[ "async", "def", "execute_response", "(", "self", ",", "bot", ")", ":", "method_name", "=", "helper", ".", "HelperMode", ".", "apply", "(", "self", ".", "method", ",", "helper", ".", "HelperMode", ".", "snake_case", ")", "method", "=", "getattr", "(", "bo...
Use this method if you want to execute response as simple HTTP request. :param bot: Bot instance. :return:
[ "Use", "this", "method", "if", "you", "want", "to", "execute", "response", "as", "simple", "HTTP", "request", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L351-L362
238,553
aiogram/aiogram
aiogram/dispatcher/webhook.py
ReplyToMixin.reply
def reply(self, message: typing.Union[int, types.Message]): """ Reply to message :param message: :obj:`int` or :obj:`types.Message` :return: self """ setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message) return self
python
def reply(self, message: typing.Union[int, types.Message]): setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message) return self
[ "def", "reply", "(", "self", ",", "message", ":", "typing", ".", "Union", "[", "int", ",", "types", ".", "Message", "]", ")", ":", "setattr", "(", "self", ",", "'reply_to_message_id'", ",", "message", ".", "message_id", "if", "isinstance", "(", "message"...
Reply to message :param message: :obj:`int` or :obj:`types.Message` :return: self
[ "Reply", "to", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L382-L390
238,554
aiogram/aiogram
aiogram/dispatcher/webhook.py
ReplyToMixin.to
def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]): """ Send to chat :param target: message or chat or id :return: """ if isinstance(target, types.Message): chat_id = target.chat.id elif isinstance(target, types.Chat): chat_id = target.id elif isinstance(target, (int, str)): chat_id = target else: raise TypeError(f"Bad type of target. ({type(target)})") setattr(self, 'chat_id', chat_id) return self
python
def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]): if isinstance(target, types.Message): chat_id = target.chat.id elif isinstance(target, types.Chat): chat_id = target.id elif isinstance(target, (int, str)): chat_id = target else: raise TypeError(f"Bad type of target. ({type(target)})") setattr(self, 'chat_id', chat_id) return self
[ "def", "to", "(", "self", ",", "target", ":", "typing", ".", "Union", "[", "types", ".", "Message", ",", "types", ".", "Chat", ",", "types", ".", "base", ".", "Integer", ",", "types", ".", "base", ".", "String", "]", ")", ":", "if", "isinstance", ...
Send to chat :param target: message or chat or id :return:
[ "Send", "to", "chat" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L392-L409
238,555
aiogram/aiogram
aiogram/dispatcher/webhook.py
SendMessage.write
def write(self, *text, sep=' '): """ Write text to response :param text: :param sep: :return: """ self.text += markdown.text(*text, sep) return self
python
def write(self, *text, sep=' '): self.text += markdown.text(*text, sep) return self
[ "def", "write", "(", "self", ",", "*", "text", ",", "sep", "=", "' '", ")", ":", "self", ".", "text", "+=", "markdown", ".", "text", "(", "*", "text", ",", "sep", ")", "return", "self" ]
Write text to response :param text: :param sep: :return:
[ "Write", "text", "to", "response" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L524-L533
238,556
aiogram/aiogram
aiogram/dispatcher/webhook.py
ForwardMessage.message
def message(self, message: types.Message): """ Select target message :param message: :return: """ setattr(self, 'from_chat_id', message.chat.id) setattr(self, 'message_id', message.message_id) return self
python
def message(self, message: types.Message): setattr(self, 'from_chat_id', message.chat.id) setattr(self, 'message_id', message.message_id) return self
[ "def", "message", "(", "self", ",", "message", ":", "types", ".", "Message", ")", ":", "setattr", "(", "self", ",", "'from_chat_id'", ",", "message", ".", "chat", ".", "id", ")", "setattr", "(", "self", ",", "'message_id'", ",", "message", ".", "messag...
Select target message :param message: :return:
[ "Select", "target", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L575-L584
238,557
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.check_address
def check_address(cls, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]): """ In all storage's methods chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. This method performs the check described above. :param chat: :param user: :return: """ if chat is None and user is None: raise ValueError('`user` or `chat` parameter is required but no one is provided!') if user is None and chat is not None: user = chat elif user is not None and chat is None: chat = user return chat, user
python
def check_address(cls, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]): if chat is None and user is None: raise ValueError('`user` or `chat` parameter is required but no one is provided!') if user is None and chat is not None: user = chat elif user is not None and chat is None: chat = user return chat, user
[ "def", "check_address", "(", "cls", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ")",...
In all storage's methods chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. This method performs the check described above. :param chat: :param user: :return:
[ "In", "all", "storage", "s", "methods", "chat", "or", "user", "is", "always", "required", ".", "If", "one", "of", "them", "is", "not", "provided", "you", "have", "to", "set", "missing", "value", "based", "on", "the", "provided", "one", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L41-L61
238,558
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.get_data
async def get_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, default: typing.Optional[typing.Dict] = None) -> typing.Dict: """ Get state-data for user in chat. Return `default` if no data is provided in storage. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param default: :return: """ raise NotImplementedError
python
async def get_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, default: typing.Optional[typing.Dict] = None) -> typing.Dict: raise NotImplementedError
[ "async", "def", "get_data", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None",...
Get state-data for user in chat. Return `default` if no data is provided in storage. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param default: :return:
[ "Get", "state", "-", "data", "for", "user", "in", "chat", ".", "Return", "default", "if", "no", "data", "is", "provided", "in", "storage", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L80-L95
238,559
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.update_data
async def update_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, data: typing.Dict = None, **kwargs): """ Update data for user in chat You can use data parameter or|and kwargs. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param data: :param chat: :param user: :param kwargs: :return: """ raise NotImplementedError
python
async def update_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, data: typing.Dict = None, **kwargs): raise NotImplementedError
[ "async", "def", "update_data", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "Non...
Update data for user in chat You can use data parameter or|and kwargs. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param data: :param chat: :param user: :param kwargs: :return:
[ "Update", "data", "for", "user", "in", "chat" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L129-L148
238,560
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.reset_state
async def reset_state(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, with_data: typing.Optional[bool] = True): """ Reset state for user in chat. You may desire to use this method when finishing conversations. Chat or user is always required. If one of this is not presented, you have to set missing value based on the provided one. :param chat: :param user: :param with_data: :return: """ chat, user = self.check_address(chat=chat, user=user) await self.set_state(chat=chat, user=user, state=None) if with_data: await self.set_data(chat=chat, user=user, data={})
python
async def reset_state(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, with_data: typing.Optional[bool] = True): chat, user = self.check_address(chat=chat, user=user) await self.set_state(chat=chat, user=user, state=None) if with_data: await self.set_data(chat=chat, user=user, data={})
[ "async", "def", "reset_state", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "Non...
Reset state for user in chat. You may desire to use this method when finishing conversations. Chat or user is always required. If one of this is not presented, you have to set missing value based on the provided one. :param chat: :param user: :param with_data: :return:
[ "Reset", "state", "for", "user", "in", "chat", ".", "You", "may", "desire", "to", "use", "this", "method", "when", "finishing", "conversations", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L165-L184
238,561
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.finish
async def finish(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None): """ Finish conversation for user in chat. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :return: """ await self.reset_state(chat=chat, user=user, with_data=True)
python
async def finish(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None): await self.reset_state(chat=chat, user=user, with_data=True)
[ "async", "def", "finish", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ...
Finish conversation for user in chat. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :return:
[ "Finish", "conversation", "for", "user", "in", "chat", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L186-L199
238,562
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.get_bucket
async def get_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, default: typing.Optional[dict] = None) -> typing.Dict: """ Get bucket for user in chat. Return `default` if no data is provided in storage. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param default: :return: """ raise NotImplementedError
python
async def get_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, default: typing.Optional[dict] = None) -> typing.Dict: raise NotImplementedError
[ "async", "def", "get_bucket", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None...
Get bucket for user in chat. Return `default` if no data is provided in storage. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param default: :return:
[ "Get", "bucket", "for", "user", "in", "chat", ".", "Return", "default", "if", "no", "data", "is", "provided", "in", "storage", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L204-L219
238,563
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.set_bucket
async def set_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, bucket: typing.Dict = None): """ Set bucket for user in chat Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param bucket: """ raise NotImplementedError
python
async def set_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, bucket: typing.Dict = None): raise NotImplementedError
[ "async", "def", "set_bucket", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None...
Set bucket for user in chat Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param bucket:
[ "Set", "bucket", "for", "user", "in", "chat" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L221-L235
238,564
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.update_bucket
async def update_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, bucket: typing.Dict = None, **kwargs): """ Update bucket for user in chat You can use bucket parameter or|and kwargs. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param bucket: :param chat: :param user: :param kwargs: :return: """ raise NotImplementedError
python
async def update_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, bucket: typing.Dict = None, **kwargs): raise NotImplementedError
[ "async", "def", "update_bucket", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "N...
Update bucket for user in chat You can use bucket parameter or|and kwargs. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param bucket: :param chat: :param user: :param kwargs: :return:
[ "Update", "bucket", "for", "user", "in", "chat" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L237-L256
238,565
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.reset_bucket
async def reset_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None): """ Reset bucket dor user in chat. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :return: """ await self.set_data(chat=chat, user=user, data={})
python
async def reset_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None): await self.set_data(chat=chat, user=user, data={})
[ "async", "def", "reset_bucket", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "No...
Reset bucket dor user in chat. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :return:
[ "Reset", "bucket", "dor", "user", "in", "chat", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L258-L271
238,566
aiogram/aiogram
aiogram/contrib/fsm_storage/rethinkdb.py
RethinkDBStorage.connect
async def connect(self) -> Connection: """ Get or create a connection. """ if self._conn is None: self._conn = await r.connect(host=self._host, port=self._port, db=self._db, auth_key=self._auth_key, user=self._user, password=self._password, timeout=self._timeout, ssl=self._ssl, io_loop=self._loop) return self._conn
python
async def connect(self) -> Connection: if self._conn is None: self._conn = await r.connect(host=self._host, port=self._port, db=self._db, auth_key=self._auth_key, user=self._user, password=self._password, timeout=self._timeout, ssl=self._ssl, io_loop=self._loop) return self._conn
[ "async", "def", "connect", "(", "self", ")", "->", "Connection", ":", "if", "self", ".", "_conn", "is", "None", ":", "self", ".", "_conn", "=", "await", "r", ".", "connect", "(", "host", "=", "self", ".", "_host", ",", "port", "=", "self", ".", "...
Get or create a connection.
[ "Get", "or", "create", "a", "connection", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/fsm_storage/rethinkdb.py#L59-L73
238,567
aiogram/aiogram
aiogram/types/input_media.py
MediaGroup.attach_many
def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]): """ Attach list of media :param medias: """ for media in medias: self.attach(media)
python
def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]): for media in medias: self.attach(media)
[ "def", "attach_many", "(", "self", ",", "*", "medias", ":", "typing", ".", "Union", "[", "InputMedia", ",", "typing", ".", "Dict", "]", ")", ":", "for", "media", "in", "medias", ":", "self", ".", "attach", "(", "media", ")" ]
Attach list of media :param medias:
[ "Attach", "list", "of", "media" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_media.py#L209-L216
238,568
aiogram/aiogram
aiogram/dispatcher/filters/builtin.py
Command.validate
def validate(cls, full_config: Dict[str, Any]) -> Optional[Dict[str, Any]]: """ Validator for filters factory From filters factory this filter can be registered with arguments: - ``command`` - ``commands_prefix`` (will be passed as ``prefixes``) - ``commands_ignore_mention`` (will be passed as ``ignore_mention`` :param full_config: :return: config or empty dict """ config = {} if 'commands' in full_config: config['commands'] = full_config.pop('commands') if config and 'commands_prefix' in full_config: config['prefixes'] = full_config.pop('commands_prefix') if config and 'commands_ignore_mention' in full_config: config['ignore_mention'] = full_config.pop('commands_ignore_mention') return config
python
def validate(cls, full_config: Dict[str, Any]) -> Optional[Dict[str, Any]]: config = {} if 'commands' in full_config: config['commands'] = full_config.pop('commands') if config and 'commands_prefix' in full_config: config['prefixes'] = full_config.pop('commands_prefix') if config and 'commands_ignore_mention' in full_config: config['ignore_mention'] = full_config.pop('commands_ignore_mention') return config
[ "def", "validate", "(", "cls", ",", "full_config", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "config", "=", "{", "}", "if", "'commands'", "in", "full_config", ":", "config",...
Validator for filters factory From filters factory this filter can be registered with arguments: - ``command`` - ``commands_prefix`` (will be passed as ``prefixes``) - ``commands_ignore_mention`` (will be passed as ``ignore_mention`` :param full_config: :return: config or empty dict
[ "Validator", "for", "filters", "factory" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/builtin.py#L55-L75
238,569
aiogram/aiogram
aiogram/dispatcher/filters/builtin.py
CommandStart.check
async def check(self, message: types.Message): """ If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler :param message: :return: """ check = await super(CommandStart, self).check(message) if check and self.deep_link is not None: if not isinstance(self.deep_link, re.Pattern): return message.get_args() == self.deep_link match = self.deep_link.match(message.get_args()) if match: return {'deep_link': match} return False return check
python
async def check(self, message: types.Message): check = await super(CommandStart, self).check(message) if check and self.deep_link is not None: if not isinstance(self.deep_link, re.Pattern): return message.get_args() == self.deep_link match = self.deep_link.match(message.get_args()) if match: return {'deep_link': match} return False return check
[ "async", "def", "check", "(", "self", ",", "message", ":", "types", ".", "Message", ")", ":", "check", "=", "await", "super", "(", "CommandStart", ",", "self", ")", ".", "check", "(", "message", ")", "if", "check", "and", "self", ".", "deep_link", "i...
If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler :param message: :return:
[ "If", "deep", "-", "linking", "is", "passed", "to", "the", "filter", "result", "of", "the", "matching", "will", "be", "passed", "as", "deep_link", "to", "the", "handler" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/builtin.py#L155-L173
238,570
aiogram/aiogram
aiogram/utils/parts.py
paginate
def paginate(data: typing.Iterable, page: int = 0, limit: int = 10) -> typing.Iterable: """ Slice data over pages :param data: any iterable object :type data: :obj:`typing.Iterable` :param page: number of page :type page: :obj:`int` :param limit: items per page :type limit: :obj:`int` :return: sliced object :rtype: :obj:`typing.Iterable` """ return data[page * limit:page * limit + limit]
python
def paginate(data: typing.Iterable, page: int = 0, limit: int = 10) -> typing.Iterable: return data[page * limit:page * limit + limit]
[ "def", "paginate", "(", "data", ":", "typing", ".", "Iterable", ",", "page", ":", "int", "=", "0", ",", "limit", ":", "int", "=", "10", ")", "->", "typing", ".", "Iterable", ":", "return", "data", "[", "page", "*", "limit", ":", "page", "*", "lim...
Slice data over pages :param data: any iterable object :type data: :obj:`typing.Iterable` :param page: number of page :type page: :obj:`int` :param limit: items per page :type limit: :obj:`int` :return: sliced object :rtype: :obj:`typing.Iterable`
[ "Slice", "data", "over", "pages" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/parts.py#L46-L59
238,571
aiogram/aiogram
aiogram/bot/bot.py
Bot.download_file_by_id
async def download_file_by_id(self, file_id: base.String, destination=None, timeout: base.Integer = 30, chunk_size: base.Integer = 65536, seek: base.Boolean = True): """ Download file by file_id to destination if You want to automatically create destination (:class:`io.BytesIO`) use default value of destination and handle result of this method. :param file_id: str :param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO` :param timeout: int :param chunk_size: int :param seek: bool - go to start of file when downloading is finished :return: destination """ file = await self.get_file(file_id) return await self.download_file(file_path=file.file_path, destination=destination, timeout=timeout, chunk_size=chunk_size, seek=seek)
python
async def download_file_by_id(self, file_id: base.String, destination=None, timeout: base.Integer = 30, chunk_size: base.Integer = 65536, seek: base.Boolean = True): file = await self.get_file(file_id) return await self.download_file(file_path=file.file_path, destination=destination, timeout=timeout, chunk_size=chunk_size, seek=seek)
[ "async", "def", "download_file_by_id", "(", "self", ",", "file_id", ":", "base", ".", "String", ",", "destination", "=", "None", ",", "timeout", ":", "base", ".", "Integer", "=", "30", ",", "chunk_size", ":", "base", ".", "Integer", "=", "65536", ",", ...
Download file by file_id to destination if You want to automatically create destination (:class:`io.BytesIO`) use default value of destination and handle result of this method. :param file_id: str :param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO` :param timeout: int :param chunk_size: int :param seek: bool - go to start of file when downloading is finished :return: destination
[ "Download", "file", "by", "file_id", "to", "destination" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L42-L60
238,572
aiogram/aiogram
aiogram/bot/bot.py
Bot.get_webhook_info
async def get_webhook_info(self) -> types.WebhookInfo: """ Use this method to get current webhook status. Requires no parameters. If the bot is using getUpdates, will return an object with the url field empty. Source: https://core.telegram.org/bots/api#getwebhookinfo :return: On success, returns a WebhookInfo object :rtype: :obj:`types.WebhookInfo` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_WEBHOOK_INFO, payload) return types.WebhookInfo(**result)
python
async def get_webhook_info(self) -> types.WebhookInfo: payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_WEBHOOK_INFO, payload) return types.WebhookInfo(**result)
[ "async", "def", "get_webhook_info", "(", "self", ")", "->", "types", ".", "WebhookInfo", ":", "payload", "=", "generate_payload", "(", "*", "*", "locals", "(", ")", ")", "result", "=", "await", "self", ".", "request", "(", "api", ".", "Methods", ".", "...
Use this method to get current webhook status. Requires no parameters. If the bot is using getUpdates, will return an object with the url field empty. Source: https://core.telegram.org/bots/api#getwebhookinfo :return: On success, returns a WebhookInfo object :rtype: :obj:`types.WebhookInfo`
[ "Use", "this", "method", "to", "get", "current", "webhook", "status", ".", "Requires", "no", "parameters", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L144-L158
238,573
aiogram/aiogram
aiogram/bot/bot.py
Bot.get_me
async def get_me(self) -> types.User: """ A simple method for testing your bot's auth token. Requires no parameters. Source: https://core.telegram.org/bots/api#getme :return: Returns basic information about the bot in form of a User object :rtype: :obj:`types.User` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_ME, payload) return types.User(**result)
python
async def get_me(self) -> types.User: payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_ME, payload) return types.User(**result)
[ "async", "def", "get_me", "(", "self", ")", "->", "types", ".", "User", ":", "payload", "=", "generate_payload", "(", "*", "*", "locals", "(", ")", ")", "result", "=", "await", "self", ".", "request", "(", "api", ".", "Methods", ".", "GET_ME", ",", ...
A simple method for testing your bot's auth token. Requires no parameters. Source: https://core.telegram.org/bots/api#getme :return: Returns basic information about the bot in form of a User object :rtype: :obj:`types.User`
[ "A", "simple", "method", "for", "testing", "your", "bot", "s", "auth", "token", ".", "Requires", "no", "parameters", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L163-L175
238,574
aiogram/aiogram
aiogram/bot/bot.py
Bot.send_poll
async def send_poll(self, chat_id: typing.Union[base.Integer, base.String], question: base.String, options: typing.List[base.String], disable_notification: typing.Optional[base.Boolean], reply_to_message_id: typing.Union[base.Integer, None], reply_markup: typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None] = None) -> types.Message: """ Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent Message is returned. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername). A native poll can't be sent to a private chat. :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param question: Poll question, 1-255 characters :type question: :obj:`base.String` :param options: List of answer options, 2-10 strings 1-100 characters each :param options: :obj:`typing.List[base.String]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: :obj:`typing.Optional[Boolean]` :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: :obj:`typing.Optional[Integer]` :param reply_markup: Additional interface options :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]` :return: On success, the sent Message is returned :rtype: :obj:`types.Message` """ options = prepare_arg(options) payload = generate_payload(**locals()) result = await self.request(api.Methods.SEND_POLL, payload) return types.Message(**result)
python
async def send_poll(self, chat_id: typing.Union[base.Integer, base.String], question: base.String, options: typing.List[base.String], disable_notification: typing.Optional[base.Boolean], reply_to_message_id: typing.Union[base.Integer, None], reply_markup: typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None] = None) -> types.Message: options = prepare_arg(options) payload = generate_payload(**locals()) result = await self.request(api.Methods.SEND_POLL, payload) return types.Message(**result)
[ "async", "def", "send_poll", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ",", "question", ":", "base", ".", "String", ",", "options", ":", "typing", ".", "List", "[", "base",...
Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent Message is returned. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername). A native poll can't be sent to a private chat. :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param question: Poll question, 1-255 characters :type question: :obj:`base.String` :param options: List of answer options, 2-10 strings 1-100 characters each :param options: :obj:`typing.List[base.String]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: :obj:`typing.Optional[Boolean]` :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: :obj:`typing.Optional[Integer]` :param reply_markup: Additional interface options :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]` :return: On success, the sent Message is returned :rtype: :obj:`types.Message`
[ "Use", "this", "method", "to", "send", "a", "native", "poll", ".", "A", "native", "poll", "can", "t", "be", "sent", "to", "a", "private", "chat", ".", "On", "success", "the", "sent", "Message", "is", "returned", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L850-L885
238,575
aiogram/aiogram
aiogram/bot/bot.py
Bot.get_file
async def get_file(self, file_id: base.String) -> types.File: """ Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. Source: https://core.telegram.org/bots/api#getfile :param file_id: File identifier to get info about :type file_id: :obj:`base.String` :return: On success, a File object is returned :rtype: :obj:`types.File` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_FILE, payload) return types.File(**result)
python
async def get_file(self, file_id: base.String) -> types.File: payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_FILE, payload) return types.File(**result)
[ "async", "def", "get_file", "(", "self", ",", "file_id", ":", "base", ".", "String", ")", "->", "types", ".", "File", ":", "payload", "=", "generate_payload", "(", "*", "*", "locals", "(", ")", ")", "result", "=", "await", "self", ".", "request", "("...
Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. Source: https://core.telegram.org/bots/api#getfile :param file_id: File identifier to get info about :type file_id: :obj:`base.String` :return: On success, a File object is returned :rtype: :obj:`types.File`
[ "Use", "this", "method", "to", "get", "basic", "info", "about", "a", "file", "and", "prepare", "it", "for", "downloading", ".", "For", "the", "moment", "bots", "can", "download", "files", "of", "up", "to", "20MB", "in", "size", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L932-L950
238,576
aiogram/aiogram
aiogram/bot/bot.py
Bot.export_chat_invite_link
async def export_chat_invite_link(self, chat_id: typing.Union[base.Integer, base.String]) -> base.String: """ Use this method to generate a new invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Source: https://core.telegram.org/bots/api#exportchatinvitelink :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :return: Returns exported invite link as String on success :rtype: :obj:`base.String` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.EXPORT_CHAT_INVITE_LINK, payload) return result
python
async def export_chat_invite_link(self, chat_id: typing.Union[base.Integer, base.String]) -> base.String: payload = generate_payload(**locals()) result = await self.request(api.Methods.EXPORT_CHAT_INVITE_LINK, payload) return result
[ "async", "def", "export_chat_invite_link", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ")", "->", "base", ".", "String", ":", "payload", "=", "generate_payload", "(", "*", "*", ...
Use this method to generate a new invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Source: https://core.telegram.org/bots/api#exportchatinvitelink :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :return: Returns exported invite link as String on success :rtype: :obj:`base.String`
[ "Use", "this", "method", "to", "generate", "a", "new", "invite", "link", "for", "a", "chat", ";", "any", "previously", "generated", "link", "is", "revoked", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "chat", "for", "this", "to",...
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1091-L1106
238,577
aiogram/aiogram
aiogram/bot/bot.py
Bot.set_chat_photo
async def set_chat_photo(self, chat_id: typing.Union[base.Integer, base.String], photo: base.InputFile) -> base.Boolean: """ Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group. Source: https://core.telegram.org/bots/api#setchatphoto :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param photo: New chat photo, uploaded using multipart/form-data :type photo: :obj:`base.InputFile` :return: Returns True on success :rtype: :obj:`base.Boolean` """ payload = generate_payload(**locals(), exclude=['photo']) files = {} prepare_file(payload, files, 'photo', photo) result = await self.request(api.Methods.SET_CHAT_PHOTO, payload, files) return result
python
async def set_chat_photo(self, chat_id: typing.Union[base.Integer, base.String], photo: base.InputFile) -> base.Boolean: payload = generate_payload(**locals(), exclude=['photo']) files = {} prepare_file(payload, files, 'photo', photo) result = await self.request(api.Methods.SET_CHAT_PHOTO, payload, files) return result
[ "async", "def", "set_chat_photo", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ",", "photo", ":", "base", ".", "InputFile", ")", "->", "base", ".", "Boolean", ":", "payload", ...
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group. Source: https://core.telegram.org/bots/api#setchatphoto :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param photo: New chat photo, uploaded using multipart/form-data :type photo: :obj:`base.InputFile` :return: Returns True on success :rtype: :obj:`base.Boolean`
[ "Use", "this", "method", "to", "set", "a", "new", "profile", "photo", "for", "the", "chat", ".", "Photos", "can", "t", "be", "changed", "for", "private", "chats", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "chat", "for", "this...
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1108-L1132
238,578
aiogram/aiogram
aiogram/bot/bot.py
Bot.set_chat_description
async def set_chat_description(self, chat_id: typing.Union[base.Integer, base.String], description: typing.Union[base.String, None] = None) -> base.Boolean: """ Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Source: https://core.telegram.org/bots/api#setchatdescription :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param description: New chat description, 0-255 characters :type description: :obj:`typing.Union[base.String, None]` :return: Returns True on success :rtype: :obj:`base.Boolean` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.SET_CHAT_DESCRIPTION, payload) return result
python
async def set_chat_description(self, chat_id: typing.Union[base.Integer, base.String], description: typing.Union[base.String, None] = None) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.SET_CHAT_DESCRIPTION, payload) return result
[ "async", "def", "set_chat_description", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ",", "description", ":", "typing", ".", "Union", "[", "base", ".", "String", ",", "None", "]...
Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Source: https://core.telegram.org/bots/api#setchatdescription :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param description: New chat description, 0-255 characters :type description: :obj:`typing.Union[base.String, None]` :return: Returns True on success :rtype: :obj:`base.Boolean`
[ "Use", "this", "method", "to", "change", "the", "description", "of", "a", "supergroup", "or", "a", "channel", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "chat", "for", "this", "to", "work", "and", "must", "have", "the", "appropr...
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1177-L1195
238,579
aiogram/aiogram
aiogram/bot/bot.py
Bot.unpin_chat_message
async def unpin_chat_message(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean: """ Use this method to unpin a message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Source: https://core.telegram.org/bots/api#unpinchatmessage :param chat_id: Unique identifier for the target chat or username of the target supergroup :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :return: Returns True on success :rtype: :obj:`base.Boolean` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.UNPIN_CHAT_MESSAGE, payload) return result
python
async def unpin_chat_message(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.UNPIN_CHAT_MESSAGE, payload) return result
[ "async", "def", "unpin_chat_message", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ")", "->", "base", ".", "Boolean", ":", "payload", "=", "generate_payload", "(", "*", "*", "lo...
Use this method to unpin a message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Source: https://core.telegram.org/bots/api#unpinchatmessage :param chat_id: Unique identifier for the target chat or username of the target supergroup :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :return: Returns True on success :rtype: :obj:`base.Boolean`
[ "Use", "this", "method", "to", "unpin", "a", "message", "in", "a", "supergroup", "chat", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "chat", "for", "this", "to", "work", "and", "must", "have", "the", "appropriate", "admin", "righ...
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1220-L1235
238,580
aiogram/aiogram
aiogram/bot/bot.py
Bot.get_chat_administrators
async def get_chat_administrators(self, chat_id: typing.Union[base.Integer, base.String] ) -> typing.List[types.ChatMember]: """ Use this method to get a list of administrators in a chat. Source: https://core.telegram.org/bots/api#getchatadministrators :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :return: On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. :rtype: :obj:`typing.List[types.ChatMember]` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_CHAT_ADMINISTRATORS, payload) return [types.ChatMember(**chatmember) for chatmember in result]
python
async def get_chat_administrators(self, chat_id: typing.Union[base.Integer, base.String] ) -> typing.List[types.ChatMember]: payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_CHAT_ADMINISTRATORS, payload) return [types.ChatMember(**chatmember) for chatmember in result]
[ "async", "def", "get_chat_administrators", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ")", "->", "typing", ".", "List", "[", "types", ".", "ChatMember", "]", ":", "payload", "...
Use this method to get a list of administrators in a chat. Source: https://core.telegram.org/bots/api#getchatadministrators :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :return: On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. :rtype: :obj:`typing.List[types.ChatMember]`
[ "Use", "this", "method", "to", "get", "a", "list", "of", "administrators", "in", "a", "chat", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1270-L1288
238,581
aiogram/aiogram
aiogram/bot/bot.py
Bot.get_chat_member
async def get_chat_member(self, chat_id: typing.Union[base.Integer, base.String], user_id: base.Integer) -> types.ChatMember: """ Use this method to get information about a member of a chat. Source: https://core.telegram.org/bots/api#getchatmember :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param user_id: Unique identifier of the target user :type user_id: :obj:`base.Integer` :return: Returns a ChatMember object on success :rtype: :obj:`types.ChatMember` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_CHAT_MEMBER, payload) return types.ChatMember(**result)
python
async def get_chat_member(self, chat_id: typing.Union[base.Integer, base.String], user_id: base.Integer) -> types.ChatMember: payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_CHAT_MEMBER, payload) return types.ChatMember(**result)
[ "async", "def", "get_chat_member", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ",", "user_id", ":", "base", ".", "Integer", ")", "->", "types", ".", "ChatMember", ":", "payload...
Use this method to get information about a member of a chat. Source: https://core.telegram.org/bots/api#getchatmember :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param user_id: Unique identifier of the target user :type user_id: :obj:`base.Integer` :return: Returns a ChatMember object on success :rtype: :obj:`types.ChatMember`
[ "Use", "this", "method", "to", "get", "information", "about", "a", "member", "of", "a", "chat", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1306-L1323
238,582
aiogram/aiogram
aiogram/bot/bot.py
Bot.set_chat_sticker_set
async def set_chat_sticker_set(self, chat_id: typing.Union[base.Integer, base.String], sticker_set_name: base.String) -> base.Boolean: """ Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Source: https://core.telegram.org/bots/api#setchatstickerset :param chat_id: Unique identifier for the target chat or username of the target supergroup :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param sticker_set_name: Name of the sticker set to be set as the group sticker set :type sticker_set_name: :obj:`base.String` :return: Returns True on success :rtype: :obj:`base.Boolean` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.SET_CHAT_STICKER_SET, payload) return result
python
async def set_chat_sticker_set(self, chat_id: typing.Union[base.Integer, base.String], sticker_set_name: base.String) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.SET_CHAT_STICKER_SET, payload) return result
[ "async", "def", "set_chat_sticker_set", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ",", "sticker_set_name", ":", "base", ".", "String", ")", "->", "base", ".", "Boolean", ":", ...
Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Source: https://core.telegram.org/bots/api#setchatstickerset :param chat_id: Unique identifier for the target chat or username of the target supergroup :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param sticker_set_name: Name of the sticker set to be set as the group sticker set :type sticker_set_name: :obj:`base.String` :return: Returns True on success :rtype: :obj:`base.Boolean`
[ "Use", "this", "method", "to", "set", "a", "new", "group", "sticker", "set", "for", "a", "supergroup", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "chat", "for", "this", "to", "work", "and", "must", "have", "the", "appropriate", ...
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1325-L1346
238,583
aiogram/aiogram
aiogram/bot/bot.py
Bot.delete_chat_sticker_set
async def delete_chat_sticker_set(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean: """ Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Source: https://core.telegram.org/bots/api#deletechatstickerset :param chat_id: Unique identifier for the target chat or username of the target supergroup :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :return: Returns True on success :rtype: :obj:`base.Boolean` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.DELETE_CHAT_STICKER_SET, payload) return result
python
async def delete_chat_sticker_set(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.DELETE_CHAT_STICKER_SET, payload) return result
[ "async", "def", "delete_chat_sticker_set", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ")", "->", "base", ".", "Boolean", ":", "payload", "=", "generate_payload", "(", "*", "*", ...
Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Source: https://core.telegram.org/bots/api#deletechatstickerset :param chat_id: Unique identifier for the target chat or username of the target supergroup :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :return: Returns True on success :rtype: :obj:`base.Boolean`
[ "Use", "this", "method", "to", "delete", "a", "group", "sticker", "set", "from", "a", "supergroup", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "chat", "for", "this", "to", "work", "and", "must", "have", "the", "appropriate", "ad...
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1348-L1366
238,584
aiogram/aiogram
aiogram/bot/bot.py
Bot.stop_poll
async def stop_poll(self, chat_id: typing.Union[base.String, base.Integer], message_id: base.Integer, reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Poll: """ Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.String, base.Integer]` :param message_id: Identifier of the original message with the poll :type message_id: :obj:`base.Integer` :param reply_markup: A JSON-serialized object for a new message inline keyboard. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]` :return: On success, the stopped Poll with the final results is returned. :rtype: :obj:`types.Poll` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.STOP_POLL, payload) return types.Poll(**result)
python
async def stop_poll(self, chat_id: typing.Union[base.String, base.Integer], message_id: base.Integer, reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Poll: payload = generate_payload(**locals()) result = await self.request(api.Methods.STOP_POLL, payload) return types.Poll(**result)
[ "async", "def", "stop_poll", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "String", ",", "base", ".", "Integer", "]", ",", "message_id", ":", "base", ".", "Integer", ",", "reply_markup", ":", "typing", ".", "Union", "[", ...
Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.String, base.Integer]` :param message_id: Identifier of the original message with the poll :type message_id: :obj:`base.Integer` :param reply_markup: A JSON-serialized object for a new message inline keyboard. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]` :return: On success, the stopped Poll with the final results is returned. :rtype: :obj:`types.Poll`
[ "Use", "this", "method", "to", "stop", "a", "poll", "which", "was", "sent", "by", "the", "bot", ".", "On", "success", "the", "stopped", "Poll", "with", "the", "final", "results", "is", "returned", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1564-L1583
238,585
aiogram/aiogram
aiogram/bot/bot.py
Bot.get_sticker_set
async def get_sticker_set(self, name: base.String) -> types.StickerSet: """ Use this method to get a sticker set. Source: https://core.telegram.org/bots/api#getstickerset :param name: Name of the sticker set :type name: :obj:`base.String` :return: On success, a StickerSet object is returned :rtype: :obj:`types.StickerSet` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_STICKER_SET, payload) return types.StickerSet(**result)
python
async def get_sticker_set(self, name: base.String) -> types.StickerSet: payload = generate_payload(**locals()) result = await self.request(api.Methods.GET_STICKER_SET, payload) return types.StickerSet(**result)
[ "async", "def", "get_sticker_set", "(", "self", ",", "name", ":", "base", ".", "String", ")", "->", "types", ".", "StickerSet", ":", "payload", "=", "generate_payload", "(", "*", "*", "locals", "(", ")", ")", "result", "=", "await", "self", ".", "reque...
Use this method to get a sticker set. Source: https://core.telegram.org/bots/api#getstickerset :param name: Name of the sticker set :type name: :obj:`base.String` :return: On success, a StickerSet object is returned :rtype: :obj:`types.StickerSet`
[ "Use", "this", "method", "to", "get", "a", "sticker", "set", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1649-L1663
238,586
aiogram/aiogram
aiogram/bot/bot.py
Bot.create_new_sticker_set
async def create_new_sticker_set(self, user_id: base.Integer, name: base.String, title: base.String, png_sticker: typing.Union[base.InputFile, base.String], emojis: base.String, contains_masks: typing.Union[base.Boolean, None] = None, mask_position: typing.Union[types.MaskPosition, None] = None) -> base.Boolean: """ Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Source: https://core.telegram.org/bots/api#createnewstickerset :param user_id: User identifier of created sticker set owner :type user_id: :obj:`base.Integer` :param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals) :type name: :obj:`base.String` :param title: Sticker set title, 1-64 characters :type title: :obj:`base.String` :param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. :type png_sticker: :obj:`typing.Union[base.InputFile, base.String]` :param emojis: One or more emoji corresponding to the sticker :type emojis: :obj:`base.String` :param contains_masks: Pass True, if a set of mask stickers should be created :type contains_masks: :obj:`typing.Union[base.Boolean, None]` :param mask_position: A JSON-serialized object for position where the mask should be placed on faces :type mask_position: :obj:`typing.Union[types.MaskPosition, None]` :return: Returns True on success :rtype: :obj:`base.Boolean` """ mask_position = prepare_arg(mask_position) payload = generate_payload(**locals(), exclude=['png_sticker']) files = {} prepare_file(payload, files, 'png_sticker', png_sticker) result = await self.request(api.Methods.CREATE_NEW_STICKER_SET, payload, files) return result
python
async def create_new_sticker_set(self, user_id: base.Integer, name: base.String, title: base.String, png_sticker: typing.Union[base.InputFile, base.String], emojis: base.String, contains_masks: typing.Union[base.Boolean, None] = None, mask_position: typing.Union[types.MaskPosition, None] = None) -> base.Boolean: mask_position = prepare_arg(mask_position) payload = generate_payload(**locals(), exclude=['png_sticker']) files = {} prepare_file(payload, files, 'png_sticker', png_sticker) result = await self.request(api.Methods.CREATE_NEW_STICKER_SET, payload, files) return result
[ "async", "def", "create_new_sticker_set", "(", "self", ",", "user_id", ":", "base", ".", "Integer", ",", "name", ":", "base", ".", "String", ",", "title", ":", "base", ".", "String", ",", "png_sticker", ":", "typing", ".", "Union", "[", "base", ".", "I...
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Source: https://core.telegram.org/bots/api#createnewstickerset :param user_id: User identifier of created sticker set owner :type user_id: :obj:`base.Integer` :param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals) :type name: :obj:`base.String` :param title: Sticker set title, 1-64 characters :type title: :obj:`base.String` :param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. :type png_sticker: :obj:`typing.Union[base.InputFile, base.String]` :param emojis: One or more emoji corresponding to the sticker :type emojis: :obj:`base.String` :param contains_masks: Pass True, if a set of mask stickers should be created :type contains_masks: :obj:`typing.Union[base.Boolean, None]` :param mask_position: A JSON-serialized object for position where the mask should be placed on faces :type mask_position: :obj:`typing.Union[types.MaskPosition, None]` :return: Returns True on success :rtype: :obj:`base.Boolean`
[ "Use", "this", "method", "to", "create", "new", "sticker", "set", "owned", "by", "a", "user", ".", "The", "bot", "will", "be", "able", "to", "edit", "the", "created", "sticker", "set", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1688-L1722
238,587
aiogram/aiogram
aiogram/bot/bot.py
Bot.set_sticker_position_in_set
async def set_sticker_position_in_set(self, sticker: base.String, position: base.Integer) -> base.Boolean: """ Use this method to move a sticker in a set created by the bot to a specific position. Source: https://core.telegram.org/bots/api#setstickerpositioninset :param sticker: File identifier of the sticker :type sticker: :obj:`base.String` :param position: New sticker position in the set, zero-based :type position: :obj:`base.Integer` :return: Returns True on success :rtype: :obj:`base.Boolean` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.SET_STICKER_POSITION_IN_SET, payload) return result
python
async def set_sticker_position_in_set(self, sticker: base.String, position: base.Integer) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.SET_STICKER_POSITION_IN_SET, payload) return result
[ "async", "def", "set_sticker_position_in_set", "(", "self", ",", "sticker", ":", "base", ".", "String", ",", "position", ":", "base", ".", "Integer", ")", "->", "base", ".", "Boolean", ":", "payload", "=", "generate_payload", "(", "*", "*", "locals", "(", ...
Use this method to move a sticker in a set created by the bot to a specific position. Source: https://core.telegram.org/bots/api#setstickerpositioninset :param sticker: File identifier of the sticker :type sticker: :obj:`base.String` :param position: New sticker position in the set, zero-based :type position: :obj:`base.Integer` :return: Returns True on success :rtype: :obj:`base.Boolean`
[ "Use", "this", "method", "to", "move", "a", "sticker", "in", "a", "set", "created", "by", "the", "bot", "to", "a", "specific", "position", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1755-L1771
238,588
aiogram/aiogram
aiogram/bot/bot.py
Bot.delete_sticker_from_set
async def delete_sticker_from_set(self, sticker: base.String) -> base.Boolean: """ Use this method to delete a sticker from a set created by the bot. The following methods and objects allow your bot to work in inline mode. Source: https://core.telegram.org/bots/api#deletestickerfromset :param sticker: File identifier of the sticker :type sticker: :obj:`base.String` :return: Returns True on success :rtype: :obj:`base.Boolean` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.DELETE_STICKER_FROM_SET, payload) return result
python
async def delete_sticker_from_set(self, sticker: base.String) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.DELETE_STICKER_FROM_SET, payload) return result
[ "async", "def", "delete_sticker_from_set", "(", "self", ",", "sticker", ":", "base", ".", "String", ")", "->", "base", ".", "Boolean", ":", "payload", "=", "generate_payload", "(", "*", "*", "locals", "(", ")", ")", "result", "=", "await", "self", ".", ...
Use this method to delete a sticker from a set created by the bot. The following methods and objects allow your bot to work in inline mode. Source: https://core.telegram.org/bots/api#deletestickerfromset :param sticker: File identifier of the sticker :type sticker: :obj:`base.String` :return: Returns True on success :rtype: :obj:`base.Boolean`
[ "Use", "this", "method", "to", "delete", "a", "sticker", "from", "a", "set", "created", "by", "the", "bot", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1773-L1789
238,589
aiogram/aiogram
aiogram/bot/bot.py
Bot.send_invoice
async def send_invoice(self, chat_id: base.Integer, title: base.String, description: base.String, payload: base.String, provider_token: base.String, start_parameter: base.String, currency: base.String, prices: typing.List[types.LabeledPrice], provider_data: typing.Union[typing.Dict, None] = None, photo_url: typing.Union[base.String, None] = None, photo_size: typing.Union[base.Integer, None] = None, photo_width: typing.Union[base.Integer, None] = None, photo_height: typing.Union[base.Integer, None] = None, need_name: typing.Union[base.Boolean, None] = None, need_phone_number: typing.Union[base.Boolean, None] = None, need_email: typing.Union[base.Boolean, None] = None, need_shipping_address: typing.Union[base.Boolean, None] = None, is_flexible: typing.Union[base.Boolean, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, reply_to_message_id: typing.Union[base.Integer, None] = None, reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Message: """ Use this method to send invoices. Source: https://core.telegram.org/bots/api#sendinvoice :param chat_id: Unique identifier for the target private chat :type chat_id: :obj:`base.Integer` :param title: Product name, 1-32 characters :type title: :obj:`base.String` :param description: Product description, 1-255 characters :type description: :obj:`base.String` :param payload: Bot-defined invoice payload, 1-128 bytes This will not be displayed to the user, use for your internal processes. :type payload: :obj:`base.String` :param provider_token: Payments provider token, obtained via Botfather :type provider_token: :obj:`base.String` :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter :type start_parameter: :obj:`base.String` :param currency: Three-letter ISO 4217 currency code, see more on currencies :type currency: :obj:`base.String` :param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) :type prices: :obj:`typing.List[types.LabeledPrice]` :param provider_data: JSON-encoded data about the invoice, which will be shared with the payment provider :type provider_data: :obj:`typing.Union[typing.Dict, None]` :param photo_url: URL of the product photo for the invoice :type photo_url: :obj:`typing.Union[base.String, None]` :param photo_size: Photo size :type photo_size: :obj:`typing.Union[base.Integer, None]` :param photo_width: Photo width :type photo_width: :obj:`typing.Union[base.Integer, None]` :param photo_height: Photo height :type photo_height: :obj:`typing.Union[base.Integer, None]` :param need_name: Pass True, if you require the user's full name to complete the order :type need_name: :obj:`typing.Union[base.Boolean, None]` :param need_phone_number: Pass True, if you require the user's phone number to complete the order :type need_phone_number: :obj:`typing.Union[base.Boolean, None]` :param need_email: Pass True, if you require the user's email to complete the order :type need_email: :obj:`typing.Union[base.Boolean, None]` :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order :type need_shipping_address: :obj:`typing.Union[base.Boolean, None]` :param is_flexible: Pass True, if the final price depends on the shipping method :type is_flexible: :obj:`typing.Union[base.Boolean, None]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound :type disable_notification: :obj:`typing.Union[base.Boolean, None]` :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: :obj:`typing.Union[base.Integer, None]` :param reply_markup: A JSON-serialized object for an inline keyboard If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]` :return: On success, the sent Message is returned :rtype: :obj:`types.Message` """ prices = prepare_arg([price.to_python() if hasattr(price, 'to_python') else price for price in prices]) reply_markup = prepare_arg(reply_markup) payload_ = generate_payload(**locals()) result = await self.request(api.Methods.SEND_INVOICE, payload_) return types.Message(**result)
python
async def send_invoice(self, chat_id: base.Integer, title: base.String, description: base.String, payload: base.String, provider_token: base.String, start_parameter: base.String, currency: base.String, prices: typing.List[types.LabeledPrice], provider_data: typing.Union[typing.Dict, None] = None, photo_url: typing.Union[base.String, None] = None, photo_size: typing.Union[base.Integer, None] = None, photo_width: typing.Union[base.Integer, None] = None, photo_height: typing.Union[base.Integer, None] = None, need_name: typing.Union[base.Boolean, None] = None, need_phone_number: typing.Union[base.Boolean, None] = None, need_email: typing.Union[base.Boolean, None] = None, need_shipping_address: typing.Union[base.Boolean, None] = None, is_flexible: typing.Union[base.Boolean, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, reply_to_message_id: typing.Union[base.Integer, None] = None, reply_markup: typing.Union[types.InlineKeyboardMarkup, None] = None) -> types.Message: prices = prepare_arg([price.to_python() if hasattr(price, 'to_python') else price for price in prices]) reply_markup = prepare_arg(reply_markup) payload_ = generate_payload(**locals()) result = await self.request(api.Methods.SEND_INVOICE, payload_) return types.Message(**result)
[ "async", "def", "send_invoice", "(", "self", ",", "chat_id", ":", "base", ".", "Integer", ",", "title", ":", "base", ".", "String", ",", "description", ":", "base", ".", "String", ",", "payload", ":", "base", ".", "String", ",", "provider_token", ":", ...
Use this method to send invoices. Source: https://core.telegram.org/bots/api#sendinvoice :param chat_id: Unique identifier for the target private chat :type chat_id: :obj:`base.Integer` :param title: Product name, 1-32 characters :type title: :obj:`base.String` :param description: Product description, 1-255 characters :type description: :obj:`base.String` :param payload: Bot-defined invoice payload, 1-128 bytes This will not be displayed to the user, use for your internal processes. :type payload: :obj:`base.String` :param provider_token: Payments provider token, obtained via Botfather :type provider_token: :obj:`base.String` :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter :type start_parameter: :obj:`base.String` :param currency: Three-letter ISO 4217 currency code, see more on currencies :type currency: :obj:`base.String` :param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) :type prices: :obj:`typing.List[types.LabeledPrice]` :param provider_data: JSON-encoded data about the invoice, which will be shared with the payment provider :type provider_data: :obj:`typing.Union[typing.Dict, None]` :param photo_url: URL of the product photo for the invoice :type photo_url: :obj:`typing.Union[base.String, None]` :param photo_size: Photo size :type photo_size: :obj:`typing.Union[base.Integer, None]` :param photo_width: Photo width :type photo_width: :obj:`typing.Union[base.Integer, None]` :param photo_height: Photo height :type photo_height: :obj:`typing.Union[base.Integer, None]` :param need_name: Pass True, if you require the user's full name to complete the order :type need_name: :obj:`typing.Union[base.Boolean, None]` :param need_phone_number: Pass True, if you require the user's phone number to complete the order :type need_phone_number: :obj:`typing.Union[base.Boolean, None]` :param need_email: Pass True, if you require the user's email to complete the order :type need_email: :obj:`typing.Union[base.Boolean, None]` :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order :type need_shipping_address: :obj:`typing.Union[base.Boolean, None]` :param is_flexible: Pass True, if the final price depends on the shipping method :type is_flexible: :obj:`typing.Union[base.Boolean, None]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound :type disable_notification: :obj:`typing.Union[base.Boolean, None]` :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: :obj:`typing.Union[base.Integer, None]` :param reply_markup: A JSON-serialized object for an inline keyboard If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, None]` :return: On success, the sent Message is returned :rtype: :obj:`types.Message`
[ "Use", "this", "method", "to", "send", "invoices", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1838-L1914
238,590
aiogram/aiogram
aiogram/bot/bot.py
Bot.answer_shipping_query
async def answer_shipping_query(self, shipping_query_id: base.String, ok: base.Boolean, shipping_options: typing.Union[typing.List[types.ShippingOption], None] = None, error_message: typing.Union[base.String, None] = None) -> base.Boolean: """ If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Source: https://core.telegram.org/bots/api#answershippingquery :param shipping_query_id: Unique identifier for the query to be answered :type shipping_query_id: :obj:`base.String` :param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) :type ok: :obj:`base.Boolean` :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options :type shipping_options: :obj:`typing.Union[typing.List[types.ShippingOption], None]` :param error_message: Required if ok is False Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. :type error_message: :obj:`typing.Union[base.String, None]` :return: On success, True is returned :rtype: :obj:`base.Boolean` """ if shipping_options: shipping_options = prepare_arg([shipping_option.to_python() if hasattr(shipping_option, 'to_python') else shipping_option for shipping_option in shipping_options]) payload = generate_payload(**locals()) result = await self.request(api.Methods.ANSWER_SHIPPING_QUERY, payload) return result
python
async def answer_shipping_query(self, shipping_query_id: base.String, ok: base.Boolean, shipping_options: typing.Union[typing.List[types.ShippingOption], None] = None, error_message: typing.Union[base.String, None] = None) -> base.Boolean: if shipping_options: shipping_options = prepare_arg([shipping_option.to_python() if hasattr(shipping_option, 'to_python') else shipping_option for shipping_option in shipping_options]) payload = generate_payload(**locals()) result = await self.request(api.Methods.ANSWER_SHIPPING_QUERY, payload) return result
[ "async", "def", "answer_shipping_query", "(", "self", ",", "shipping_query_id", ":", "base", ".", "String", ",", "ok", ":", "base", ".", "Boolean", ",", "shipping_options", ":", "typing", ".", "Union", "[", "typing", ".", "List", "[", "types", ".", "Shippi...
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Source: https://core.telegram.org/bots/api#answershippingquery :param shipping_query_id: Unique identifier for the query to be answered :type shipping_query_id: :obj:`base.String` :param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) :type ok: :obj:`base.Boolean` :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options :type shipping_options: :obj:`typing.Union[typing.List[types.ShippingOption], None]` :param error_message: Required if ok is False Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. :type error_message: :obj:`typing.Union[base.String, None]` :return: On success, True is returned :rtype: :obj:`base.Boolean`
[ "If", "you", "sent", "an", "invoice", "requesting", "a", "shipping", "address", "and", "the", "parameter", "is_flexible", "was", "specified", "the", "Bot", "API", "will", "send", "an", "Update", "with", "a", "shipping_query", "field", "to", "the", "bot", "."...
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1916-L1948
238,591
aiogram/aiogram
aiogram/bot/bot.py
Bot.answer_pre_checkout_query
async def answer_pre_checkout_query(self, pre_checkout_query_id: base.String, ok: base.Boolean, error_message: typing.Union[base.String, None] = None) -> base.Boolean: """ Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. Source: https://core.telegram.org/bots/api#answerprecheckoutquery :param pre_checkout_query_id: Unique identifier for the query to be answered :type pre_checkout_query_id: :obj:`base.String` :param ok: Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. :type ok: :obj:`base.Boolean` :param error_message: Required if ok is False Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. :type error_message: :obj:`typing.Union[base.String, None]` :return: On success, True is returned :rtype: :obj:`base.Boolean` """ payload = generate_payload(**locals()) result = await self.request(api.Methods.ANSWER_PRE_CHECKOUT_QUERY, payload) return result
python
async def answer_pre_checkout_query(self, pre_checkout_query_id: base.String, ok: base.Boolean, error_message: typing.Union[base.String, None] = None) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.ANSWER_PRE_CHECKOUT_QUERY, payload) return result
[ "async", "def", "answer_pre_checkout_query", "(", "self", ",", "pre_checkout_query_id", ":", "base", ".", "String", ",", "ok", ":", "base", ".", "Boolean", ",", "error_message", ":", "typing", ".", "Union", "[", "base", ".", "String", ",", "None", "]", "="...
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. Source: https://core.telegram.org/bots/api#answerprecheckoutquery :param pre_checkout_query_id: Unique identifier for the query to be answered :type pre_checkout_query_id: :obj:`base.String` :param ok: Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. :type ok: :obj:`base.Boolean` :param error_message: Required if ok is False Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. :type error_message: :obj:`typing.Union[base.String, None]` :return: On success, True is returned :rtype: :obj:`base.Boolean`
[ "Once", "the", "user", "has", "confirmed", "their", "payment", "and", "shipping", "details", "the", "Bot", "API", "sends", "the", "final", "confirmation", "in", "the", "form", "of", "an", "Update", "with", "the", "field", "pre_checkout_query", ".", "Use", "t...
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L1950-L1976
238,592
aiogram/aiogram
examples/callback_data_factory.py
get_keyboard
def get_keyboard() -> types.InlineKeyboardMarkup: """ Generate keyboard with list of posts """ markup = types.InlineKeyboardMarkup() for post_id, post in POSTS.items(): markup.add( types.InlineKeyboardButton( post['title'], callback_data=posts_cb.new(id=post_id, action='view')) ) return markup
python
def get_keyboard() -> types.InlineKeyboardMarkup: markup = types.InlineKeyboardMarkup() for post_id, post in POSTS.items(): markup.add( types.InlineKeyboardButton( post['title'], callback_data=posts_cb.new(id=post_id, action='view')) ) return markup
[ "def", "get_keyboard", "(", ")", "->", "types", ".", "InlineKeyboardMarkup", ":", "markup", "=", "types", ".", "InlineKeyboardMarkup", "(", ")", "for", "post_id", ",", "post", "in", "POSTS", ".", "items", "(", ")", ":", "markup", ".", "add", "(", "types"...
Generate keyboard with list of posts
[ "Generate", "keyboard", "with", "list", "of", "posts" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/callback_data_factory.py#L36-L47
238,593
aiogram/aiogram
aiogram/contrib/middlewares/i18n.py
I18nMiddleware.find_locales
def find_locales(self) -> Dict[str, gettext.GNUTranslations]: """ Load all compiled locales from path :return: dict with locales """ translations = {} for name in os.listdir(self.path): if not os.path.isdir(os.path.join(self.path, name)): continue mo_path = os.path.join(self.path, name, 'LC_MESSAGES', self.domain + '.mo') if os.path.exists(mo_path): with open(mo_path, 'rb') as fp: translations[name] = gettext.GNUTranslations(fp) elif os.path.exists(mo_path[:-2] + 'po'): raise RuntimeError(f"Found locale '{name} but this language is not compiled!") return translations
python
def find_locales(self) -> Dict[str, gettext.GNUTranslations]: translations = {} for name in os.listdir(self.path): if not os.path.isdir(os.path.join(self.path, name)): continue mo_path = os.path.join(self.path, name, 'LC_MESSAGES', self.domain + '.mo') if os.path.exists(mo_path): with open(mo_path, 'rb') as fp: translations[name] = gettext.GNUTranslations(fp) elif os.path.exists(mo_path[:-2] + 'po'): raise RuntimeError(f"Found locale '{name} but this language is not compiled!") return translations
[ "def", "find_locales", "(", "self", ")", "->", "Dict", "[", "str", ",", "gettext", ".", "GNUTranslations", "]", ":", "translations", "=", "{", "}", "for", "name", "in", "os", ".", "listdir", "(", "self", ".", "path", ")", ":", "if", "not", "os", "....
Load all compiled locales from path :return: dict with locales
[ "Load", "all", "compiled", "locales", "from", "path" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/i18n.py#L45-L64
238,594
aiogram/aiogram
aiogram/contrib/middlewares/i18n.py
I18nMiddleware.lazy_gettext
def lazy_gettext(self, singular, plural=None, n=1, locale=None) -> LazyProxy: """ Lazy get text :param singular: :param plural: :param n: :param locale: :return: """ return LazyProxy(self.gettext, singular, plural, n, locale)
python
def lazy_gettext(self, singular, plural=None, n=1, locale=None) -> LazyProxy: return LazyProxy(self.gettext, singular, plural, n, locale)
[ "def", "lazy_gettext", "(", "self", ",", "singular", ",", "plural", "=", "None", ",", "n", "=", "1", ",", "locale", "=", "None", ")", "->", "LazyProxy", ":", "return", "LazyProxy", "(", "self", ".", "gettext", ",", "singular", ",", "plural", ",", "n"...
Lazy get text :param singular: :param plural: :param n: :param locale: :return:
[ "Lazy", "get", "text" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/i18n.py#L110-L120
238,595
aiogram/aiogram
aiogram/utils/executor.py
Executor.on_startup
def on_startup(self, callback: callable, polling=True, webhook=True): """ Register a callback for the startup process :param callback: :param polling: use with polling :param webhook: use with webhook """ self._check_frozen() if not webhook and not polling: warn('This action has no effect!', UserWarning) return if isinstance(callback, (list, tuple, set)): for cb in callback: self.on_startup(cb, polling, webhook) return if polling: self._on_startup_polling.append(callback) if webhook: self._on_startup_webhook.append(callback)
python
def on_startup(self, callback: callable, polling=True, webhook=True): self._check_frozen() if not webhook and not polling: warn('This action has no effect!', UserWarning) return if isinstance(callback, (list, tuple, set)): for cb in callback: self.on_startup(cb, polling, webhook) return if polling: self._on_startup_polling.append(callback) if webhook: self._on_startup_webhook.append(callback)
[ "def", "on_startup", "(", "self", ",", "callback", ":", "callable", ",", "polling", "=", "True", ",", "webhook", "=", "True", ")", ":", "self", ".", "_check_frozen", "(", ")", "if", "not", "webhook", "and", "not", "polling", ":", "warn", "(", "'This ac...
Register a callback for the startup process :param callback: :param polling: use with polling :param webhook: use with webhook
[ "Register", "a", "callback", "for", "the", "startup", "process" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/executor.py#L166-L187
238,596
aiogram/aiogram
aiogram/utils/executor.py
Executor.on_shutdown
def on_shutdown(self, callback: callable, polling=True, webhook=True): """ Register a callback for the shutdown process :param callback: :param polling: use with polling :param webhook: use with webhook """ self._check_frozen() if not webhook and not polling: warn('This action has no effect!', UserWarning) return if isinstance(callback, (list, tuple, set)): for cb in callback: self.on_shutdown(cb, polling, webhook) return if polling: self._on_shutdown_polling.append(callback) if webhook: self._on_shutdown_webhook.append(callback)
python
def on_shutdown(self, callback: callable, polling=True, webhook=True): self._check_frozen() if not webhook and not polling: warn('This action has no effect!', UserWarning) return if isinstance(callback, (list, tuple, set)): for cb in callback: self.on_shutdown(cb, polling, webhook) return if polling: self._on_shutdown_polling.append(callback) if webhook: self._on_shutdown_webhook.append(callback)
[ "def", "on_shutdown", "(", "self", ",", "callback", ":", "callable", ",", "polling", "=", "True", ",", "webhook", "=", "True", ")", ":", "self", ".", "_check_frozen", "(", ")", "if", "not", "webhook", "and", "not", "polling", ":", "warn", "(", "'This a...
Register a callback for the shutdown process :param callback: :param polling: use with polling :param webhook: use with webhook
[ "Register", "a", "callback", "for", "the", "shutdown", "process" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/executor.py#L189-L210
238,597
aiogram/aiogram
setup.py
get_requirements
def get_requirements(filename=None): """ Read requirements from 'requirements txt' :return: requirements :rtype: list """ if filename is None: filename = 'requirements.txt' file = WORK_DIR / filename install_reqs = parse_requirements(str(file), session='hack') return [str(ir.req) for ir in install_reqs]
python
def get_requirements(filename=None): if filename is None: filename = 'requirements.txt' file = WORK_DIR / filename install_reqs = parse_requirements(str(file), session='hack') return [str(ir.req) for ir in install_reqs]
[ "def", "get_requirements", "(", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "'requirements.txt'", "file", "=", "WORK_DIR", "/", "filename", "install_reqs", "=", "parse_requirements", "(", "str", "(", "file", ")", ...
Read requirements from 'requirements txt' :return: requirements :rtype: list
[ "Read", "requirements", "from", "requirements", "txt" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/setup.py#L45-L58
238,598
aiogram/aiogram
aiogram/bot/base.py
BaseBot.request_timeout
def request_timeout(self, timeout): """ Context manager implements opportunity to change request timeout in current context :param timeout: :return: """ timeout = self._prepare_timeout(timeout) token = self._ctx_timeout.set(timeout) try: yield finally: self._ctx_timeout.reset(token)
python
def request_timeout(self, timeout): timeout = self._prepare_timeout(timeout) token = self._ctx_timeout.set(timeout) try: yield finally: self._ctx_timeout.reset(token)
[ "def", "request_timeout", "(", "self", ",", "timeout", ")", ":", "timeout", "=", "self", ".", "_prepare_timeout", "(", "timeout", ")", "token", "=", "self", ".", "_ctx_timeout", ".", "set", "(", "timeout", ")", "try", ":", "yield", "finally", ":", "self"...
Context manager implements opportunity to change request timeout in current context :param timeout: :return:
[ "Context", "manager", "implements", "opportunity", "to", "change", "request", "timeout", "in", "current", "context" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/base.py#L124-L136
238,599
aiogram/aiogram
aiogram/bot/base.py
BaseBot.request
async def request(self, method: base.String, data: Optional[Dict] = None, files: Optional[Dict] = None, **kwargs) -> Union[List, Dict, base.Boolean]: """ Make an request to Telegram Bot API https://core.telegram.org/bots/api#making-requests :param method: API method :type method: :obj:`str` :param data: request parameters :type data: :obj:`dict` :param files: files :type files: :obj:`dict` :return: result :rtype: Union[List, Dict] :raise: :obj:`aiogram.exceptions.TelegramApiError` """ return await api.make_request(self.session, self.__token, method, data, files, proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)
python
async def request(self, method: base.String, data: Optional[Dict] = None, files: Optional[Dict] = None, **kwargs) -> Union[List, Dict, base.Boolean]: return await api.make_request(self.session, self.__token, method, data, files, proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)
[ "async", "def", "request", "(", "self", ",", "method", ":", "base", ".", "String", ",", "data", ":", "Optional", "[", "Dict", "]", "=", "None", ",", "files", ":", "Optional", "[", "Dict", "]", "=", "None", ",", "*", "*", "kwargs", ")", "->", "Uni...
Make an request to Telegram Bot API https://core.telegram.org/bots/api#making-requests :param method: API method :type method: :obj:`str` :param data: request parameters :type data: :obj:`dict` :param files: files :type files: :obj:`dict` :return: result :rtype: Union[List, Dict] :raise: :obj:`aiogram.exceptions.TelegramApiError`
[ "Make", "an", "request", "to", "Telegram", "Bot", "API" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/base.py#L144-L163