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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
25,200 | pecan/pecan | pecan/templating.py | format_line_context | def format_line_context(filename, lineno, context=10):
'''
Formats the the line context for error rendering.
:param filename: the location of the file, within which the error occurred
:param lineno: the offending line number
:param context: number of lines of code to display before and after the
offending line.
'''
with open(filename) as f:
lines = f.readlines()
lineno = lineno - 1 # files are indexed by 1 not 0
if lineno > 0:
start_lineno = max(lineno - context, 0)
end_lineno = lineno + context
lines = [escape(l, True) for l in lines[start_lineno:end_lineno]]
i = lineno - start_lineno
lines[i] = '<strong>%s</strong>' % lines[i]
else:
lines = [escape(l, True) for l in lines[:context]]
msg = '<pre style="background-color:#ccc;padding:2em;">%s</pre>'
return msg % ''.join(lines) | python | def format_line_context(filename, lineno, context=10):
'''
Formats the the line context for error rendering.
:param filename: the location of the file, within which the error occurred
:param lineno: the offending line number
:param context: number of lines of code to display before and after the
offending line.
'''
with open(filename) as f:
lines = f.readlines()
lineno = lineno - 1 # files are indexed by 1 not 0
if lineno > 0:
start_lineno = max(lineno - context, 0)
end_lineno = lineno + context
lines = [escape(l, True) for l in lines[start_lineno:end_lineno]]
i = lineno - start_lineno
lines[i] = '<strong>%s</strong>' % lines[i]
else:
lines = [escape(l, True) for l in lines[:context]]
msg = '<pre style="background-color:#ccc;padding:2em;">%s</pre>'
return msg % ''.join(lines) | [
"def",
"format_line_context",
"(",
"filename",
",",
"lineno",
",",
"context",
"=",
"10",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"lineno",
"=",
"lineno",
"-",
"1",
"# files are inde... | Formats the the line context for error rendering.
:param filename: the location of the file, within which the error occurred
:param lineno: the offending line number
:param context: number of lines of code to display before and after the
offending line. | [
"Formats",
"the",
"the",
"line",
"context",
"for",
"error",
"rendering",
"."
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/templating.py#L183-L207 |
25,201 | pecan/pecan | pecan/templating.py | ExtraNamespace.make_ns | def make_ns(self, ns):
'''
Returns the `lazily` created template namespace.
'''
if self.namespace:
val = {}
val.update(self.namespace)
val.update(ns)
return val
else:
return ns | python | def make_ns(self, ns):
'''
Returns the `lazily` created template namespace.
'''
if self.namespace:
val = {}
val.update(self.namespace)
val.update(ns)
return val
else:
return ns | [
"def",
"make_ns",
"(",
"self",
",",
"ns",
")",
":",
"if",
"self",
".",
"namespace",
":",
"val",
"=",
"{",
"}",
"val",
".",
"update",
"(",
"self",
".",
"namespace",
")",
"val",
".",
"update",
"(",
"ns",
")",
"return",
"val",
"else",
":",
"return",... | Returns the `lazily` created template namespace. | [
"Returns",
"the",
"lazily",
"created",
"template",
"namespace",
"."
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/templating.py#L229-L239 |
25,202 | pecan/pecan | pecan/templating.py | RendererFactory.get | def get(self, name, template_path):
'''
Returns the renderer object.
:param name: name of the requested renderer
:param template_path: path to the template
'''
if name not in self._renderers:
cls = self._renderer_classes.get(name)
if cls is None:
return None
else:
self._renderers[name] = cls(template_path, self.extra_vars)
return self._renderers[name] | python | def get(self, name, template_path):
'''
Returns the renderer object.
:param name: name of the requested renderer
:param template_path: path to the template
'''
if name not in self._renderers:
cls = self._renderer_classes.get(name)
if cls is None:
return None
else:
self._renderers[name] = cls(template_path, self.extra_vars)
return self._renderers[name] | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"template_path",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_renderers",
":",
"cls",
"=",
"self",
".",
"_renderer_classes",
".",
"get",
"(",
"name",
")",
"if",
"cls",
"is",
"None",
":",
"return",
... | Returns the renderer object.
:param name: name of the requested renderer
:param template_path: path to the template | [
"Returns",
"the",
"renderer",
"object",
"."
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/templating.py#L274-L287 |
25,203 | pecan/pecan | pecan/jsonify.py | GenericJSON.default | def default(self, obj):
'''
Converts an object and returns a ``JSON``-friendly structure.
:param obj: object or structure to be converted into a
``JSON``-ifiable structure
Considers the following special cases in order:
* object has a callable __json__() attribute defined
returns the result of the call to __json__()
* date and datetime objects
returns the object cast to str
* Decimal objects
returns the object cast to float
* SQLAlchemy objects
returns a copy of the object.__dict__ with internal SQLAlchemy
parameters removed
* SQLAlchemy ResultProxy objects
Casts the iterable ResultProxy into a list of tuples containing
the entire resultset data, returns the list in a dictionary
along with the resultset "row" count.
.. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',),
('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]}
* SQLAlchemy RowProxy objects
Casts the RowProxy cursor object into a dictionary, probably
losing its ordered dictionary behavior in the process but
making it JSON-friendly.
* webob_dicts objects
returns webob_dicts.mixed() dictionary, which is guaranteed
to be JSON-friendly.
'''
if hasattr(obj, '__json__') and six.callable(obj.__json__):
return obj.__json__()
elif isinstance(obj, (date, datetime)):
return str(obj)
elif isinstance(obj, Decimal):
# XXX What to do about JSONEncoder crappy handling of Decimals?
# SimpleJSON has better Decimal encoding than the std lib
# but only in recent versions
return float(obj)
elif is_saobject(obj):
props = {}
for key in obj.__dict__:
if not key.startswith('_sa_'):
props[key] = getattr(obj, key)
return props
elif isinstance(obj, ResultProxy):
props = dict(rows=list(obj), count=obj.rowcount)
if props['count'] < 0:
props['count'] = len(props['rows'])
return props
elif isinstance(obj, RowProxy):
return dict(obj)
elif isinstance(obj, webob_dicts):
return obj.mixed()
else:
return JSONEncoder.default(self, obj) | python | def default(self, obj):
'''
Converts an object and returns a ``JSON``-friendly structure.
:param obj: object or structure to be converted into a
``JSON``-ifiable structure
Considers the following special cases in order:
* object has a callable __json__() attribute defined
returns the result of the call to __json__()
* date and datetime objects
returns the object cast to str
* Decimal objects
returns the object cast to float
* SQLAlchemy objects
returns a copy of the object.__dict__ with internal SQLAlchemy
parameters removed
* SQLAlchemy ResultProxy objects
Casts the iterable ResultProxy into a list of tuples containing
the entire resultset data, returns the list in a dictionary
along with the resultset "row" count.
.. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',),
('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]}
* SQLAlchemy RowProxy objects
Casts the RowProxy cursor object into a dictionary, probably
losing its ordered dictionary behavior in the process but
making it JSON-friendly.
* webob_dicts objects
returns webob_dicts.mixed() dictionary, which is guaranteed
to be JSON-friendly.
'''
if hasattr(obj, '__json__') and six.callable(obj.__json__):
return obj.__json__()
elif isinstance(obj, (date, datetime)):
return str(obj)
elif isinstance(obj, Decimal):
# XXX What to do about JSONEncoder crappy handling of Decimals?
# SimpleJSON has better Decimal encoding than the std lib
# but only in recent versions
return float(obj)
elif is_saobject(obj):
props = {}
for key in obj.__dict__:
if not key.startswith('_sa_'):
props[key] = getattr(obj, key)
return props
elif isinstance(obj, ResultProxy):
props = dict(rows=list(obj), count=obj.rowcount)
if props['count'] < 0:
props['count'] = len(props['rows'])
return props
elif isinstance(obj, RowProxy):
return dict(obj)
elif isinstance(obj, webob_dicts):
return obj.mixed()
else:
return JSONEncoder.default(self, obj) | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'__json__'",
")",
"and",
"six",
".",
"callable",
"(",
"obj",
".",
"__json__",
")",
":",
"return",
"obj",
".",
"__json__",
"(",
")",
"elif",
"isinstance",
"(",
"... | Converts an object and returns a ``JSON``-friendly structure.
:param obj: object or structure to be converted into a
``JSON``-ifiable structure
Considers the following special cases in order:
* object has a callable __json__() attribute defined
returns the result of the call to __json__()
* date and datetime objects
returns the object cast to str
* Decimal objects
returns the object cast to float
* SQLAlchemy objects
returns a copy of the object.__dict__ with internal SQLAlchemy
parameters removed
* SQLAlchemy ResultProxy objects
Casts the iterable ResultProxy into a list of tuples containing
the entire resultset data, returns the list in a dictionary
along with the resultset "row" count.
.. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',),
('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]}
* SQLAlchemy RowProxy objects
Casts the RowProxy cursor object into a dictionary, probably
losing its ordered dictionary behavior in the process but
making it JSON-friendly.
* webob_dicts objects
returns webob_dicts.mixed() dictionary, which is guaranteed
to be JSON-friendly. | [
"Converts",
"an",
"object",
"and",
"returns",
"a",
"JSON",
"-",
"friendly",
"structure",
"."
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/jsonify.py#L49-L108 |
25,204 | pecan/pecan | pecan/util.py | getargspec | def getargspec(method):
"""
Drill through layers of decorators attempting to locate the actual argspec
for a method.
"""
argspec = _getargspec(method)
args = argspec[0]
if args and args[0] == 'self':
return argspec
if hasattr(method, '__func__'):
method = method.__func__
func_closure = six.get_function_closure(method)
# NOTE(sileht): if the closure is None we cannot look deeper,
# so return actual argspec, this occurs when the method
# is static for example.
if not func_closure:
return argspec
closure = None
# In the case of deeply nested decorators (with arguments), it's possible
# that there are several callables in scope; Take a best guess and go
# with the one that looks most like a pecan controller function
# (has a __code__ object, and 'self' is the first argument)
func_closure = filter(
lambda c: (
six.callable(c.cell_contents) and
hasattr(c.cell_contents, '__code__')
),
func_closure
)
func_closure = sorted(
func_closure,
key=lambda c: 'self' in c.cell_contents.__code__.co_varnames,
reverse=True
)
closure = func_closure[0]
method = closure.cell_contents
return getargspec(method) | python | def getargspec(method):
argspec = _getargspec(method)
args = argspec[0]
if args and args[0] == 'self':
return argspec
if hasattr(method, '__func__'):
method = method.__func__
func_closure = six.get_function_closure(method)
# NOTE(sileht): if the closure is None we cannot look deeper,
# so return actual argspec, this occurs when the method
# is static for example.
if not func_closure:
return argspec
closure = None
# In the case of deeply nested decorators (with arguments), it's possible
# that there are several callables in scope; Take a best guess and go
# with the one that looks most like a pecan controller function
# (has a __code__ object, and 'self' is the first argument)
func_closure = filter(
lambda c: (
six.callable(c.cell_contents) and
hasattr(c.cell_contents, '__code__')
),
func_closure
)
func_closure = sorted(
func_closure,
key=lambda c: 'self' in c.cell_contents.__code__.co_varnames,
reverse=True
)
closure = func_closure[0]
method = closure.cell_contents
return getargspec(method) | [
"def",
"getargspec",
"(",
"method",
")",
":",
"argspec",
"=",
"_getargspec",
"(",
"method",
")",
"args",
"=",
"argspec",
"[",
"0",
"]",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"'self'",
":",
"return",
"argspec",
"if",
"hasattr",
"(",
"metho... | Drill through layers of decorators attempting to locate the actual argspec
for a method. | [
"Drill",
"through",
"layers",
"of",
"decorators",
"attempting",
"to",
"locate",
"the",
"actual",
"argspec",
"for",
"a",
"method",
"."
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/util.py#L12-L54 |
25,205 | pecan/pecan | pecan/commands/serve.py | gunicorn_run | def gunicorn_run():
"""
The ``gunicorn_pecan`` command for launching ``pecan`` applications
"""
try:
from gunicorn.app.wsgiapp import WSGIApplication
except ImportError as exc:
args = exc.args
arg0 = args[0] if args else ''
arg0 += ' (are you sure `gunicorn` is installed?)'
exc.args = (arg0,) + args[1:]
raise
class PecanApplication(WSGIApplication):
def init(self, parser, opts, args):
if len(args) != 1:
parser.error("No configuration file was specified.")
self.cfgfname = os.path.normpath(
os.path.join(os.getcwd(), args[0])
)
self.cfgfname = os.path.abspath(self.cfgfname)
if not os.path.exists(self.cfgfname):
parser.error("Config file not found: %s" % self.cfgfname)
from pecan.configuration import _runtime_conf, set_config
set_config(self.cfgfname, overwrite=True)
# If available, use the host and port from the pecan config file
cfg = {}
if _runtime_conf.get('server'):
server = _runtime_conf['server']
if hasattr(server, 'host') and hasattr(server, 'port'):
cfg['bind'] = '%s:%s' % (
server.host, server.port
)
return cfg
def load(self):
from pecan.deploy import deploy
return deploy(self.cfgfname)
PecanApplication("%(prog)s [OPTIONS] config.py").run() | python | def gunicorn_run():
try:
from gunicorn.app.wsgiapp import WSGIApplication
except ImportError as exc:
args = exc.args
arg0 = args[0] if args else ''
arg0 += ' (are you sure `gunicorn` is installed?)'
exc.args = (arg0,) + args[1:]
raise
class PecanApplication(WSGIApplication):
def init(self, parser, opts, args):
if len(args) != 1:
parser.error("No configuration file was specified.")
self.cfgfname = os.path.normpath(
os.path.join(os.getcwd(), args[0])
)
self.cfgfname = os.path.abspath(self.cfgfname)
if not os.path.exists(self.cfgfname):
parser.error("Config file not found: %s" % self.cfgfname)
from pecan.configuration import _runtime_conf, set_config
set_config(self.cfgfname, overwrite=True)
# If available, use the host and port from the pecan config file
cfg = {}
if _runtime_conf.get('server'):
server = _runtime_conf['server']
if hasattr(server, 'host') and hasattr(server, 'port'):
cfg['bind'] = '%s:%s' % (
server.host, server.port
)
return cfg
def load(self):
from pecan.deploy import deploy
return deploy(self.cfgfname)
PecanApplication("%(prog)s [OPTIONS] config.py").run() | [
"def",
"gunicorn_run",
"(",
")",
":",
"try",
":",
"from",
"gunicorn",
".",
"app",
".",
"wsgiapp",
"import",
"WSGIApplication",
"except",
"ImportError",
"as",
"exc",
":",
"args",
"=",
"exc",
".",
"args",
"arg0",
"=",
"args",
"[",
"0",
"]",
"if",
"args",... | The ``gunicorn_pecan`` command for launching ``pecan`` applications | [
"The",
"gunicorn_pecan",
"command",
"for",
"launching",
"pecan",
"applications"
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/serve.py#L155-L198 |
25,206 | pecan/pecan | pecan/commands/serve.py | ServeCommand.serve | def serve(self, app, conf):
"""
A very simple approach for a WSGI server.
"""
if self.args.reload:
try:
self.watch_and_spawn(conf)
except ImportError:
print('The `--reload` option requires `watchdog` to be '
'installed.')
print(' $ pip install watchdog')
else:
self._serve(app, conf) | python | def serve(self, app, conf):
if self.args.reload:
try:
self.watch_and_spawn(conf)
except ImportError:
print('The `--reload` option requires `watchdog` to be '
'installed.')
print(' $ pip install watchdog')
else:
self._serve(app, conf) | [
"def",
"serve",
"(",
"self",
",",
"app",
",",
"conf",
")",
":",
"if",
"self",
".",
"args",
".",
"reload",
":",
"try",
":",
"self",
".",
"watch_and_spawn",
"(",
"conf",
")",
"except",
"ImportError",
":",
"print",
"(",
"'The `--reload` option requires `watch... | A very simple approach for a WSGI server. | [
"A",
"very",
"simple",
"approach",
"for",
"a",
"WSGI",
"server",
"."
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/serve.py#L139-L152 |
25,207 | pecan/pecan | pecan/commands/serve.py | PecanWSGIRequestHandler.log_message | def log_message(self, format, *args):
"""
overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
warnings, 5XX as errors and everything else as INFO level.
"""
code = args[1][0]
levels = {
'4': 'warning',
'5': 'error'
}
log_handler = getattr(logger, levels.get(code, 'info'))
log_handler(format % args) | python | def log_message(self, format, *args):
code = args[1][0]
levels = {
'4': 'warning',
'5': 'error'
}
log_handler = getattr(logger, levels.get(code, 'info'))
log_handler(format % args) | [
"def",
"log_message",
"(",
"self",
",",
"format",
",",
"*",
"args",
")",
":",
"code",
"=",
"args",
"[",
"1",
"]",
"[",
"0",
"]",
"levels",
"=",
"{",
"'4'",
":",
"'warning'",
",",
"'5'",
":",
"'error'",
"}",
"log_handler",
"=",
"getattr",
"(",
"lo... | overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
warnings, 5XX as errors and everything else as INFO level. | [
"overrides",
"the",
"log_message",
"method",
"from",
"the",
"wsgiref",
"server",
"so",
"that",
"normal",
"logging",
"works",
"with",
"whatever",
"configuration",
"the",
"application",
"has",
"been",
"set",
"to",
"."
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/serve.py#L213-L229 |
25,208 | pecan/pecan | pecan/decorators.py | expose | def expose(template=None,
generic=False,
route=None,
**kw):
'''
Decorator used to flag controller methods as being "exposed" for
access via HTTP, and to configure that access.
:param template: The path to a template, relative to the base template
directory. Can also be passed a string representing
a special or custom renderer, such as ``'json'`` for
:ref:`expose_json`.
:param content_type: The content-type to use for this template.
:param generic: A boolean which flags this as a "generic" controller,
which uses generic functions based upon
``functools.singledispatch`` generic functions. Allows you
to split a single controller into multiple paths based upon
HTTP method.
:param route: The name of the path segment to match (excluding
separator characters, like `/`). Defaults to the name of
the function itself, but this can be used to resolve paths
which are not valid Python function names, e.g., if you
wanted to route a function to `some-special-path'.
'''
content_type = kw.get('content_type', 'text/html')
if template == 'json':
content_type = 'application/json'
def decorate(f):
# flag the method as exposed
f.exposed = True
cfg = _cfg(f)
cfg['explicit_content_type'] = 'content_type' in kw
if route:
# This import is here to avoid a circular import issue
from pecan import routing
if cfg.get('generic_handler'):
raise ValueError(
'Path segments cannot be overridden for generic '
'controllers.'
)
routing.route(route, f)
# set a "pecan" attribute, where we will store details
cfg['content_type'] = content_type
cfg.setdefault('template', []).append(template)
cfg.setdefault('content_types', {})[content_type] = template
# handle generic controllers
if generic:
if f.__name__ in ('_default', '_lookup', '_route'):
raise ValueError(
'The special method %s cannot be used as a generic '
'controller' % f.__name__
)
cfg['generic'] = True
cfg['generic_handlers'] = dict(DEFAULT=f)
cfg['allowed_methods'] = []
f.when = when_for(f)
# store the arguments for this controller method
cfg['argspec'] = getargspec(f)
return f
return decorate | python | def expose(template=None,
generic=False,
route=None,
**kw):
'''
Decorator used to flag controller methods as being "exposed" for
access via HTTP, and to configure that access.
:param template: The path to a template, relative to the base template
directory. Can also be passed a string representing
a special or custom renderer, such as ``'json'`` for
:ref:`expose_json`.
:param content_type: The content-type to use for this template.
:param generic: A boolean which flags this as a "generic" controller,
which uses generic functions based upon
``functools.singledispatch`` generic functions. Allows you
to split a single controller into multiple paths based upon
HTTP method.
:param route: The name of the path segment to match (excluding
separator characters, like `/`). Defaults to the name of
the function itself, but this can be used to resolve paths
which are not valid Python function names, e.g., if you
wanted to route a function to `some-special-path'.
'''
content_type = kw.get('content_type', 'text/html')
if template == 'json':
content_type = 'application/json'
def decorate(f):
# flag the method as exposed
f.exposed = True
cfg = _cfg(f)
cfg['explicit_content_type'] = 'content_type' in kw
if route:
# This import is here to avoid a circular import issue
from pecan import routing
if cfg.get('generic_handler'):
raise ValueError(
'Path segments cannot be overridden for generic '
'controllers.'
)
routing.route(route, f)
# set a "pecan" attribute, where we will store details
cfg['content_type'] = content_type
cfg.setdefault('template', []).append(template)
cfg.setdefault('content_types', {})[content_type] = template
# handle generic controllers
if generic:
if f.__name__ in ('_default', '_lookup', '_route'):
raise ValueError(
'The special method %s cannot be used as a generic '
'controller' % f.__name__
)
cfg['generic'] = True
cfg['generic_handlers'] = dict(DEFAULT=f)
cfg['allowed_methods'] = []
f.when = when_for(f)
# store the arguments for this controller method
cfg['argspec'] = getargspec(f)
return f
return decorate | [
"def",
"expose",
"(",
"template",
"=",
"None",
",",
"generic",
"=",
"False",
",",
"route",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"content_type",
"=",
"kw",
".",
"get",
"(",
"'content_type'",
",",
"'text/html'",
")",
"if",
"template",
"==",
"'js... | Decorator used to flag controller methods as being "exposed" for
access via HTTP, and to configure that access.
:param template: The path to a template, relative to the base template
directory. Can also be passed a string representing
a special or custom renderer, such as ``'json'`` for
:ref:`expose_json`.
:param content_type: The content-type to use for this template.
:param generic: A boolean which flags this as a "generic" controller,
which uses generic functions based upon
``functools.singledispatch`` generic functions. Allows you
to split a single controller into multiple paths based upon
HTTP method.
:param route: The name of the path segment to match (excluding
separator characters, like `/`). Defaults to the name of
the function itself, but this can be used to resolve paths
which are not valid Python function names, e.g., if you
wanted to route a function to `some-special-path'. | [
"Decorator",
"used",
"to",
"flag",
"controller",
"methods",
"as",
"being",
"exposed",
"for",
"access",
"via",
"HTTP",
"and",
"to",
"configure",
"that",
"access",
"."
] | 833d0653fa0e6bbfb52545b091c30182105f4a82 | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/decorators.py#L25-L95 |
25,209 | craft-ai/craft-ai-client-python | craftai/time.py | Time.to_dict | def to_dict(self):
"""Returns the Time instance as a usable dictionary for craftai"""
return {
"timestamp": int(self.timestamp),
"timezone": self.timezone,
"time_of_day": self.time_of_day,
"day_of_week": self.day_of_week,
"day_of_month": self.day_of_month,
"month_of_year": self.month_of_year,
"utc_iso": self.utc_iso
} | python | def to_dict(self):
return {
"timestamp": int(self.timestamp),
"timezone": self.timezone,
"time_of_day": self.time_of_day,
"day_of_week": self.day_of_week,
"day_of_month": self.day_of_month,
"month_of_year": self.month_of_year,
"utc_iso": self.utc_iso
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"\"timestamp\"",
":",
"int",
"(",
"self",
".",
"timestamp",
")",
",",
"\"timezone\"",
":",
"self",
".",
"timezone",
",",
"\"time_of_day\"",
":",
"self",
".",
"time_of_day",
",",
"\"day_of_week\"",
":"... | Returns the Time instance as a usable dictionary for craftai | [
"Returns",
"the",
"Time",
"instance",
"as",
"a",
"usable",
"dictionary",
"for",
"craftai"
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/time.py#L138-L148 |
25,210 | craft-ai/craft-ai-client-python | craftai/time.py | Time.timestamp_from_datetime | def timestamp_from_datetime(date_time):
"""Returns POSIX timestamp as float"""
if date_time.tzinfo is None:
return time.mktime((date_time.year, date_time.month, date_time.day, date_time.hour,
date_time.minute, date_time.second,
-1, -1, -1)) + date_time.microsecond / 1e6
return (date_time - _EPOCH).total_seconds() | python | def timestamp_from_datetime(date_time):
if date_time.tzinfo is None:
return time.mktime((date_time.year, date_time.month, date_time.day, date_time.hour,
date_time.minute, date_time.second,
-1, -1, -1)) + date_time.microsecond / 1e6
return (date_time - _EPOCH).total_seconds() | [
"def",
"timestamp_from_datetime",
"(",
"date_time",
")",
":",
"if",
"date_time",
".",
"tzinfo",
"is",
"None",
":",
"return",
"time",
".",
"mktime",
"(",
"(",
"date_time",
".",
"year",
",",
"date_time",
".",
"month",
",",
"date_time",
".",
"day",
",",
"da... | Returns POSIX timestamp as float | [
"Returns",
"POSIX",
"timestamp",
"as",
"float"
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/time.py#L151-L157 |
25,211 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient.create_agent | def create_agent(self, configuration, agent_id=""):
"""Create an agent.
:param dict configuration: Form given by the craftai documentation.
:param str agent_id: Optional. The id of the agent to create. It
must be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:default agent_id: "", the agent_id is generated.
:return: agent created.
:rtype: dict.
:raise CraftAiBadRequestError: if the input is not of
the right form.
"""
# Extra header in addition to the main session's
ct_header = {"Content-Type": "application/json; charset=utf-8"}
# Building payload and checking that it is valid for a JSON
# serialization
payload = {"configuration": configuration}
if agent_id != "":
# Raises an error when agent_id is invalid
self._check_agent_id(agent_id)
payload["id"] = agent_id
try:
json_pl = json.dumps(payload)
except TypeError as err:
raise CraftAiBadRequestError("Invalid configuration or agent id given. {}"
.format(err.__str__()))
req_url = "{}/agents".format(self._base_url)
resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl)
agent = self._decode_response(resp)
return agent | python | def create_agent(self, configuration, agent_id=""):
# Extra header in addition to the main session's
ct_header = {"Content-Type": "application/json; charset=utf-8"}
# Building payload and checking that it is valid for a JSON
# serialization
payload = {"configuration": configuration}
if agent_id != "":
# Raises an error when agent_id is invalid
self._check_agent_id(agent_id)
payload["id"] = agent_id
try:
json_pl = json.dumps(payload)
except TypeError as err:
raise CraftAiBadRequestError("Invalid configuration or agent id given. {}"
.format(err.__str__()))
req_url = "{}/agents".format(self._base_url)
resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl)
agent = self._decode_response(resp)
return agent | [
"def",
"create_agent",
"(",
"self",
",",
"configuration",
",",
"agent_id",
"=",
"\"\"",
")",
":",
"# Extra header in addition to the main session's",
"ct_header",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json; charset=utf-8\"",
"}",
"# Building payload and checking t... | Create an agent.
:param dict configuration: Form given by the craftai documentation.
:param str agent_id: Optional. The id of the agent to create. It
must be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:default agent_id: "", the agent_id is generated.
:return: agent created.
:rtype: dict.
:raise CraftAiBadRequestError: if the input is not of
the right form. | [
"Create",
"an",
"agent",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L112-L151 |
25,212 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient.delete_agent | def delete_agent(self, agent_id):
"""Delete an agent.
:param str agent_id: The id of the agent to delete. It must
be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:return: agent deleted.
:rtype: dict.
"""
# Raises an error when agent_id is invalid
self._check_agent_id(agent_id)
req_url = "{}/agents/{}".format(self._base_url, agent_id)
resp = self._requests_session.delete(req_url)
decoded_resp = self._decode_response(resp)
return decoded_resp | python | def delete_agent(self, agent_id):
# Raises an error when agent_id is invalid
self._check_agent_id(agent_id)
req_url = "{}/agents/{}".format(self._base_url, agent_id)
resp = self._requests_session.delete(req_url)
decoded_resp = self._decode_response(resp)
return decoded_resp | [
"def",
"delete_agent",
"(",
"self",
",",
"agent_id",
")",
":",
"# Raises an error when agent_id is invalid",
"self",
".",
"_check_agent_id",
"(",
"agent_id",
")",
"req_url",
"=",
"\"{}/agents/{}\"",
".",
"format",
"(",
"self",
".",
"_base_url",
",",
"agent_id",
")... | Delete an agent.
:param str agent_id: The id of the agent to delete. It must
be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:return: agent deleted.
:rtype: dict. | [
"Delete",
"an",
"agent",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L205-L223 |
25,213 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient.delete_agents_bulk | def delete_agents_bulk(self, payload):
"""Delete a group of agents
:param list payload: Contains the informations to delete the agents.
It's in the form [{"id": agent_id}].
With id an str containing only characters in "a-zA-Z0-9_-" and must
be between 1 and 36 characters.
:return: the list of agents deleted which are represented with
dictionnaries.
:rtype: list of dict.
:raises CraftAiBadRequestError: If all of the ids are invalid.
"""
# Check all ids, raise an error if all ids are invalid
valid_indices, invalid_indices, invalid_agents = self._check_agent_id_bulk(payload)
# Create the json file with the agents with valid id and send it
valid_agents = self._create_and_send_json_bulk([payload[i] for i in valid_indices],
"{}/bulk/agents".format(self._base_url),
"DELETE")
if invalid_indices == []:
return valid_agents
# Put the valid and invalid agents in their original index
return self._recreate_list_with_indices(valid_indices,
valid_agents,
invalid_indices,
invalid_agents) | python | def delete_agents_bulk(self, payload):
# Check all ids, raise an error if all ids are invalid
valid_indices, invalid_indices, invalid_agents = self._check_agent_id_bulk(payload)
# Create the json file with the agents with valid id and send it
valid_agents = self._create_and_send_json_bulk([payload[i] for i in valid_indices],
"{}/bulk/agents".format(self._base_url),
"DELETE")
if invalid_indices == []:
return valid_agents
# Put the valid and invalid agents in their original index
return self._recreate_list_with_indices(valid_indices,
valid_agents,
invalid_indices,
invalid_agents) | [
"def",
"delete_agents_bulk",
"(",
"self",
",",
"payload",
")",
":",
"# Check all ids, raise an error if all ids are invalid",
"valid_indices",
",",
"invalid_indices",
",",
"invalid_agents",
"=",
"self",
".",
"_check_agent_id_bulk",
"(",
"payload",
")",
"# Create the json fi... | Delete a group of agents
:param list payload: Contains the informations to delete the agents.
It's in the form [{"id": agent_id}].
With id an str containing only characters in "a-zA-Z0-9_-" and must
be between 1 and 36 characters.
:return: the list of agents deleted which are represented with
dictionnaries.
:rtype: list of dict.
:raises CraftAiBadRequestError: If all of the ids are invalid. | [
"Delete",
"a",
"group",
"of",
"agents"
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L225-L254 |
25,214 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient.add_operations | def add_operations(self, agent_id, operations):
"""Add operations to an agent.
:param str agent_id: The id of the agent to delete. It must be
an str containing only characters in "a-zA-Z0-9_-" and must be
between 1 and 36 characters. It must referenced an existing agent.
:param list operations: Contains dictionnaries that has the
form given in the craftai documentation and the configuration
of the agent.
:return: message about the added operations.
:rtype: str
:raise CraftAiBadRequestError: if the input is not of
the right form.
"""
# Raises an error when agent_id is invalid
self._check_agent_id(agent_id)
# Extra header in addition to the main session's
ct_header = {"Content-Type": "application/json; charset=utf-8"}
offset = 0
is_looping = True
while is_looping:
next_offset = offset + self.config["operationsChunksSize"]
try:
json_pl = json.dumps(operations[offset:next_offset])
except TypeError as err:
raise CraftAiBadRequestError("Invalid configuration or agent id given. {}"
.format(err.__str__()))
req_url = "{}/agents/{}/context".format(self._base_url, agent_id)
resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl)
self._decode_response(resp)
if next_offset >= len(operations):
is_looping = False
offset = next_offset
return {
"message": "Successfully added %i operation(s) to the agent \"%s/%s/%s\" context."
% (len(operations), self.config["owner"], self.config["project"], agent_id)
} | python | def add_operations(self, agent_id, operations):
# Raises an error when agent_id is invalid
self._check_agent_id(agent_id)
# Extra header in addition to the main session's
ct_header = {"Content-Type": "application/json; charset=utf-8"}
offset = 0
is_looping = True
while is_looping:
next_offset = offset + self.config["operationsChunksSize"]
try:
json_pl = json.dumps(operations[offset:next_offset])
except TypeError as err:
raise CraftAiBadRequestError("Invalid configuration or agent id given. {}"
.format(err.__str__()))
req_url = "{}/agents/{}/context".format(self._base_url, agent_id)
resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl)
self._decode_response(resp)
if next_offset >= len(operations):
is_looping = False
offset = next_offset
return {
"message": "Successfully added %i operation(s) to the agent \"%s/%s/%s\" context."
% (len(operations), self.config["owner"], self.config["project"], agent_id)
} | [
"def",
"add_operations",
"(",
"self",
",",
"agent_id",
",",
"operations",
")",
":",
"# Raises an error when agent_id is invalid",
"self",
".",
"_check_agent_id",
"(",
"agent_id",
")",
"# Extra header in addition to the main session's",
"ct_header",
"=",
"{",
"\"Content-Type... | Add operations to an agent.
:param str agent_id: The id of the agent to delete. It must be
an str containing only characters in "a-zA-Z0-9_-" and must be
between 1 and 36 characters. It must referenced an existing agent.
:param list operations: Contains dictionnaries that has the
form given in the craftai documentation and the configuration
of the agent.
:return: message about the added operations.
:rtype: str
:raise CraftAiBadRequestError: if the input is not of
the right form. | [
"Add",
"operations",
"to",
"an",
"agent",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L285-L331 |
25,215 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._add_operations_bulk | def _add_operations_bulk(self, chunked_data):
"""Tool for the function add_operations_bulk. It send the requests to
add the operations to the agents.
:param list chunked_data: list of list of the agents and their operations
to add. Each chunk can be requested at the same time.
:return: list of agents containing a message about the added
operations.
:rtype: list if dict.
:raises CraftAiBadRequestError: if the input is not of the right form.
"""
url = "{}/bulk/context".format(self._base_url)
ct_header = {"Content-Type": "application/json; charset=utf-8"}
responses = []
for chunk in chunked_data:
if len(chunk) > 1:
try:
json_pl = json.dumps(chunk)
except TypeError as err:
raise CraftAiBadRequestError("Error while dumping the payload into json"
"format when converting it for the bulk request. {}"
.format(err.__str__()))
resp = self._requests_session.post(url, headers=ct_header, data=json_pl)
resp = self._decode_response(resp)
responses += resp
elif chunk:
message = self.add_operations(chunk[0]["id"], chunk[0]["operations"])
responses.append({"id": chunk[0]["id"], "status": 201, "message": message})
if responses == []:
raise CraftAiBadRequestError("Invalid or empty set of operations given")
return responses | python | def _add_operations_bulk(self, chunked_data):
url = "{}/bulk/context".format(self._base_url)
ct_header = {"Content-Type": "application/json; charset=utf-8"}
responses = []
for chunk in chunked_data:
if len(chunk) > 1:
try:
json_pl = json.dumps(chunk)
except TypeError as err:
raise CraftAiBadRequestError("Error while dumping the payload into json"
"format when converting it for the bulk request. {}"
.format(err.__str__()))
resp = self._requests_session.post(url, headers=ct_header, data=json_pl)
resp = self._decode_response(resp)
responses += resp
elif chunk:
message = self.add_operations(chunk[0]["id"], chunk[0]["operations"])
responses.append({"id": chunk[0]["id"], "status": 201, "message": message})
if responses == []:
raise CraftAiBadRequestError("Invalid or empty set of operations given")
return responses | [
"def",
"_add_operations_bulk",
"(",
"self",
",",
"chunked_data",
")",
":",
"url",
"=",
"\"{}/bulk/context\"",
".",
"format",
"(",
"self",
".",
"_base_url",
")",
"ct_header",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json; charset=utf-8\"",
"}",
"responses",
... | Tool for the function add_operations_bulk. It send the requests to
add the operations to the agents.
:param list chunked_data: list of list of the agents and their operations
to add. Each chunk can be requested at the same time.
:return: list of agents containing a message about the added
operations.
:rtype: list if dict.
:raises CraftAiBadRequestError: if the input is not of the right form. | [
"Tool",
"for",
"the",
"function",
"add_operations_bulk",
".",
"It",
"send",
"the",
"requests",
"to",
"add",
"the",
"operations",
"to",
"the",
"agents",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L333-L368 |
25,216 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient.add_operations_bulk | def add_operations_bulk(self, payload):
"""Add operations to a group of agents.
:param list payload: contains the informations necessary for the action.
It's in the form [{"id": agent_id, "operations": operations}]
With id that is an str containing only characters in "a-zA-Z0-9_-"
and must be between 1 and 36 characters. It must referenced an
existing agent.
With operations a list containing dictionnaries that has the form given
in the craftai documentation and the configuration of the agent.
:return: list of agents containing a message about the added
operations.
:rtype: list if dict.
:raises CraftAiBadRequestError: if all of the ids are invalid or
referenced non existing agents or one of the operations is invalid.
"""
# Check all ids, raise an error if all ids are invalid
valid_indices, _, _ = self._check_agent_id_bulk(payload)
valid_payload = [payload[i] for i in valid_indices]
chunked_data = []
current_chunk = []
current_chunk_size = 0
for agent in valid_payload:
if (agent["operations"] and isinstance(agent["operations"], list)):
if current_chunk_size + len(agent["operations"]) > self.config["operationsChunksSize"]:
chunked_data.append(current_chunk)
current_chunk_size = 0
current_chunk = []
if len(agent["operations"]) > self.config["operationsChunksSize"]:
chunked_data.append([agent])
current_chunk_size = 0
else:
current_chunk_size += len(agent["operations"])
current_chunk.append(agent)
if current_chunk:
chunked_data.append(current_chunk)
return self._add_operations_bulk(chunked_data) | python | def add_operations_bulk(self, payload):
# Check all ids, raise an error if all ids are invalid
valid_indices, _, _ = self._check_agent_id_bulk(payload)
valid_payload = [payload[i] for i in valid_indices]
chunked_data = []
current_chunk = []
current_chunk_size = 0
for agent in valid_payload:
if (agent["operations"] and isinstance(agent["operations"], list)):
if current_chunk_size + len(agent["operations"]) > self.config["operationsChunksSize"]:
chunked_data.append(current_chunk)
current_chunk_size = 0
current_chunk = []
if len(agent["operations"]) > self.config["operationsChunksSize"]:
chunked_data.append([agent])
current_chunk_size = 0
else:
current_chunk_size += len(agent["operations"])
current_chunk.append(agent)
if current_chunk:
chunked_data.append(current_chunk)
return self._add_operations_bulk(chunked_data) | [
"def",
"add_operations_bulk",
"(",
"self",
",",
"payload",
")",
":",
"# Check all ids, raise an error if all ids are invalid",
"valid_indices",
",",
"_",
",",
"_",
"=",
"self",
".",
"_check_agent_id_bulk",
"(",
"payload",
")",
"valid_payload",
"=",
"[",
"payload",
"... | Add operations to a group of agents.
:param list payload: contains the informations necessary for the action.
It's in the form [{"id": agent_id, "operations": operations}]
With id that is an str containing only characters in "a-zA-Z0-9_-"
and must be between 1 and 36 characters. It must referenced an
existing agent.
With operations a list containing dictionnaries that has the form given
in the craftai documentation and the configuration of the agent.
:return: list of agents containing a message about the added
operations.
:rtype: list if dict.
:raises CraftAiBadRequestError: if all of the ids are invalid or
referenced non existing agents or one of the operations is invalid. | [
"Add",
"operations",
"to",
"a",
"group",
"of",
"agents",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L370-L412 |
25,217 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._get_decision_tree | def _get_decision_tree(self, agent_id, timestamp, version):
"""Tool for the function get_decision_tree.
:param str agent_id: the id of the agent to get the tree. It
must be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:param int timestamp: Optional. The decision tree is comptuted
at this timestamp.
:default timestamp: None, means that we get the tree computed
with all its context history.
:param version: version of the tree to get.
:type version: str or int
:default version: default version of the tree.
:return: decision tree.
:rtype: dict.
"""
headers = self._headers.copy()
headers["x-craft-ai-tree-version"] = version
# If we give no timestamp the default behaviour is to give the tree from the latest timestamp
if timestamp is None:
req_url = "{}/agents/{}/decision/tree?".format(self._base_url, agent_id)
else:
req_url = "{}/agents/{}/decision/tree?t={}".format(self._base_url, agent_id, timestamp)
resp = self._requests_session.get(req_url)
decision_tree = self._decode_response(resp)
return decision_tree | python | def _get_decision_tree(self, agent_id, timestamp, version):
headers = self._headers.copy()
headers["x-craft-ai-tree-version"] = version
# If we give no timestamp the default behaviour is to give the tree from the latest timestamp
if timestamp is None:
req_url = "{}/agents/{}/decision/tree?".format(self._base_url, agent_id)
else:
req_url = "{}/agents/{}/decision/tree?t={}".format(self._base_url, agent_id, timestamp)
resp = self._requests_session.get(req_url)
decision_tree = self._decode_response(resp)
return decision_tree | [
"def",
"_get_decision_tree",
"(",
"self",
",",
"agent_id",
",",
"timestamp",
",",
"version",
")",
":",
"headers",
"=",
"self",
".",
"_headers",
".",
"copy",
"(",
")",
"headers",
"[",
"\"x-craft-ai-tree-version\"",
"]",
"=",
"version",
"# If we give no timestamp ... | Tool for the function get_decision_tree.
:param str agent_id: the id of the agent to get the tree. It
must be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:param int timestamp: Optional. The decision tree is comptuted
at this timestamp.
:default timestamp: None, means that we get the tree computed
with all its context history.
:param version: version of the tree to get.
:type version: str or int
:default version: default version of the tree.
:return: decision tree.
:rtype: dict. | [
"Tool",
"for",
"the",
"function",
"get_decision_tree",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L485-L514 |
25,218 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient.get_decision_tree | def get_decision_tree(self, agent_id, timestamp=None, version=DEFAULT_DECISION_TREE_VERSION):
"""Get decision tree.
:param str agent_id: the id of the agent to get the tree. It
must be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:param int timestamp: Optional. The decision tree is comptuted
at this timestamp.
:default timestamp: None, means that we get the tree computed
with all its context history.
:param version: version of the tree to get.
:type version: str or int.
:default version: default version of the tree.
:return: decision tree.
:rtype: dict.
:raises CraftAiLongRequestTimeOutError: if the API doesn't get
the tree in the time given by the configuration.
"""
# Raises an error when agent_id is invalid
self._check_agent_id(agent_id)
if self._config["decisionTreeRetrievalTimeout"] is False:
# Don't retry
return self._get_decision_tree(agent_id, timestamp, version)
start = current_time_ms()
while True:
now = current_time_ms()
if now - start > self._config["decisionTreeRetrievalTimeout"]:
# Client side timeout
raise CraftAiLongRequestTimeOutError()
try:
return self._get_decision_tree(agent_id, timestamp, version)
except CraftAiLongRequestTimeOutError:
# Do nothing and continue.
continue | python | def get_decision_tree(self, agent_id, timestamp=None, version=DEFAULT_DECISION_TREE_VERSION):
# Raises an error when agent_id is invalid
self._check_agent_id(agent_id)
if self._config["decisionTreeRetrievalTimeout"] is False:
# Don't retry
return self._get_decision_tree(agent_id, timestamp, version)
start = current_time_ms()
while True:
now = current_time_ms()
if now - start > self._config["decisionTreeRetrievalTimeout"]:
# Client side timeout
raise CraftAiLongRequestTimeOutError()
try:
return self._get_decision_tree(agent_id, timestamp, version)
except CraftAiLongRequestTimeOutError:
# Do nothing and continue.
continue | [
"def",
"get_decision_tree",
"(",
"self",
",",
"agent_id",
",",
"timestamp",
"=",
"None",
",",
"version",
"=",
"DEFAULT_DECISION_TREE_VERSION",
")",
":",
"# Raises an error when agent_id is invalid",
"self",
".",
"_check_agent_id",
"(",
"agent_id",
")",
"if",
"self",
... | Get decision tree.
:param str agent_id: the id of the agent to get the tree. It
must be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:param int timestamp: Optional. The decision tree is comptuted
at this timestamp.
:default timestamp: None, means that we get the tree computed
with all its context history.
:param version: version of the tree to get.
:type version: str or int.
:default version: default version of the tree.
:return: decision tree.
:rtype: dict.
:raises CraftAiLongRequestTimeOutError: if the API doesn't get
the tree in the time given by the configuration. | [
"Get",
"decision",
"tree",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L516-L552 |
25,219 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._get_decision_trees_bulk | def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts):
"""Tool for the function get_decision_trees_bulk.
:param list payload: contains the informations necessary for getting
the trees. Its form is the same than for the function.
get_decision_trees_bulk.
:param list valid_indices: list of the indices of the valid agent id.
:param list invalid_indices: list of the indices of the valid agent id.
:param list invalid_dts: list of the invalid agent id.
:return: decision trees.
:rtype: list of dict.
"""
valid_dts = self._create_and_send_json_bulk([payload[i] for i in valid_indices],
"{}/bulk/decision_tree".format(self._base_url),
"POST")
if invalid_indices == []:
return valid_dts
# Put the valid and invalid decision trees in their original index
return self._recreate_list_with_indices(valid_indices, valid_dts, invalid_indices, invalid_dts) | python | def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts):
valid_dts = self._create_and_send_json_bulk([payload[i] for i in valid_indices],
"{}/bulk/decision_tree".format(self._base_url),
"POST")
if invalid_indices == []:
return valid_dts
# Put the valid and invalid decision trees in their original index
return self._recreate_list_with_indices(valid_indices, valid_dts, invalid_indices, invalid_dts) | [
"def",
"_get_decision_trees_bulk",
"(",
"self",
",",
"payload",
",",
"valid_indices",
",",
"invalid_indices",
",",
"invalid_dts",
")",
":",
"valid_dts",
"=",
"self",
".",
"_create_and_send_json_bulk",
"(",
"[",
"payload",
"[",
"i",
"]",
"for",
"i",
"in",
"vali... | Tool for the function get_decision_trees_bulk.
:param list payload: contains the informations necessary for getting
the trees. Its form is the same than for the function.
get_decision_trees_bulk.
:param list valid_indices: list of the indices of the valid agent id.
:param list invalid_indices: list of the indices of the valid agent id.
:param list invalid_dts: list of the invalid agent id.
:return: decision trees.
:rtype: list of dict. | [
"Tool",
"for",
"the",
"function",
"get_decision_trees_bulk",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L554-L575 |
25,220 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient.get_decision_trees_bulk | def get_decision_trees_bulk(self, payload, version=DEFAULT_DECISION_TREE_VERSION):
"""Get a group of decision trees.
:param list payload: contains the informations necessary for getting
the trees. It's in the form [{"id": agent_id, "timestamp": timestamp}]
With id a str containing only characters in "a-zA-Z0-9_-" and must be
between 1 and 36 characters. It must referenced an existing agent.
With timestamp an positive and not null integer.
:param version: version of the tree to get.
:type version: str or int.
:default version: default version of the tree.
:return: Decision trees.
:rtype: list of dict.
:raises CraftAiBadRequestError: if all of the ids are invalid or
referenced non existing agents or all of the timestamp are invalid.
:raises CraftAiLongRequestTimeOutError: if the API doesn't get
the tree in the time given by the configuration.
"""
# payload = [{"id": agent_id, "timestamp": timestamp}]
headers = self._headers.copy()
headers["x-craft-ai-tree-version"] = version
# Check all ids, raise an error if all ids are invalid
valid_indices, invalid_indices, invalid_dts = self._check_agent_id_bulk(payload)
if self._config["decisionTreeRetrievalTimeout"] is False:
# Don't retry
return self._get_decision_trees_bulk(payload,
valid_indices,
invalid_indices,
invalid_dts)
start = current_time_ms()
while True:
now = current_time_ms()
if now - start > self._config["decisionTreeRetrievalTimeout"]:
# Client side timeout
raise CraftAiLongRequestTimeOutError()
try:
return self._get_decision_trees_bulk(payload,
valid_indices,
invalid_indices,
invalid_dts)
except CraftAiLongRequestTimeOutError:
# Do nothing and continue.
continue | python | def get_decision_trees_bulk(self, payload, version=DEFAULT_DECISION_TREE_VERSION):
# payload = [{"id": agent_id, "timestamp": timestamp}]
headers = self._headers.copy()
headers["x-craft-ai-tree-version"] = version
# Check all ids, raise an error if all ids are invalid
valid_indices, invalid_indices, invalid_dts = self._check_agent_id_bulk(payload)
if self._config["decisionTreeRetrievalTimeout"] is False:
# Don't retry
return self._get_decision_trees_bulk(payload,
valid_indices,
invalid_indices,
invalid_dts)
start = current_time_ms()
while True:
now = current_time_ms()
if now - start > self._config["decisionTreeRetrievalTimeout"]:
# Client side timeout
raise CraftAiLongRequestTimeOutError()
try:
return self._get_decision_trees_bulk(payload,
valid_indices,
invalid_indices,
invalid_dts)
except CraftAiLongRequestTimeOutError:
# Do nothing and continue.
continue | [
"def",
"get_decision_trees_bulk",
"(",
"self",
",",
"payload",
",",
"version",
"=",
"DEFAULT_DECISION_TREE_VERSION",
")",
":",
"# payload = [{\"id\": agent_id, \"timestamp\": timestamp}]",
"headers",
"=",
"self",
".",
"_headers",
".",
"copy",
"(",
")",
"headers",
"[",
... | Get a group of decision trees.
:param list payload: contains the informations necessary for getting
the trees. It's in the form [{"id": agent_id, "timestamp": timestamp}]
With id a str containing only characters in "a-zA-Z0-9_-" and must be
between 1 and 36 characters. It must referenced an existing agent.
With timestamp an positive and not null integer.
:param version: version of the tree to get.
:type version: str or int.
:default version: default version of the tree.
:return: Decision trees.
:rtype: list of dict.
:raises CraftAiBadRequestError: if all of the ids are invalid or
referenced non existing agents or all of the timestamp are invalid.
:raises CraftAiLongRequestTimeOutError: if the API doesn't get
the tree in the time given by the configuration. | [
"Get",
"a",
"group",
"of",
"decision",
"trees",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L577-L623 |
25,221 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._decode_response | def _decode_response(response):
"""Decode the response of a request.
:param response: response of a request.
:return: decoded response.
:raise Error: Raise the error given by the request.
"""
status_code = response.status_code
message = "Status code " + str(status_code)
try:
message = CraftAIClient._parse_body(response)["message"]
except (CraftAiInternalError, KeyError, TypeError):
pass
if status_code in [200, 201, 204, 207]:
return CraftAIClient._parse_body(response)
else:
raise CraftAIClient._get_error_from_status(status_code, message)
return None | python | def _decode_response(response):
status_code = response.status_code
message = "Status code " + str(status_code)
try:
message = CraftAIClient._parse_body(response)["message"]
except (CraftAiInternalError, KeyError, TypeError):
pass
if status_code in [200, 201, 204, 207]:
return CraftAIClient._parse_body(response)
else:
raise CraftAIClient._get_error_from_status(status_code, message)
return None | [
"def",
"_decode_response",
"(",
"response",
")",
":",
"status_code",
"=",
"response",
".",
"status_code",
"message",
"=",
"\"Status code \"",
"+",
"str",
"(",
"status_code",
")",
"try",
":",
"message",
"=",
"CraftAIClient",
".",
"_parse_body",
"(",
"response",
... | Decode the response of a request.
:param response: response of a request.
:return: decoded response.
:raise Error: Raise the error given by the request. | [
"Decode",
"the",
"response",
"of",
"a",
"request",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L639-L660 |
25,222 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._decode_response_bulk | def _decode_response_bulk(response_bulk):
"""Decode the response of each agent given by a bulk function.
:param list response_bulk: list of dictionnary which represents
the response for an agent.
:return: decoded response.
:rtype: list of dict.
"""
resp = []
for response in response_bulk:
if ("status" in response) and (response.get("status") == 201):
agent = {"id": response["id"],
"message": response["message"]}
resp.append(agent)
elif "status" in response:
status_code = response["status"]
message = response["message"]
agent = {"error": CraftAIClient._get_error_from_status(status_code, message)}
try:
agent["id"] = response["id"]
except KeyError:
pass
resp.append(agent)
else:
resp.append(response)
return resp | python | def _decode_response_bulk(response_bulk):
resp = []
for response in response_bulk:
if ("status" in response) and (response.get("status") == 201):
agent = {"id": response["id"],
"message": response["message"]}
resp.append(agent)
elif "status" in response:
status_code = response["status"]
message = response["message"]
agent = {"error": CraftAIClient._get_error_from_status(status_code, message)}
try:
agent["id"] = response["id"]
except KeyError:
pass
resp.append(agent)
else:
resp.append(response)
return resp | [
"def",
"_decode_response_bulk",
"(",
"response_bulk",
")",
":",
"resp",
"=",
"[",
"]",
"for",
"response",
"in",
"response_bulk",
":",
"if",
"(",
"\"status\"",
"in",
"response",
")",
"and",
"(",
"response",
".",
"get",
"(",
"\"status\"",
")",
"==",
"201",
... | Decode the response of each agent given by a bulk function.
:param list response_bulk: list of dictionnary which represents
the response for an agent.
:return: decoded response.
:rtype: list of dict. | [
"Decode",
"the",
"response",
"of",
"each",
"agent",
"given",
"by",
"a",
"bulk",
"function",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L663-L691 |
25,223 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._get_error_from_status | def _get_error_from_status(status_code, message):
"""Give the error corresponding to the status code.
:param int status_code: status code of the response to
a request.
:param str message: error message given by the response.
:return: error corresponding to the status code.
:rtype: Error.
"""
if status_code == 202:
err = CraftAiLongRequestTimeOutError(message)
elif status_code == 401 or status_code == 403:
err = CraftAiCredentialsError(message)
elif status_code == 400:
err = CraftAiBadRequestError(message)
elif status_code == 404:
err = CraftAiNotFoundError(message)
elif status_code == 413:
err = CraftAiBadRequestError("Given payload is too large")
elif status_code == 500:
err = CraftAiInternalError(message)
elif status_code == 503:
err = CraftAiNetworkError("""Service momentarily unavailable, please try"""
"""again in a few minutes. If the problem """
"""persists please contact us at support@craft.ai""")
elif status_code == 504:
err = CraftAiBadRequestError("Request has timed out")
else:
err = CraftAiUnknownError(message)
return err | python | def _get_error_from_status(status_code, message):
if status_code == 202:
err = CraftAiLongRequestTimeOutError(message)
elif status_code == 401 or status_code == 403:
err = CraftAiCredentialsError(message)
elif status_code == 400:
err = CraftAiBadRequestError(message)
elif status_code == 404:
err = CraftAiNotFoundError(message)
elif status_code == 413:
err = CraftAiBadRequestError("Given payload is too large")
elif status_code == 500:
err = CraftAiInternalError(message)
elif status_code == 503:
err = CraftAiNetworkError("""Service momentarily unavailable, please try"""
"""again in a few minutes. If the problem """
"""persists please contact us at support@craft.ai""")
elif status_code == 504:
err = CraftAiBadRequestError("Request has timed out")
else:
err = CraftAiUnknownError(message)
return err | [
"def",
"_get_error_from_status",
"(",
"status_code",
",",
"message",
")",
":",
"if",
"status_code",
"==",
"202",
":",
"err",
"=",
"CraftAiLongRequestTimeOutError",
"(",
"message",
")",
"elif",
"status_code",
"==",
"401",
"or",
"status_code",
"==",
"403",
":",
... | Give the error corresponding to the status code.
:param int status_code: status code of the response to
a request.
:param str message: error message given by the response.
:return: error corresponding to the status code.
:rtype: Error. | [
"Give",
"the",
"error",
"corresponding",
"to",
"the",
"status",
"code",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L694-L725 |
25,224 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._check_agent_id | def _check_agent_id(agent_id):
"""Checks that the given agent_id is a valid non-empty string.
:param str agent_id: agent id to check.
:raise CraftAiBadRequestError: If the given agent_id is not of
type string or if it is an empty string.
"""
if (not isinstance(agent_id, six.string_types) or
AGENT_ID_PATTERN.match(agent_id) is None):
raise CraftAiBadRequestError(ERROR_ID_MESSAGE) | python | def _check_agent_id(agent_id):
if (not isinstance(agent_id, six.string_types) or
AGENT_ID_PATTERN.match(agent_id) is None):
raise CraftAiBadRequestError(ERROR_ID_MESSAGE) | [
"def",
"_check_agent_id",
"(",
"agent_id",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"agent_id",
",",
"six",
".",
"string_types",
")",
"or",
"AGENT_ID_PATTERN",
".",
"match",
"(",
"agent_id",
")",
"is",
"None",
")",
":",
"raise",
"CraftAiBadRequestError... | Checks that the given agent_id is a valid non-empty string.
:param str agent_id: agent id to check.
:raise CraftAiBadRequestError: If the given agent_id is not of
type string or if it is an empty string. | [
"Checks",
"that",
"the",
"given",
"agent_id",
"is",
"a",
"valid",
"non",
"-",
"empty",
"string",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L728-L738 |
25,225 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._check_agent_id_bulk | def _check_agent_id_bulk(self, payload):
"""Checks that all the given agent ids are valid non-empty strings
and if the agents are serializable.
:param list payload: list of dictionnary which represents an agent.
:return: list of the agents with valid ids, list of the agents with
invalid ids, list of the dictionnaries with valid ids.
:rtype: list, list, list of dict.
:raise CraftAiBadRequestError: If all the agents are invalid.
"""
invalid_agent_indices = []
valid_agent_indices = []
invalid_payload = []
for index, agent in enumerate(payload):
# Check if the agent ID is valid
try:
if "id" in agent:
self._check_agent_id(agent["id"])
except CraftAiBadRequestError:
invalid_agent_indices.append(index)
invalid_payload.append({"id": agent["id"],
"error": CraftAiBadRequestError(ERROR_ID_MESSAGE)})
else:
# Check if the agent is serializable
try:
json.dumps([agent])
except TypeError as err:
invalid_agent_indices.append(index)
invalid_payload.append({"id": agent["id"],
"error": err})
else:
valid_agent_indices.append(index)
if len(invalid_agent_indices) == len(payload):
raise CraftAiBadRequestError(ERROR_ID_MESSAGE)
return valid_agent_indices, invalid_agent_indices, invalid_payload | python | def _check_agent_id_bulk(self, payload):
invalid_agent_indices = []
valid_agent_indices = []
invalid_payload = []
for index, agent in enumerate(payload):
# Check if the agent ID is valid
try:
if "id" in agent:
self._check_agent_id(agent["id"])
except CraftAiBadRequestError:
invalid_agent_indices.append(index)
invalid_payload.append({"id": agent["id"],
"error": CraftAiBadRequestError(ERROR_ID_MESSAGE)})
else:
# Check if the agent is serializable
try:
json.dumps([agent])
except TypeError as err:
invalid_agent_indices.append(index)
invalid_payload.append({"id": agent["id"],
"error": err})
else:
valid_agent_indices.append(index)
if len(invalid_agent_indices) == len(payload):
raise CraftAiBadRequestError(ERROR_ID_MESSAGE)
return valid_agent_indices, invalid_agent_indices, invalid_payload | [
"def",
"_check_agent_id_bulk",
"(",
"self",
",",
"payload",
")",
":",
"invalid_agent_indices",
"=",
"[",
"]",
"valid_agent_indices",
"=",
"[",
"]",
"invalid_payload",
"=",
"[",
"]",
"for",
"index",
",",
"agent",
"in",
"enumerate",
"(",
"payload",
")",
":",
... | Checks that all the given agent ids are valid non-empty strings
and if the agents are serializable.
:param list payload: list of dictionnary which represents an agent.
:return: list of the agents with valid ids, list of the agents with
invalid ids, list of the dictionnaries with valid ids.
:rtype: list, list, list of dict.
:raise CraftAiBadRequestError: If all the agents are invalid. | [
"Checks",
"that",
"all",
"the",
"given",
"agent",
"ids",
"are",
"valid",
"non",
"-",
"empty",
"strings",
"and",
"if",
"the",
"agents",
"are",
"serializable",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L740-L778 |
25,226 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._recreate_list_with_indices | def _recreate_list_with_indices(indices1, values1, indices2, values2):
"""Create a list in the right order.
:param list indices1: contains the list of indices corresponding to
the values in values1.
:param list values1: contains the first list of values.
:param list indices2: contains the list of indices corresponding to
the values in values2.
:param list values2: contains the second list of values.
:return: list of the values in the correct order.
:rtype: list.
"""
# Test if indices are continuous
list_indices = sorted(indices1 + indices2)
for i, index in enumerate(list_indices):
if i != index:
raise CraftAiInternalError("The agents's indices are not continuous")
full_list = [None] * (len(indices1) + len(indices2))
for i, index in enumerate(indices1):
full_list[index] = values1[i]
for i, index in enumerate(indices2):
full_list[index] = values2[i]
return full_list | python | def _recreate_list_with_indices(indices1, values1, indices2, values2):
# Test if indices are continuous
list_indices = sorted(indices1 + indices2)
for i, index in enumerate(list_indices):
if i != index:
raise CraftAiInternalError("The agents's indices are not continuous")
full_list = [None] * (len(indices1) + len(indices2))
for i, index in enumerate(indices1):
full_list[index] = values1[i]
for i, index in enumerate(indices2):
full_list[index] = values2[i]
return full_list | [
"def",
"_recreate_list_with_indices",
"(",
"indices1",
",",
"values1",
",",
"indices2",
",",
"values2",
")",
":",
"# Test if indices are continuous",
"list_indices",
"=",
"sorted",
"(",
"indices1",
"+",
"indices2",
")",
"for",
"i",
",",
"index",
"in",
"enumerate",... | Create a list in the right order.
:param list indices1: contains the list of indices corresponding to
the values in values1.
:param list values1: contains the first list of values.
:param list indices2: contains the list of indices corresponding to
the values in values2.
:param list values2: contains the second list of values.
:return: list of the values in the correct order.
:rtype: list. | [
"Create",
"a",
"list",
"in",
"the",
"right",
"order",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L781-L805 |
25,227 | craft-ai/craft-ai-client-python | craftai/client.py | CraftAIClient._create_and_send_json_bulk | def _create_and_send_json_bulk(self, payload, req_url, request_type="POST"):
"""Create a json, do a request to the URL and process the response.
:param list payload: contains the informations necessary for the action.
It's a list of dictionnary.
:param str req_url: URL to request with the payload.
:param str request_type: type of request, either "POST" or "DELETE".
:default request_type: "POST".
:return: response of the request.
:rtype: list of dict.
:raises CraftAiBadRequestError: if the payload doesn't have the
correct form to be transformed into a json or request_type is
neither "POST" or "DELETE".
"""
# Extra header in addition to the main session's
ct_header = {"Content-Type": "application/json; charset=utf-8"}
try:
json_pl = json.dumps(payload)
except TypeError as err:
raise CraftAiBadRequestError("Error while dumping the payload into json"
"format when converting it for the bulk request. {}"
.format(err.__str__()))
if request_type == "POST":
resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl)
elif request_type == "DELETE":
resp = self._requests_session.delete(req_url, headers=ct_header, data=json_pl)
else:
raise CraftAiBadRequestError("Request for the bulk API should be either a POST or DELETE"
"request")
agents = self._decode_response(resp)
agents = self._decode_response_bulk(agents)
return agents | python | def _create_and_send_json_bulk(self, payload, req_url, request_type="POST"):
# Extra header in addition to the main session's
ct_header = {"Content-Type": "application/json; charset=utf-8"}
try:
json_pl = json.dumps(payload)
except TypeError as err:
raise CraftAiBadRequestError("Error while dumping the payload into json"
"format when converting it for the bulk request. {}"
.format(err.__str__()))
if request_type == "POST":
resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl)
elif request_type == "DELETE":
resp = self._requests_session.delete(req_url, headers=ct_header, data=json_pl)
else:
raise CraftAiBadRequestError("Request for the bulk API should be either a POST or DELETE"
"request")
agents = self._decode_response(resp)
agents = self._decode_response_bulk(agents)
return agents | [
"def",
"_create_and_send_json_bulk",
"(",
"self",
",",
"payload",
",",
"req_url",
",",
"request_type",
"=",
"\"POST\"",
")",
":",
"# Extra header in addition to the main session's",
"ct_header",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json; charset=utf-8\"",
"}",
... | Create a json, do a request to the URL and process the response.
:param list payload: contains the informations necessary for the action.
It's a list of dictionnary.
:param str req_url: URL to request with the payload.
:param str request_type: type of request, either "POST" or "DELETE".
:default request_type: "POST".
:return: response of the request.
:rtype: list of dict.
:raises CraftAiBadRequestError: if the payload doesn't have the
correct form to be transformed into a json or request_type is
neither "POST" or "DELETE". | [
"Create",
"a",
"json",
"do",
"a",
"request",
"to",
"the",
"URL",
"and",
"process",
"the",
"response",
"."
] | 8bc1a9038511540930371aacfdde0f4040e08f24 | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L807-L844 |
25,228 | Shizmob/pydle | pydle/features/ctcp.py | construct_ctcp | def construct_ctcp(*parts):
""" Construct CTCP message. """
message = ' '.join(parts)
message = message.replace('\0', CTCP_ESCAPE_CHAR + '0')
message = message.replace('\n', CTCP_ESCAPE_CHAR + 'n')
message = message.replace('\r', CTCP_ESCAPE_CHAR + 'r')
message = message.replace(CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR)
return CTCP_DELIMITER + message + CTCP_DELIMITER | python | def construct_ctcp(*parts):
message = ' '.join(parts)
message = message.replace('\0', CTCP_ESCAPE_CHAR + '0')
message = message.replace('\n', CTCP_ESCAPE_CHAR + 'n')
message = message.replace('\r', CTCP_ESCAPE_CHAR + 'r')
message = message.replace(CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR)
return CTCP_DELIMITER + message + CTCP_DELIMITER | [
"def",
"construct_ctcp",
"(",
"*",
"parts",
")",
":",
"message",
"=",
"' '",
".",
"join",
"(",
"parts",
")",
"message",
"=",
"message",
".",
"replace",
"(",
"'\\0'",
",",
"CTCP_ESCAPE_CHAR",
"+",
"'0'",
")",
"message",
"=",
"message",
".",
"replace",
"... | Construct CTCP message. | [
"Construct",
"CTCP",
"message",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L105-L112 |
25,229 | Shizmob/pydle | pydle/features/ctcp.py | parse_ctcp | def parse_ctcp(query):
""" Strip and de-quote CTCP messages. """
query = query.strip(CTCP_DELIMITER)
query = query.replace(CTCP_ESCAPE_CHAR + '0', '\0')
query = query.replace(CTCP_ESCAPE_CHAR + 'n', '\n')
query = query.replace(CTCP_ESCAPE_CHAR + 'r', '\r')
query = query.replace(CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR)
if ' ' in query:
return query.split(' ', 1)
return query, None | python | def parse_ctcp(query):
query = query.strip(CTCP_DELIMITER)
query = query.replace(CTCP_ESCAPE_CHAR + '0', '\0')
query = query.replace(CTCP_ESCAPE_CHAR + 'n', '\n')
query = query.replace(CTCP_ESCAPE_CHAR + 'r', '\r')
query = query.replace(CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR)
if ' ' in query:
return query.split(' ', 1)
return query, None | [
"def",
"parse_ctcp",
"(",
"query",
")",
":",
"query",
"=",
"query",
".",
"strip",
"(",
"CTCP_DELIMITER",
")",
"query",
"=",
"query",
".",
"replace",
"(",
"CTCP_ESCAPE_CHAR",
"+",
"'0'",
",",
"'\\0'",
")",
"query",
"=",
"query",
".",
"replace",
"(",
"CT... | Strip and de-quote CTCP messages. | [
"Strip",
"and",
"de",
"-",
"quote",
"CTCP",
"messages",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L114-L123 |
25,230 | Shizmob/pydle | pydle/features/ctcp.py | CTCPSupport.on_ctcp_version | async def on_ctcp_version(self, by, target, contents):
""" Built-in CTCP version as some networks seem to require it. """
import pydle
version = '{name} v{ver}'.format(name=pydle.__name__, ver=pydle.__version__)
self.ctcp_reply(by, 'VERSION', version) | python | async def on_ctcp_version(self, by, target, contents):
import pydle
version = '{name} v{ver}'.format(name=pydle.__name__, ver=pydle.__version__)
self.ctcp_reply(by, 'VERSION', version) | [
"async",
"def",
"on_ctcp_version",
"(",
"self",
",",
"by",
",",
"target",
",",
"contents",
")",
":",
"import",
"pydle",
"version",
"=",
"'{name} v{ver}'",
".",
"format",
"(",
"name",
"=",
"pydle",
".",
"__name__",
",",
"ver",
"=",
"pydle",
".",
"__versio... | Built-in CTCP version as some networks seem to require it. | [
"Built",
"-",
"in",
"CTCP",
"version",
"as",
"some",
"networks",
"seem",
"to",
"require",
"it",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L34-L39 |
25,231 | Shizmob/pydle | pydle/features/ctcp.py | CTCPSupport.ctcp | async def ctcp(self, target, query, contents=None):
""" Send a CTCP request to a target. """
if self.is_channel(target) and not self.in_channel(target):
raise client.NotInChannel(target)
await self.message(target, construct_ctcp(query, contents)) | python | async def ctcp(self, target, query, contents=None):
if self.is_channel(target) and not self.in_channel(target):
raise client.NotInChannel(target)
await self.message(target, construct_ctcp(query, contents)) | [
"async",
"def",
"ctcp",
"(",
"self",
",",
"target",
",",
"query",
",",
"contents",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_channel",
"(",
"target",
")",
"and",
"not",
"self",
".",
"in_channel",
"(",
"target",
")",
":",
"raise",
"client",
".",
... | Send a CTCP request to a target. | [
"Send",
"a",
"CTCP",
"request",
"to",
"a",
"target",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L44-L49 |
25,232 | Shizmob/pydle | pydle/features/ctcp.py | CTCPSupport.ctcp_reply | async def ctcp_reply(self, target, query, response):
""" Send a CTCP reply to a target. """
if self.is_channel(target) and not self.in_channel(target):
raise client.NotInChannel(target)
await self.notice(target, construct_ctcp(query, response)) | python | async def ctcp_reply(self, target, query, response):
if self.is_channel(target) and not self.in_channel(target):
raise client.NotInChannel(target)
await self.notice(target, construct_ctcp(query, response)) | [
"async",
"def",
"ctcp_reply",
"(",
"self",
",",
"target",
",",
"query",
",",
"response",
")",
":",
"if",
"self",
".",
"is_channel",
"(",
"target",
")",
"and",
"not",
"self",
".",
"in_channel",
"(",
"target",
")",
":",
"raise",
"client",
".",
"NotInChan... | Send a CTCP reply to a target. | [
"Send",
"a",
"CTCP",
"reply",
"to",
"a",
"target",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L51-L56 |
25,233 | Shizmob/pydle | pydle/features/ctcp.py | CTCPSupport.on_raw_privmsg | async def on_raw_privmsg(self, message):
""" Modify PRIVMSG to redirect CTCP messages. """
nick, metadata = self._parse_user(message.source)
target, msg = message.params
if is_ctcp(msg):
self._sync_user(nick, metadata)
type, contents = parse_ctcp(msg)
# Find dedicated handler if it exists.
attr = 'on_ctcp_' + pydle.protocol.identifierify(type)
if hasattr(self, attr):
await getattr(self, attr)(nick, target, contents)
# Invoke global handler.
await self.on_ctcp(nick, target, type, contents)
else:
await super().on_raw_privmsg(message) | python | async def on_raw_privmsg(self, message):
nick, metadata = self._parse_user(message.source)
target, msg = message.params
if is_ctcp(msg):
self._sync_user(nick, metadata)
type, contents = parse_ctcp(msg)
# Find dedicated handler if it exists.
attr = 'on_ctcp_' + pydle.protocol.identifierify(type)
if hasattr(self, attr):
await getattr(self, attr)(nick, target, contents)
# Invoke global handler.
await self.on_ctcp(nick, target, type, contents)
else:
await super().on_raw_privmsg(message) | [
"async",
"def",
"on_raw_privmsg",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"target",
",",
"msg",
"=",
"message",
".",
"params",
"if",
"is_ctcp",
"(",
"msg",
")"... | Modify PRIVMSG to redirect CTCP messages. | [
"Modify",
"PRIVMSG",
"to",
"redirect",
"CTCP",
"messages",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L61-L77 |
25,234 | Shizmob/pydle | pydle/features/ctcp.py | CTCPSupport.on_raw_notice | async def on_raw_notice(self, message):
""" Modify NOTICE to redirect CTCP messages. """
nick, metadata = self._parse_user(message.source)
target, msg = message.params
if is_ctcp(msg):
self._sync_user(nick, metadata)
type, response = parse_ctcp(msg)
# Find dedicated handler if it exists.
attr = 'on_ctcp_' + pydle.protocol.identifierify(type) + '_reply'
if hasattr(self, attr):
await getattr(self, attr)(user, target, response)
# Invoke global handler.
await self.on_ctcp_reply(user, target, type, response)
else:
await super().on_raw_notice(message) | python | async def on_raw_notice(self, message):
nick, metadata = self._parse_user(message.source)
target, msg = message.params
if is_ctcp(msg):
self._sync_user(nick, metadata)
type, response = parse_ctcp(msg)
# Find dedicated handler if it exists.
attr = 'on_ctcp_' + pydle.protocol.identifierify(type) + '_reply'
if hasattr(self, attr):
await getattr(self, attr)(user, target, response)
# Invoke global handler.
await self.on_ctcp_reply(user, target, type, response)
else:
await super().on_raw_notice(message) | [
"async",
"def",
"on_raw_notice",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"target",
",",
"msg",
"=",
"message",
".",
"params",
"if",
"is_ctcp",
"(",
"msg",
")",... | Modify NOTICE to redirect CTCP messages. | [
"Modify",
"NOTICE",
"to",
"redirect",
"CTCP",
"messages",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L80-L96 |
25,235 | Shizmob/pydle | pydle/features/ircv3/cap.py | CapabilityNegotiationSupport._register | async def _register(self):
""" Hijack registration to send a CAP LS first. """
if self.registered:
self.logger.debug("skipping cap registration, already registered!")
return
# Ask server to list capabilities.
await self.rawmsg('CAP', 'LS', '302')
# Register as usual.
await super()._register() | python | async def _register(self):
if self.registered:
self.logger.debug("skipping cap registration, already registered!")
return
# Ask server to list capabilities.
await self.rawmsg('CAP', 'LS', '302')
# Register as usual.
await super()._register() | [
"async",
"def",
"_register",
"(",
"self",
")",
":",
"if",
"self",
".",
"registered",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"skipping cap registration, already registered!\"",
")",
"return",
"# Ask server to list capabilities.",
"await",
"self",
".",
"rawm... | Hijack registration to send a CAP LS first. | [
"Hijack",
"registration",
"to",
"send",
"a",
"CAP",
"LS",
"first",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L31-L41 |
25,236 | Shizmob/pydle | pydle/features/ircv3/cap.py | CapabilityNegotiationSupport._capability_negotiated | async def _capability_negotiated(self, capab):
""" Mark capability as negotiated, and end negotiation if we're done. """
self._capabilities_negotiating.discard(capab)
if not self._capabilities_requested and not self._capabilities_negotiating:
await self.rawmsg('CAP', 'END') | python | async def _capability_negotiated(self, capab):
self._capabilities_negotiating.discard(capab)
if not self._capabilities_requested and not self._capabilities_negotiating:
await self.rawmsg('CAP', 'END') | [
"async",
"def",
"_capability_negotiated",
"(",
"self",
",",
"capab",
")",
":",
"self",
".",
"_capabilities_negotiating",
".",
"discard",
"(",
"capab",
")",
"if",
"not",
"self",
".",
"_capabilities_requested",
"and",
"not",
"self",
".",
"_capabilities_negotiating",... | Mark capability as negotiated, and end negotiation if we're done. | [
"Mark",
"capability",
"as",
"negotiated",
"and",
"end",
"negotiation",
"if",
"we",
"re",
"done",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L55-L60 |
25,237 | Shizmob/pydle | pydle/features/ircv3/cap.py | CapabilityNegotiationSupport.on_raw_cap | async def on_raw_cap(self, message):
""" Handle CAP message. """
target, subcommand = message.params[:2]
params = message.params[2:]
# Call handler.
attr = 'on_raw_cap_' + pydle.protocol.identifierify(subcommand)
if hasattr(self, attr):
await getattr(self, attr)(params)
else:
self.logger.warning('Unknown CAP subcommand sent from server: %s', subcommand) | python | async def on_raw_cap(self, message):
target, subcommand = message.params[:2]
params = message.params[2:]
# Call handler.
attr = 'on_raw_cap_' + pydle.protocol.identifierify(subcommand)
if hasattr(self, attr):
await getattr(self, attr)(params)
else:
self.logger.warning('Unknown CAP subcommand sent from server: %s', subcommand) | [
"async",
"def",
"on_raw_cap",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"subcommand",
"=",
"message",
".",
"params",
"[",
":",
"2",
"]",
"params",
"=",
"message",
".",
"params",
"[",
"2",
":",
"]",
"# Call handler.",
"attr",
"=",
"'on_raw_c... | Handle CAP message. | [
"Handle",
"CAP",
"message",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L65-L75 |
25,238 | Shizmob/pydle | pydle/features/ircv3/cap.py | CapabilityNegotiationSupport.on_raw_cap_ls | async def on_raw_cap_ls(self, params):
""" Update capability mapping. Request capabilities. """
to_request = set()
for capab in params[0].split():
capab, value = self._capability_normalize(capab)
# Only process new capabilities.
if capab in self._capabilities:
continue
# Check if we support the capability.
attr = 'on_capability_' + pydle.protocol.identifierify(capab) + '_available'
supported = (await getattr(self, attr)(value)) if hasattr(self, attr) else False
if supported:
if isinstance(supported, str):
to_request.add(capab + CAPABILITY_VALUE_DIVIDER + supported)
else:
to_request.add(capab)
else:
self._capabilities[capab] = False
if to_request:
# Request some capabilities.
self._capabilities_requested.update(x.split(CAPABILITY_VALUE_DIVIDER, 1)[0] for x in to_request)
await self.rawmsg('CAP', 'REQ', ' '.join(to_request))
else:
# No capabilities requested, end negotiation.
await self.rawmsg('CAP', 'END') | python | async def on_raw_cap_ls(self, params):
to_request = set()
for capab in params[0].split():
capab, value = self._capability_normalize(capab)
# Only process new capabilities.
if capab in self._capabilities:
continue
# Check if we support the capability.
attr = 'on_capability_' + pydle.protocol.identifierify(capab) + '_available'
supported = (await getattr(self, attr)(value)) if hasattr(self, attr) else False
if supported:
if isinstance(supported, str):
to_request.add(capab + CAPABILITY_VALUE_DIVIDER + supported)
else:
to_request.add(capab)
else:
self._capabilities[capab] = False
if to_request:
# Request some capabilities.
self._capabilities_requested.update(x.split(CAPABILITY_VALUE_DIVIDER, 1)[0] for x in to_request)
await self.rawmsg('CAP', 'REQ', ' '.join(to_request))
else:
# No capabilities requested, end negotiation.
await self.rawmsg('CAP', 'END') | [
"async",
"def",
"on_raw_cap_ls",
"(",
"self",
",",
"params",
")",
":",
"to_request",
"=",
"set",
"(",
")",
"for",
"capab",
"in",
"params",
"[",
"0",
"]",
".",
"split",
"(",
")",
":",
"capab",
",",
"value",
"=",
"self",
".",
"_capability_normalize",
"... | Update capability mapping. Request capabilities. | [
"Update",
"capability",
"mapping",
".",
"Request",
"capabilities",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L77-L106 |
25,239 | Shizmob/pydle | pydle/features/ircv3/cap.py | CapabilityNegotiationSupport.on_raw_cap_list | async def on_raw_cap_list(self, params):
""" Update active capabilities. """
self._capabilities = { capab: False for capab in self._capabilities }
for capab in params[0].split():
capab, value = self._capability_normalize(capab)
self._capabilities[capab] = value if value else True | python | async def on_raw_cap_list(self, params):
self._capabilities = { capab: False for capab in self._capabilities }
for capab in params[0].split():
capab, value = self._capability_normalize(capab)
self._capabilities[capab] = value if value else True | [
"async",
"def",
"on_raw_cap_list",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"_capabilities",
"=",
"{",
"capab",
":",
"False",
"for",
"capab",
"in",
"self",
".",
"_capabilities",
"}",
"for",
"capab",
"in",
"params",
"[",
"0",
"]",
".",
"split"... | Update active capabilities. | [
"Update",
"active",
"capabilities",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L108-L114 |
25,240 | Shizmob/pydle | pydle/features/ircv3/cap.py | CapabilityNegotiationSupport.on_raw_410 | async def on_raw_410(self, message):
""" Unknown CAP subcommand or CAP error. Force-end negotiations. """
self.logger.error('Server sent "Unknown CAP subcommand: %s". Aborting capability negotiation.', message.params[0])
self._capabilities_requested = set()
self._capabilities_negotiating = set()
await self.rawmsg('CAP', 'END') | python | async def on_raw_410(self, message):
self.logger.error('Server sent "Unknown CAP subcommand: %s". Aborting capability negotiation.', message.params[0])
self._capabilities_requested = set()
self._capabilities_negotiating = set()
await self.rawmsg('CAP', 'END') | [
"async",
"def",
"on_raw_410",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Server sent \"Unknown CAP subcommand: %s\". Aborting capability negotiation.'",
",",
"message",
".",
"params",
"[",
"0",
"]",
")",
"self",
".",
"_capab... | Unknown CAP subcommand or CAP error. Force-end negotiations. | [
"Unknown",
"CAP",
"subcommand",
"or",
"CAP",
"error",
".",
"Force",
"-",
"end",
"negotiations",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L179-L185 |
25,241 | Shizmob/pydle | pydle/features/ircv3/sasl.py | SASLSupport._sasl_start | async def _sasl_start(self, mechanism):
""" Initiate SASL authentication. """
# The rest will be handled in on_raw_authenticate()/_sasl_respond().
await self.rawmsg('AUTHENTICATE', mechanism)
# create a partial, required for our callback to get the kwarg
_sasl_partial = partial(self._sasl_abort, timeout=True)
self._sasl_timer = self.eventloop.call_later(self.SASL_TIMEOUT, _sasl_partial) | python | async def _sasl_start(self, mechanism):
# The rest will be handled in on_raw_authenticate()/_sasl_respond().
await self.rawmsg('AUTHENTICATE', mechanism)
# create a partial, required for our callback to get the kwarg
_sasl_partial = partial(self._sasl_abort, timeout=True)
self._sasl_timer = self.eventloop.call_later(self.SASL_TIMEOUT, _sasl_partial) | [
"async",
"def",
"_sasl_start",
"(",
"self",
",",
"mechanism",
")",
":",
"# The rest will be handled in on_raw_authenticate()/_sasl_respond().",
"await",
"self",
".",
"rawmsg",
"(",
"'AUTHENTICATE'",
",",
"mechanism",
")",
"# create a partial, required for our callback to get th... | Initiate SASL authentication. | [
"Initiate",
"SASL",
"authentication",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L45-L51 |
25,242 | Shizmob/pydle | pydle/features/ircv3/sasl.py | SASLSupport._sasl_abort | async def _sasl_abort(self, timeout=False):
""" Abort SASL authentication. """
if timeout:
self.logger.error('SASL authentication timed out: aborting.')
else:
self.logger.error('SASL authentication aborted.')
if self._sasl_timer:
self._sasl_timer.cancel()
self._sasl_timer = None
# We're done here.
await self.rawmsg('AUTHENTICATE', ABORT_MESSAGE)
await self._capability_negotiated('sasl') | python | async def _sasl_abort(self, timeout=False):
if timeout:
self.logger.error('SASL authentication timed out: aborting.')
else:
self.logger.error('SASL authentication aborted.')
if self._sasl_timer:
self._sasl_timer.cancel()
self._sasl_timer = None
# We're done here.
await self.rawmsg('AUTHENTICATE', ABORT_MESSAGE)
await self._capability_negotiated('sasl') | [
"async",
"def",
"_sasl_abort",
"(",
"self",
",",
"timeout",
"=",
"False",
")",
":",
"if",
"timeout",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'SASL authentication timed out: aborting.'",
")",
"else",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'... | Abort SASL authentication. | [
"Abort",
"SASL",
"authentication",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L53-L67 |
25,243 | Shizmob/pydle | pydle/features/ircv3/sasl.py | SASLSupport._sasl_end | async def _sasl_end(self):
""" Finalize SASL authentication. """
if self._sasl_timer:
self._sasl_timer.cancel()
self._sasl_timer = None
await self._capability_negotiated('sasl') | python | async def _sasl_end(self):
if self._sasl_timer:
self._sasl_timer.cancel()
self._sasl_timer = None
await self._capability_negotiated('sasl') | [
"async",
"def",
"_sasl_end",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sasl_timer",
":",
"self",
".",
"_sasl_timer",
".",
"cancel",
"(",
")",
"self",
".",
"_sasl_timer",
"=",
"None",
"await",
"self",
".",
"_capability_negotiated",
"(",
"'sasl'",
")"
] | Finalize SASL authentication. | [
"Finalize",
"SASL",
"authentication",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L69-L74 |
25,244 | Shizmob/pydle | pydle/features/ircv3/sasl.py | SASLSupport._sasl_respond | async def _sasl_respond(self):
""" Respond to SASL challenge with response. """
# Formulate a response.
if self._sasl_client:
try:
response = self._sasl_client.process(self._sasl_challenge)
except puresasl.SASLError:
response = None
if response is None:
self.logger.warning('SASL challenge processing failed: aborting SASL authentication.')
await self._sasl_abort()
else:
response = b''
response = base64.b64encode(response).decode(self.encoding)
to_send = len(response)
self._sasl_challenge = b''
# Send response in chunks.
while to_send > 0:
await self.rawmsg('AUTHENTICATE', response[:RESPONSE_LIMIT])
response = response[RESPONSE_LIMIT:]
to_send -= RESPONSE_LIMIT
# If our message fit exactly in SASL_RESPOSE_LIMIT-byte chunks, send an empty message to indicate we're done.
if to_send == 0:
await self.rawmsg('AUTHENTICATE', EMPTY_MESSAGE) | python | async def _sasl_respond(self):
# Formulate a response.
if self._sasl_client:
try:
response = self._sasl_client.process(self._sasl_challenge)
except puresasl.SASLError:
response = None
if response is None:
self.logger.warning('SASL challenge processing failed: aborting SASL authentication.')
await self._sasl_abort()
else:
response = b''
response = base64.b64encode(response).decode(self.encoding)
to_send = len(response)
self._sasl_challenge = b''
# Send response in chunks.
while to_send > 0:
await self.rawmsg('AUTHENTICATE', response[:RESPONSE_LIMIT])
response = response[RESPONSE_LIMIT:]
to_send -= RESPONSE_LIMIT
# If our message fit exactly in SASL_RESPOSE_LIMIT-byte chunks, send an empty message to indicate we're done.
if to_send == 0:
await self.rawmsg('AUTHENTICATE', EMPTY_MESSAGE) | [
"async",
"def",
"_sasl_respond",
"(",
"self",
")",
":",
"# Formulate a response.",
"if",
"self",
".",
"_sasl_client",
":",
"try",
":",
"response",
"=",
"self",
".",
"_sasl_client",
".",
"process",
"(",
"self",
".",
"_sasl_challenge",
")",
"except",
"puresasl",... | Respond to SASL challenge with response. | [
"Respond",
"to",
"SASL",
"challenge",
"with",
"response",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L76-L103 |
25,245 | Shizmob/pydle | pydle/features/ircv3/sasl.py | SASLSupport.on_capability_sasl_available | async def on_capability_sasl_available(self, value):
""" Check whether or not SASL is available. """
if value:
self._sasl_mechanisms = value.upper().split(',')
else:
self._sasl_mechanisms = None
if self.sasl_mechanism == 'EXTERNAL' or (self.sasl_username and self.sasl_password):
if self.sasl_mechanism == 'EXTERNAL' or puresasl:
return True
self.logger.warning('SASL credentials set but puresasl module not found: not initiating SASL authentication.')
return False | python | async def on_capability_sasl_available(self, value):
if value:
self._sasl_mechanisms = value.upper().split(',')
else:
self._sasl_mechanisms = None
if self.sasl_mechanism == 'EXTERNAL' or (self.sasl_username and self.sasl_password):
if self.sasl_mechanism == 'EXTERNAL' or puresasl:
return True
self.logger.warning('SASL credentials set but puresasl module not found: not initiating SASL authentication.')
return False | [
"async",
"def",
"on_capability_sasl_available",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"self",
".",
"_sasl_mechanisms",
"=",
"value",
".",
"upper",
"(",
")",
".",
"split",
"(",
"','",
")",
"else",
":",
"self",
".",
"_sasl_mechanisms",
"... | Check whether or not SASL is available. | [
"Check",
"whether",
"or",
"not",
"SASL",
"is",
"available",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L108-L119 |
25,246 | Shizmob/pydle | pydle/features/ircv3/sasl.py | SASLSupport.on_capability_sasl_enabled | async def on_capability_sasl_enabled(self):
""" Start SASL authentication. """
if self.sasl_mechanism:
if self._sasl_mechanisms and self.sasl_mechanism not in self._sasl_mechanisms:
self.logger.warning('Requested SASL mechanism is not in server mechanism list: aborting SASL authentication.')
return cap.failed
mechanisms = [self.sasl_mechanism]
else:
mechanisms = self._sasl_mechanisms or ['PLAIN']
if mechanisms == ['EXTERNAL']:
mechanism = 'EXTERNAL'
else:
self._sasl_client = puresasl.client.SASLClient(self.connection.hostname, 'irc',
username=self.sasl_username,
password=self.sasl_password,
identity=self.sasl_identity
)
try:
self._sasl_client.choose_mechanism(mechanisms, allow_anonymous=False)
except puresasl.SASLError:
self.logger.exception('SASL mechanism choice failed: aborting SASL authentication.')
return cap.FAILED
mechanism = self._sasl_client.mechanism.upper()
# Initialize SASL.
await self._sasl_start(mechanism)
# Tell caller we need more time, and to not end capability negotiation just yet.
return cap.NEGOTIATING | python | async def on_capability_sasl_enabled(self):
if self.sasl_mechanism:
if self._sasl_mechanisms and self.sasl_mechanism not in self._sasl_mechanisms:
self.logger.warning('Requested SASL mechanism is not in server mechanism list: aborting SASL authentication.')
return cap.failed
mechanisms = [self.sasl_mechanism]
else:
mechanisms = self._sasl_mechanisms or ['PLAIN']
if mechanisms == ['EXTERNAL']:
mechanism = 'EXTERNAL'
else:
self._sasl_client = puresasl.client.SASLClient(self.connection.hostname, 'irc',
username=self.sasl_username,
password=self.sasl_password,
identity=self.sasl_identity
)
try:
self._sasl_client.choose_mechanism(mechanisms, allow_anonymous=False)
except puresasl.SASLError:
self.logger.exception('SASL mechanism choice failed: aborting SASL authentication.')
return cap.FAILED
mechanism = self._sasl_client.mechanism.upper()
# Initialize SASL.
await self._sasl_start(mechanism)
# Tell caller we need more time, and to not end capability negotiation just yet.
return cap.NEGOTIATING | [
"async",
"def",
"on_capability_sasl_enabled",
"(",
"self",
")",
":",
"if",
"self",
".",
"sasl_mechanism",
":",
"if",
"self",
".",
"_sasl_mechanisms",
"and",
"self",
".",
"sasl_mechanism",
"not",
"in",
"self",
".",
"_sasl_mechanisms",
":",
"self",
".",
"logger"... | Start SASL authentication. | [
"Start",
"SASL",
"authentication",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L121-L150 |
25,247 | Shizmob/pydle | pydle/features/ircv3/sasl.py | SASLSupport.on_raw_authenticate | async def on_raw_authenticate(self, message):
""" Received part of the authentication challenge. """
# Cancel timeout timer.
if self._sasl_timer:
self._sasl_timer.cancel()
self._sasl_timer = None
# Add response data.
response = ' '.join(message.params)
if response != EMPTY_MESSAGE:
self._sasl_challenge += base64.b64decode(response)
# If the response ain't exactly SASL_RESPONSE_LIMIT bytes long, it's the end. Process.
if len(response) % RESPONSE_LIMIT > 0:
await self._sasl_respond()
else:
# Response not done yet. Restart timer.
self._sasl_timer = self.eventloop.call_later(self.SASL_TIMEOUT, self._sasl_abort(timeout=True)) | python | async def on_raw_authenticate(self, message):
# Cancel timeout timer.
if self._sasl_timer:
self._sasl_timer.cancel()
self._sasl_timer = None
# Add response data.
response = ' '.join(message.params)
if response != EMPTY_MESSAGE:
self._sasl_challenge += base64.b64decode(response)
# If the response ain't exactly SASL_RESPONSE_LIMIT bytes long, it's the end. Process.
if len(response) % RESPONSE_LIMIT > 0:
await self._sasl_respond()
else:
# Response not done yet. Restart timer.
self._sasl_timer = self.eventloop.call_later(self.SASL_TIMEOUT, self._sasl_abort(timeout=True)) | [
"async",
"def",
"on_raw_authenticate",
"(",
"self",
",",
"message",
")",
":",
"# Cancel timeout timer.",
"if",
"self",
".",
"_sasl_timer",
":",
"self",
".",
"_sasl_timer",
".",
"cancel",
"(",
")",
"self",
".",
"_sasl_timer",
"=",
"None",
"# Add response data.",
... | Received part of the authentication challenge. | [
"Received",
"part",
"of",
"the",
"authentication",
"challenge",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L155-L172 |
25,248 | Shizmob/pydle | pydle/features/ircv3/monitor.py | MonitoringSupport.monitor | def monitor(self, target):
""" Start monitoring the online status of a user. Returns whether or not the server supports monitoring. """
if 'monitor-notify' in self._capabilities and not self.is_monitoring(target):
yield from self.rawmsg('MONITOR', '+', target)
self._monitoring.add(target)
return True
else:
return False | python | def monitor(self, target):
if 'monitor-notify' in self._capabilities and not self.is_monitoring(target):
yield from self.rawmsg('MONITOR', '+', target)
self._monitoring.add(target)
return True
else:
return False | [
"def",
"monitor",
"(",
"self",
",",
"target",
")",
":",
"if",
"'monitor-notify'",
"in",
"self",
".",
"_capabilities",
"and",
"not",
"self",
".",
"is_monitoring",
"(",
"target",
")",
":",
"yield",
"from",
"self",
".",
"rawmsg",
"(",
"'MONITOR'",
",",
"'+'... | Start monitoring the online status of a user. Returns whether or not the server supports monitoring. | [
"Start",
"monitoring",
"the",
"online",
"status",
"of",
"a",
"user",
".",
"Returns",
"whether",
"or",
"not",
"the",
"server",
"supports",
"monitoring",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/monitor.py#L39-L46 |
25,249 | Shizmob/pydle | pydle/features/ircv3/monitor.py | MonitoringSupport.unmonitor | def unmonitor(self, target):
""" Stop monitoring the online status of a user. Returns whether or not the server supports monitoring. """
if 'monitor-notify' in self._capabilities and self.is_monitoring(target):
yield from self.rawmsg('MONITOR', '-', target)
self._monitoring.remove(target)
return True
else:
return False | python | def unmonitor(self, target):
if 'monitor-notify' in self._capabilities and self.is_monitoring(target):
yield from self.rawmsg('MONITOR', '-', target)
self._monitoring.remove(target)
return True
else:
return False | [
"def",
"unmonitor",
"(",
"self",
",",
"target",
")",
":",
"if",
"'monitor-notify'",
"in",
"self",
".",
"_capabilities",
"and",
"self",
".",
"is_monitoring",
"(",
"target",
")",
":",
"yield",
"from",
"self",
".",
"rawmsg",
"(",
"'MONITOR'",
",",
"'-'",
",... | Stop monitoring the online status of a user. Returns whether or not the server supports monitoring. | [
"Stop",
"monitoring",
"the",
"online",
"status",
"of",
"a",
"user",
".",
"Returns",
"whether",
"or",
"not",
"the",
"server",
"supports",
"monitoring",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/monitor.py#L48-L55 |
25,250 | Shizmob/pydle | pydle/features/ircv3/monitor.py | MonitoringSupport.on_raw_730 | async def on_raw_730(self, message):
""" Someone we are monitoring just came online. """
for nick in message.params[1].split(','):
self._create_user(nick)
await self.on_user_online(nickname) | python | async def on_raw_730(self, message):
for nick in message.params[1].split(','):
self._create_user(nick)
await self.on_user_online(nickname) | [
"async",
"def",
"on_raw_730",
"(",
"self",
",",
"message",
")",
":",
"for",
"nick",
"in",
"message",
".",
"params",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
":",
"self",
".",
"_create_user",
"(",
"nick",
")",
"await",
"self",
".",
"on_user_onlin... | Someone we are monitoring just came online. | [
"Someone",
"we",
"are",
"monitoring",
"just",
"came",
"online",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/monitor.py#L78-L82 |
25,251 | Shizmob/pydle | pydle/features/ircv3/monitor.py | MonitoringSupport.on_raw_731 | async def on_raw_731(self, message):
""" Someone we are monitoring got offline. """
for nick in message.params[1].split(','):
self._destroy_user(nick, monitor_override=True)
await self.on_user_offline(nickname) | python | async def on_raw_731(self, message):
for nick in message.params[1].split(','):
self._destroy_user(nick, monitor_override=True)
await self.on_user_offline(nickname) | [
"async",
"def",
"on_raw_731",
"(",
"self",
",",
"message",
")",
":",
"for",
"nick",
"in",
"message",
".",
"params",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
":",
"self",
".",
"_destroy_user",
"(",
"nick",
",",
"monitor_override",
"=",
"True",
")... | Someone we are monitoring got offline. | [
"Someone",
"we",
"are",
"monitoring",
"got",
"offline",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/monitor.py#L84-L88 |
25,252 | Shizmob/pydle | pydle/features/ircv3/ircv3_1.py | IRCv3_1Support.on_raw_account | async def on_raw_account(self, message):
""" Changes in the associated account for a nickname. """
if not self._capabilities.get('account-notify', False):
return
nick, metadata = self._parse_user(message.source)
account = message.params[0]
if nick not in self.users:
return
self._sync_user(nick, metadata)
if account == NO_ACCOUNT:
self._sync_user(nick, { 'account': None, 'identified': False })
else:
self._sync_user(nick, { 'account': account, 'identified': True }) | python | async def on_raw_account(self, message):
if not self._capabilities.get('account-notify', False):
return
nick, metadata = self._parse_user(message.source)
account = message.params[0]
if nick not in self.users:
return
self._sync_user(nick, metadata)
if account == NO_ACCOUNT:
self._sync_user(nick, { 'account': None, 'identified': False })
else:
self._sync_user(nick, { 'account': account, 'identified': True }) | [
"async",
"def",
"on_raw_account",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"_capabilities",
".",
"get",
"(",
"'account-notify'",
",",
"False",
")",
":",
"return",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"mes... | Changes in the associated account for a nickname. | [
"Changes",
"in",
"the",
"associated",
"account",
"for",
"a",
"nickname",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/ircv3_1.py#L52-L67 |
25,253 | Shizmob/pydle | pydle/features/ircv3/ircv3_1.py | IRCv3_1Support.on_raw_away | async def on_raw_away(self, message):
""" Process AWAY messages. """
if 'away-notify' not in self._capabilities or not self._capabilities['away-notify']:
return
nick, metadata = self._parse_user(message.source)
if nick not in self.users:
return
self._sync_user(nick, metadata)
self.users[nick]['away'] = len(message.params) > 0
self.users[nick]['away_message'] = message.params[0] if len(message.params) > 0 else None | python | async def on_raw_away(self, message):
if 'away-notify' not in self._capabilities or not self._capabilities['away-notify']:
return
nick, metadata = self._parse_user(message.source)
if nick not in self.users:
return
self._sync_user(nick, metadata)
self.users[nick]['away'] = len(message.params) > 0
self.users[nick]['away_message'] = message.params[0] if len(message.params) > 0 else None | [
"async",
"def",
"on_raw_away",
"(",
"self",
",",
"message",
")",
":",
"if",
"'away-notify'",
"not",
"in",
"self",
".",
"_capabilities",
"or",
"not",
"self",
".",
"_capabilities",
"[",
"'away-notify'",
"]",
":",
"return",
"nick",
",",
"metadata",
"=",
"self... | Process AWAY messages. | [
"Process",
"AWAY",
"messages",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/ircv3_1.py#L69-L80 |
25,254 | Shizmob/pydle | pydle/features/ircv3/ircv3_1.py | IRCv3_1Support.on_raw_join | async def on_raw_join(self, message):
""" Process extended JOIN messages. """
if 'extended-join' in self._capabilities and self._capabilities['extended-join']:
nick, metadata = self._parse_user(message.source)
channels, account, realname = message.params
self._sync_user(nick, metadata)
# Emit a fake join message.
fakemsg = self._create_message('JOIN', channels, source=message.source)
await super().on_raw_join(fakemsg)
if account == NO_ACCOUNT:
account = None
self.users[nick]['account'] = account
self.users[nick]['realname'] = realname
else:
await super().on_raw_join(message) | python | async def on_raw_join(self, message):
if 'extended-join' in self._capabilities and self._capabilities['extended-join']:
nick, metadata = self._parse_user(message.source)
channels, account, realname = message.params
self._sync_user(nick, metadata)
# Emit a fake join message.
fakemsg = self._create_message('JOIN', channels, source=message.source)
await super().on_raw_join(fakemsg)
if account == NO_ACCOUNT:
account = None
self.users[nick]['account'] = account
self.users[nick]['realname'] = realname
else:
await super().on_raw_join(message) | [
"async",
"def",
"on_raw_join",
"(",
"self",
",",
"message",
")",
":",
"if",
"'extended-join'",
"in",
"self",
".",
"_capabilities",
"and",
"self",
".",
"_capabilities",
"[",
"'extended-join'",
"]",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user"... | Process extended JOIN messages. | [
"Process",
"extended",
"JOIN",
"messages",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/ircv3_1.py#L82-L99 |
25,255 | Shizmob/pydle | pydle/features/ircv3/metadata.py | MetadataSupport.on_raw_metadata | async def on_raw_metadata(self, message):
""" Metadata event. """
target, targetmeta = self._parse_user(message.params[0])
key, visibility, value = message.params[1:4]
if visibility == VISIBLITY_ALL:
visibility = None
if target in self.users:
self._sync_user(target, targetmeta)
await self.on_metadata(target, key, value, visibility=visibility) | python | async def on_raw_metadata(self, message):
target, targetmeta = self._parse_user(message.params[0])
key, visibility, value = message.params[1:4]
if visibility == VISIBLITY_ALL:
visibility = None
if target in self.users:
self._sync_user(target, targetmeta)
await self.on_metadata(target, key, value, visibility=visibility) | [
"async",
"def",
"on_raw_metadata",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"targetmeta",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"params",
"[",
"0",
"]",
")",
"key",
",",
"visibility",
",",
"value",
"=",
"message",
".",
"par... | Metadata event. | [
"Metadata",
"event",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/metadata.py#L56-L65 |
25,256 | Shizmob/pydle | pydle/features/ircv3/metadata.py | MetadataSupport.on_raw_762 | async def on_raw_762(self, message):
""" End of metadata. """
# No way to figure out whose query this belongs to, so make a best guess
# it was the first one.
if not self._metadata_queue:
return
nickname = self._metadata_queue.pop()
future = self._pending['metadata'].pop(nickname)
future.set_result(self._metadata_info.pop(nickname)) | python | async def on_raw_762(self, message):
# No way to figure out whose query this belongs to, so make a best guess
# it was the first one.
if not self._metadata_queue:
return
nickname = self._metadata_queue.pop()
future = self._pending['metadata'].pop(nickname)
future.set_result(self._metadata_info.pop(nickname)) | [
"async",
"def",
"on_raw_762",
"(",
"self",
",",
"message",
")",
":",
"# No way to figure out whose query this belongs to, so make a best guess",
"# it was the first one.",
"if",
"not",
"self",
".",
"_metadata_queue",
":",
"return",
"nickname",
"=",
"self",
".",
"_metadata... | End of metadata. | [
"End",
"of",
"metadata",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/metadata.py#L93-L102 |
25,257 | Shizmob/pydle | pydle/features/ircv3/metadata.py | MetadataSupport.on_raw_765 | async def on_raw_765(self, message):
""" Invalid metadata target. """
target, targetmeta = self._parse_user(message.params[0])
if target not in self._pending['metadata']:
return
if target in self.users:
self._sync_user(target, targetmeta)
self._metadata_queue.remove(target)
del self._metadata_info[target]
future = self._pending['metadata'].pop(target)
future.set_result(None) | python | async def on_raw_765(self, message):
target, targetmeta = self._parse_user(message.params[0])
if target not in self._pending['metadata']:
return
if target in self.users:
self._sync_user(target, targetmeta)
self._metadata_queue.remove(target)
del self._metadata_info[target]
future = self._pending['metadata'].pop(target)
future.set_result(None) | [
"async",
"def",
"on_raw_765",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"targetmeta",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"params",
"[",
"0",
"]",
")",
"if",
"target",
"not",
"in",
"self",
".",
"_pending",
"[",
"'metadata'... | Invalid metadata target. | [
"Invalid",
"metadata",
"target",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/metadata.py#L108-L121 |
25,258 | Shizmob/pydle | pydle/connection.py | Connection.connect | async def connect(self):
""" Connect to target. """
self.tls_context = None
if self.tls:
self.tls_context = self.create_tls_context()
(self.reader, self.writer) = await asyncio.open_connection(
host=self.hostname,
port=self.port,
local_addr=self.source_address,
ssl=self.tls_context,
loop=self.eventloop
) | python | async def connect(self):
self.tls_context = None
if self.tls:
self.tls_context = self.create_tls_context()
(self.reader, self.writer) = await asyncio.open_connection(
host=self.hostname,
port=self.port,
local_addr=self.source_address,
ssl=self.tls_context,
loop=self.eventloop
) | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"tls_context",
"=",
"None",
"if",
"self",
".",
"tls",
":",
"self",
".",
"tls_context",
"=",
"self",
".",
"create_tls_context",
"(",
")",
"(",
"self",
".",
"reader",
",",
"self",
".",
"wri... | Connect to target. | [
"Connect",
"to",
"target",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/connection.py#L41-L54 |
25,259 | Shizmob/pydle | pydle/connection.py | Connection.create_tls_context | def create_tls_context(self):
""" Transform our regular socket into a TLS socket. """
# Create context manually, as we're going to set our own options.
tls_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
# Load client/server certificate.
if self.tls_certificate_file:
tls_context.load_cert_chain(self.tls_certificate_file, self.tls_certificate_keyfile,
password=self.tls_certificate_password)
# Set some relevant options:
# - No server should use SSLv2 or SSLv3 any more, they are outdated and full of security holes. (RFC6176, RFC7568)
# - Disable compression in order to counter the CRIME attack. (https://en.wikipedia.org/wiki/CRIME_%28security_exploit%29)
# - Disable session resumption to maintain perfect forward secrecy. (https://timtaubert.de/blog/2014/11/the-sad-state-of-server-side-tls-session-resumption-implementations/)
for opt in ['NO_SSLv2', 'NO_SSLv3', 'NO_COMPRESSION', 'NO_TICKET']:
if hasattr(ssl, 'OP_' + opt):
tls_context.options |= getattr(ssl, 'OP_' + opt)
# Set TLS verification options.
if self.tls_verify:
# Set our custom verification callback, if the library supports it.
tls_context.set_servername_callback(self.verify_tls)
# Load certificate verification paths.
tls_context.set_default_verify_paths()
if sys.platform in DEFAULT_CA_PATHS and path.isdir(DEFAULT_CA_PATHS[sys.platform]):
tls_context.load_verify_locations(capath=DEFAULT_CA_PATHS[sys.platform])
# If we want to verify the TLS connection, we first need a certicate.
# Check this certificate and its entire chain, if possible, against revocation lists.
tls_context.verify_mode = ssl.CERT_REQUIRED
tls_context.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN
return tls_context | python | def create_tls_context(self):
# Create context manually, as we're going to set our own options.
tls_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
# Load client/server certificate.
if self.tls_certificate_file:
tls_context.load_cert_chain(self.tls_certificate_file, self.tls_certificate_keyfile,
password=self.tls_certificate_password)
# Set some relevant options:
# - No server should use SSLv2 or SSLv3 any more, they are outdated and full of security holes. (RFC6176, RFC7568)
# - Disable compression in order to counter the CRIME attack. (https://en.wikipedia.org/wiki/CRIME_%28security_exploit%29)
# - Disable session resumption to maintain perfect forward secrecy. (https://timtaubert.de/blog/2014/11/the-sad-state-of-server-side-tls-session-resumption-implementations/)
for opt in ['NO_SSLv2', 'NO_SSLv3', 'NO_COMPRESSION', 'NO_TICKET']:
if hasattr(ssl, 'OP_' + opt):
tls_context.options |= getattr(ssl, 'OP_' + opt)
# Set TLS verification options.
if self.tls_verify:
# Set our custom verification callback, if the library supports it.
tls_context.set_servername_callback(self.verify_tls)
# Load certificate verification paths.
tls_context.set_default_verify_paths()
if sys.platform in DEFAULT_CA_PATHS and path.isdir(DEFAULT_CA_PATHS[sys.platform]):
tls_context.load_verify_locations(capath=DEFAULT_CA_PATHS[sys.platform])
# If we want to verify the TLS connection, we first need a certicate.
# Check this certificate and its entire chain, if possible, against revocation lists.
tls_context.verify_mode = ssl.CERT_REQUIRED
tls_context.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN
return tls_context | [
"def",
"create_tls_context",
"(",
"self",
")",
":",
"# Create context manually, as we're going to set our own options.",
"tls_context",
"=",
"ssl",
".",
"SSLContext",
"(",
"ssl",
".",
"PROTOCOL_SSLv23",
")",
"# Load client/server certificate.",
"if",
"self",
".",
"tls_certi... | Transform our regular socket into a TLS socket. | [
"Transform",
"our",
"regular",
"socket",
"into",
"a",
"TLS",
"socket",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/connection.py#L56-L89 |
25,260 | Shizmob/pydle | pydle/connection.py | Connection.disconnect | async def disconnect(self):
""" Disconnect from target. """
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None | python | async def disconnect(self):
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None | [
"async",
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"return",
"self",
".",
"writer",
".",
"close",
"(",
")",
"self",
".",
"reader",
"=",
"None",
"self",
".",
"writer",
"=",
"None"
] | Disconnect from target. | [
"Disconnect",
"from",
"target",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/connection.py#L107-L114 |
25,261 | Shizmob/pydle | pydle/connection.py | Connection.send | async def send(self, data):
""" Add data to send queue. """
self.writer.write(data)
await self.writer.drain() | python | async def send(self, data):
self.writer.write(data)
await self.writer.drain() | [
"async",
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"writer",
".",
"write",
"(",
"data",
")",
"await",
"self",
".",
"writer",
".",
"drain",
"(",
")"
] | Add data to send queue. | [
"Add",
"data",
"to",
"send",
"queue",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/connection.py#L125-L128 |
25,262 | Shizmob/pydle | pydle/protocol.py | identifierify | def identifierify(name):
""" Clean up name so it works for a Python identifier. """
name = name.lower()
name = re.sub('[^a-z0-9]', '_', name)
return name | python | def identifierify(name):
name = name.lower()
name = re.sub('[^a-z0-9]', '_', name)
return name | [
"def",
"identifierify",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"'[^a-z0-9]'",
",",
"'_'",
",",
"name",
")",
"return",
"name"
] | Clean up name so it works for a Python identifier. | [
"Clean",
"up",
"name",
"so",
"it",
"works",
"for",
"a",
"Python",
"identifier",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/protocol.py#L40-L44 |
25,263 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support._register | async def _register(self):
""" Perform IRC connection registration. """
if self.registered:
return
self._registration_attempts += 1
# Don't throttle during registration, most ircds don't care for flooding during registration,
# and it might speed it up significantly.
self.connection.throttle = False
# Password first.
if self.password:
await self.rawmsg('PASS', self.password)
# Then nickname...
await self.set_nickname(self._attempt_nicknames.pop(0))
# And now for the rest of the user information.
await self.rawmsg('USER', self.username, '0', '*', self.realname) | python | async def _register(self):
if self.registered:
return
self._registration_attempts += 1
# Don't throttle during registration, most ircds don't care for flooding during registration,
# and it might speed it up significantly.
self.connection.throttle = False
# Password first.
if self.password:
await self.rawmsg('PASS', self.password)
# Then nickname...
await self.set_nickname(self._attempt_nicknames.pop(0))
# And now for the rest of the user information.
await self.rawmsg('USER', self.username, '0', '*', self.realname) | [
"async",
"def",
"_register",
"(",
"self",
")",
":",
"if",
"self",
".",
"registered",
":",
"return",
"self",
".",
"_registration_attempts",
"+=",
"1",
"# Don't throttle during registration, most ircds don't care for flooding during registration,",
"# and it might speed it up sig... | Perform IRC connection registration. | [
"Perform",
"IRC",
"connection",
"registration",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L199-L216 |
25,264 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support._registration_completed | async def _registration_completed(self, message):
""" We're connected and registered. Receive proper nickname and emit fake NICK message. """
if not self.registered:
# Re-enable throttling.
self.registered = True
self.connection.throttle = True
target = message.params[0]
fakemsg = self._create_message('NICK', target, source=self.nickname)
await self.on_raw_nick(fakemsg) | python | async def _registration_completed(self, message):
if not self.registered:
# Re-enable throttling.
self.registered = True
self.connection.throttle = True
target = message.params[0]
fakemsg = self._create_message('NICK', target, source=self.nickname)
await self.on_raw_nick(fakemsg) | [
"async",
"def",
"_registration_completed",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"registered",
":",
"# Re-enable throttling.",
"self",
".",
"registered",
"=",
"True",
"self",
".",
"connection",
".",
"throttle",
"=",
"True",
"target",... | We're connected and registered. Receive proper nickname and emit fake NICK message. | [
"We",
"re",
"connected",
"and",
"registered",
".",
"Receive",
"proper",
"nickname",
"and",
"emit",
"fake",
"NICK",
"message",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L218-L227 |
25,265 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support._has_message | def _has_message(self):
""" Whether or not we have messages available for processing. """
sep = protocol.MINIMAL_LINE_SEPARATOR.encode(self.encoding)
return sep in self._receive_buffer | python | def _has_message(self):
sep = protocol.MINIMAL_LINE_SEPARATOR.encode(self.encoding)
return sep in self._receive_buffer | [
"def",
"_has_message",
"(",
"self",
")",
":",
"sep",
"=",
"protocol",
".",
"MINIMAL_LINE_SEPARATOR",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
"return",
"sep",
"in",
"self",
".",
"_receive_buffer"
] | Whether or not we have messages available for processing. | [
"Whether",
"or",
"not",
"we",
"have",
"messages",
"available",
"for",
"processing",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L231-L234 |
25,266 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.join | async def join(self, channel, password=None):
""" Join channel, optionally with password. """
if self.in_channel(channel):
raise AlreadyInChannel(channel)
if password:
await self.rawmsg('JOIN', channel, password)
else:
await self.rawmsg('JOIN', channel) | python | async def join(self, channel, password=None):
if self.in_channel(channel):
raise AlreadyInChannel(channel)
if password:
await self.rawmsg('JOIN', channel, password)
else:
await self.rawmsg('JOIN', channel) | [
"async",
"def",
"join",
"(",
"self",
",",
"channel",
",",
"password",
"=",
"None",
")",
":",
"if",
"self",
".",
"in_channel",
"(",
"channel",
")",
":",
"raise",
"AlreadyInChannel",
"(",
"channel",
")",
"if",
"password",
":",
"await",
"self",
".",
"rawm... | Join channel, optionally with password. | [
"Join",
"channel",
"optionally",
"with",
"password",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L254-L262 |
25,267 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.part | async def part(self, channel, message=None):
""" Leave channel, optionally with message. """
if not self.in_channel(channel):
raise NotInChannel(channel)
# Message seems to be an extension to the spec.
if message:
await self.rawmsg('PART', channel, message)
else:
await self.rawmsg('PART', channel) | python | async def part(self, channel, message=None):
if not self.in_channel(channel):
raise NotInChannel(channel)
# Message seems to be an extension to the spec.
if message:
await self.rawmsg('PART', channel, message)
else:
await self.rawmsg('PART', channel) | [
"async",
"def",
"part",
"(",
"self",
",",
"channel",
",",
"message",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"in_channel",
"(",
"channel",
")",
":",
"raise",
"NotInChannel",
"(",
"channel",
")",
"# Message seems to be an extension to the spec.",
"if",... | Leave channel, optionally with message. | [
"Leave",
"channel",
"optionally",
"with",
"message",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L264-L273 |
25,268 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.kick | async def kick(self, channel, target, reason=None):
""" Kick user from channel. """
if not self.in_channel(channel):
raise NotInChannel(channel)
if reason:
await self.rawmsg('KICK', channel, target, reason)
else:
await self.rawmsg('KICK', channel, target) | python | async def kick(self, channel, target, reason=None):
if not self.in_channel(channel):
raise NotInChannel(channel)
if reason:
await self.rawmsg('KICK', channel, target, reason)
else:
await self.rawmsg('KICK', channel, target) | [
"async",
"def",
"kick",
"(",
"self",
",",
"channel",
",",
"target",
",",
"reason",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"in_channel",
"(",
"channel",
")",
":",
"raise",
"NotInChannel",
"(",
"channel",
")",
"if",
"reason",
":",
"await",
"s... | Kick user from channel. | [
"Kick",
"user",
"from",
"channel",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L275-L283 |
25,269 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.unban | async def unban(self, channel, target, range=0):
"""
Unban user from channel. Target can be either a user or a host.
See ban documentation for the range parameter.
"""
if target in self.users:
host = self.users[target]['hostname']
else:
host = target
host = self._format_host_range(host, range)
mask = self._format_host_mask('*', '*', host)
await self.rawmsg('MODE', channel, '-b', mask) | python | async def unban(self, channel, target, range=0):
if target in self.users:
host = self.users[target]['hostname']
else:
host = target
host = self._format_host_range(host, range)
mask = self._format_host_mask('*', '*', host)
await self.rawmsg('MODE', channel, '-b', mask) | [
"async",
"def",
"unban",
"(",
"self",
",",
"channel",
",",
"target",
",",
"range",
"=",
"0",
")",
":",
"if",
"target",
"in",
"self",
".",
"users",
":",
"host",
"=",
"self",
".",
"users",
"[",
"target",
"]",
"[",
"'hostname'",
"]",
"else",
":",
"h... | Unban user from channel. Target can be either a user or a host.
See ban documentation for the range parameter. | [
"Unban",
"user",
"from",
"channel",
".",
"Target",
"can",
"be",
"either",
"a",
"user",
"or",
"a",
"host",
".",
"See",
"ban",
"documentation",
"for",
"the",
"range",
"parameter",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L301-L313 |
25,270 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.kickban | async def kickban(self, channel, target, reason=None, range=0):
"""
Kick and ban user from channel.
"""
await self.ban(channel, target, range)
await self.kick(channel, target, reason) | python | async def kickban(self, channel, target, reason=None, range=0):
await self.ban(channel, target, range)
await self.kick(channel, target, reason) | [
"async",
"def",
"kickban",
"(",
"self",
",",
"channel",
",",
"target",
",",
"reason",
"=",
"None",
",",
"range",
"=",
"0",
")",
":",
"await",
"self",
".",
"ban",
"(",
"channel",
",",
"target",
",",
"range",
")",
"await",
"self",
".",
"kick",
"(",
... | Kick and ban user from channel. | [
"Kick",
"and",
"ban",
"user",
"from",
"channel",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L315-L320 |
25,271 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.quit | async def quit(self, message=None):
""" Quit network. """
if message is None:
message = self.DEFAULT_QUIT_MESSAGE
await self.rawmsg('QUIT', message)
await self.disconnect(expected=True) | python | async def quit(self, message=None):
if message is None:
message = self.DEFAULT_QUIT_MESSAGE
await self.rawmsg('QUIT', message)
await self.disconnect(expected=True) | [
"async",
"def",
"quit",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"self",
".",
"DEFAULT_QUIT_MESSAGE",
"await",
"self",
".",
"rawmsg",
"(",
"'QUIT'",
",",
"message",
")",
"await",
"self",
".... | Quit network. | [
"Quit",
"network",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L322-L328 |
25,272 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.cycle | async def cycle(self, channel):
""" Rejoin channel. """
if not self.in_channel(channel):
raise NotInChannel(channel)
password = self.channels[channel]['password']
await self.part(channel)
await self.join(channel, password) | python | async def cycle(self, channel):
if not self.in_channel(channel):
raise NotInChannel(channel)
password = self.channels[channel]['password']
await self.part(channel)
await self.join(channel, password) | [
"async",
"def",
"cycle",
"(",
"self",
",",
"channel",
")",
":",
"if",
"not",
"self",
".",
"in_channel",
"(",
"channel",
")",
":",
"raise",
"NotInChannel",
"(",
"channel",
")",
"password",
"=",
"self",
".",
"channels",
"[",
"channel",
"]",
"[",
"'passwo... | Rejoin channel. | [
"Rejoin",
"channel",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L330-L337 |
25,273 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.message | async def message(self, target, message):
""" Message channel or user. """
hostmask = self._format_user_mask(self.nickname)
# Leeway.
chunklen = protocol.MESSAGE_LENGTH_LIMIT - len(
'{hostmask} PRIVMSG {target} :'.format(hostmask=hostmask, target=target)) - 25
for line in message.replace('\r', '').split('\n'):
for chunk in chunkify(line, chunklen):
# Some IRC servers respond with "412 Bot :No text to send" on empty messages.
await self.rawmsg('PRIVMSG', target, chunk or ' ') | python | async def message(self, target, message):
hostmask = self._format_user_mask(self.nickname)
# Leeway.
chunklen = protocol.MESSAGE_LENGTH_LIMIT - len(
'{hostmask} PRIVMSG {target} :'.format(hostmask=hostmask, target=target)) - 25
for line in message.replace('\r', '').split('\n'):
for chunk in chunkify(line, chunklen):
# Some IRC servers respond with "412 Bot :No text to send" on empty messages.
await self.rawmsg('PRIVMSG', target, chunk or ' ') | [
"async",
"def",
"message",
"(",
"self",
",",
"target",
",",
"message",
")",
":",
"hostmask",
"=",
"self",
".",
"_format_user_mask",
"(",
"self",
".",
"nickname",
")",
"# Leeway.",
"chunklen",
"=",
"protocol",
".",
"MESSAGE_LENGTH_LIMIT",
"-",
"len",
"(",
"... | Message channel or user. | [
"Message",
"channel",
"or",
"user",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L339-L349 |
25,274 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.set_topic | async def set_topic(self, channel, topic):
"""
Set topic on channel.
Users should only rely on the topic actually being changed when receiving an on_topic_change callback.
"""
if not self.is_channel(channel):
raise ValueError('Not a channel: {}'.format(channel))
elif not self.in_channel(channel):
raise NotInChannel(channel)
await self.rawmsg('TOPIC', channel, topic) | python | async def set_topic(self, channel, topic):
if not self.is_channel(channel):
raise ValueError('Not a channel: {}'.format(channel))
elif not self.in_channel(channel):
raise NotInChannel(channel)
await self.rawmsg('TOPIC', channel, topic) | [
"async",
"def",
"set_topic",
"(",
"self",
",",
"channel",
",",
"topic",
")",
":",
"if",
"not",
"self",
".",
"is_channel",
"(",
"channel",
")",
":",
"raise",
"ValueError",
"(",
"'Not a channel: {}'",
".",
"format",
"(",
"channel",
")",
")",
"elif",
"not",... | Set topic on channel.
Users should only rely on the topic actually being changed when receiving an on_topic_change callback. | [
"Set",
"topic",
"on",
"channel",
".",
"Users",
"should",
"only",
"rely",
"on",
"the",
"topic",
"actually",
"being",
"changed",
"when",
"receiving",
"an",
"on_topic_change",
"callback",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L372-L382 |
25,275 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_error | async def on_raw_error(self, message):
""" Server encountered an error and will now close the connection. """
error = protocol.ServerError(' '.join(message.params))
await self.on_data_error(error) | python | async def on_raw_error(self, message):
error = protocol.ServerError(' '.join(message.params))
await self.on_data_error(error) | [
"async",
"def",
"on_raw_error",
"(",
"self",
",",
"message",
")",
":",
"error",
"=",
"protocol",
".",
"ServerError",
"(",
"' '",
".",
"join",
"(",
"message",
".",
"params",
")",
")",
"await",
"self",
".",
"on_data_error",
"(",
"error",
")"
] | Server encountered an error and will now close the connection. | [
"Server",
"encountered",
"an",
"error",
"and",
"will",
"now",
"close",
"the",
"connection",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L539-L542 |
25,276 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_invite | async def on_raw_invite(self, message):
""" INVITE command. """
nick, metadata = self._parse_user(message.source)
self._sync_user(nick, metadata)
target, channel = message.params
target, metadata = self._parse_user(target)
if self.is_same_nick(self.nickname, target):
await self.on_invite(channel, nick)
else:
await self.on_user_invite(target, channel, nick) | python | async def on_raw_invite(self, message):
nick, metadata = self._parse_user(message.source)
self._sync_user(nick, metadata)
target, channel = message.params
target, metadata = self._parse_user(target)
if self.is_same_nick(self.nickname, target):
await self.on_invite(channel, nick)
else:
await self.on_user_invite(target, channel, nick) | [
"async",
"def",
"on_raw_invite",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"self",
".",
"_sync_user",
"(",
"nick",
",",
"metadata",
")",
"target",
",",
"channel",
... | INVITE command. | [
"INVITE",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L544-L555 |
25,277 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_join | async def on_raw_join(self, message):
""" JOIN command. """
nick, metadata = self._parse_user(message.source)
self._sync_user(nick, metadata)
channels = message.params[0].split(',')
if self.is_same_nick(self.nickname, nick):
# Add to our channel list, we joined here.
for channel in channels:
if not self.in_channel(channel):
self._create_channel(channel)
# Request channel mode from IRCd.
await self.rawmsg('MODE', channel)
else:
# Add user to channel user list.
for channel in channels:
if self.in_channel(channel):
self.channels[channel]['users'].add(nick)
for channel in channels:
await self.on_join(channel, nick) | python | async def on_raw_join(self, message):
nick, metadata = self._parse_user(message.source)
self._sync_user(nick, metadata)
channels = message.params[0].split(',')
if self.is_same_nick(self.nickname, nick):
# Add to our channel list, we joined here.
for channel in channels:
if not self.in_channel(channel):
self._create_channel(channel)
# Request channel mode from IRCd.
await self.rawmsg('MODE', channel)
else:
# Add user to channel user list.
for channel in channels:
if self.in_channel(channel):
self.channels[channel]['users'].add(nick)
for channel in channels:
await self.on_join(channel, nick) | [
"async",
"def",
"on_raw_join",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"self",
".",
"_sync_user",
"(",
"nick",
",",
"metadata",
")",
"channels",
"=",
"message",
... | JOIN command. | [
"JOIN",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L557-L578 |
25,278 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_kick | async def on_raw_kick(self, message):
""" KICK command. """
kicker, kickermeta = self._parse_user(message.source)
self._sync_user(kicker, kickermeta)
if len(message.params) > 2:
channels, targets, reason = message.params
else:
channels, targets = message.params
reason = None
channels = channels.split(',')
targets = targets.split(',')
for channel, target in itertools.product(channels, targets):
target, targetmeta = self._parse_user(target)
self._sync_user(target, targetmeta)
if self.is_same_nick(target, self.nickname):
self._destroy_channel(channel)
else:
# Update nick list on channel.
if self.in_channel(channel):
self._destroy_user(target, channel)
await self.on_kick(channel, target, kicker, reason) | python | async def on_raw_kick(self, message):
kicker, kickermeta = self._parse_user(message.source)
self._sync_user(kicker, kickermeta)
if len(message.params) > 2:
channels, targets, reason = message.params
else:
channels, targets = message.params
reason = None
channels = channels.split(',')
targets = targets.split(',')
for channel, target in itertools.product(channels, targets):
target, targetmeta = self._parse_user(target)
self._sync_user(target, targetmeta)
if self.is_same_nick(target, self.nickname):
self._destroy_channel(channel)
else:
# Update nick list on channel.
if self.in_channel(channel):
self._destroy_user(target, channel)
await self.on_kick(channel, target, kicker, reason) | [
"async",
"def",
"on_raw_kick",
"(",
"self",
",",
"message",
")",
":",
"kicker",
",",
"kickermeta",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"self",
".",
"_sync_user",
"(",
"kicker",
",",
"kickermeta",
")",
"if",
"len",
"(",
... | KICK command. | [
"KICK",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L580-L605 |
25,279 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_kill | async def on_raw_kill(self, message):
""" KILL command. """
by, bymeta = self._parse_user(message.source)
target, targetmeta = self._parse_user(message.params[0])
reason = message.params[1]
self._sync_user(target, targetmeta)
if by in self.users:
self._sync_user(by, bymeta)
await self.on_kill(target, by, reason)
if self.is_same_nick(self.nickname, target):
await self.disconnect(expected=False)
else:
self._destroy_user(target) | python | async def on_raw_kill(self, message):
by, bymeta = self._parse_user(message.source)
target, targetmeta = self._parse_user(message.params[0])
reason = message.params[1]
self._sync_user(target, targetmeta)
if by in self.users:
self._sync_user(by, bymeta)
await self.on_kill(target, by, reason)
if self.is_same_nick(self.nickname, target):
await self.disconnect(expected=False)
else:
self._destroy_user(target) | [
"async",
"def",
"on_raw_kill",
"(",
"self",
",",
"message",
")",
":",
"by",
",",
"bymeta",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"target",
",",
"targetmeta",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"params",
... | KILL command. | [
"KILL",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L607-L621 |
25,280 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_mode | async def on_raw_mode(self, message):
""" MODE command. """
nick, metadata = self._parse_user(message.source)
target, modes = message.params[0], message.params[1:]
self._sync_user(nick, metadata)
if self.is_channel(target):
if self.in_channel(target):
# Parse modes.
self.channels[target]['modes'] = self._parse_channel_modes(target, modes)
await self.on_mode_change(target, modes, nick)
else:
target, targetmeta = self._parse_user(target)
self._sync_user(target, targetmeta)
# Update own modes.
if self.is_same_nick(self.nickname, nick):
self._mode = self._parse_user_modes(nick, modes, current=self._mode)
await self.on_user_mode_change(modes) | python | async def on_raw_mode(self, message):
nick, metadata = self._parse_user(message.source)
target, modes = message.params[0], message.params[1:]
self._sync_user(nick, metadata)
if self.is_channel(target):
if self.in_channel(target):
# Parse modes.
self.channels[target]['modes'] = self._parse_channel_modes(target, modes)
await self.on_mode_change(target, modes, nick)
else:
target, targetmeta = self._parse_user(target)
self._sync_user(target, targetmeta)
# Update own modes.
if self.is_same_nick(self.nickname, nick):
self._mode = self._parse_user_modes(nick, modes, current=self._mode)
await self.on_user_mode_change(modes) | [
"async",
"def",
"on_raw_mode",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"target",
",",
"modes",
"=",
"message",
".",
"params",
"[",
"0",
"]",
",",
"message",
... | MODE command. | [
"MODE",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L623-L643 |
25,281 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_nick | async def on_raw_nick(self, message):
""" NICK command. """
nick, metadata = self._parse_user(message.source)
new = message.params[0]
self._sync_user(nick, metadata)
# Acknowledgement of nickname change: set it internally, too.
# Alternatively, we were force nick-changed. Nothing much we can do about it.
if self.is_same_nick(self.nickname, nick):
self.nickname = new
# Go through all user lists and replace.
self._rename_user(nick, new)
# Call handler.
await self.on_nick_change(nick, new) | python | async def on_raw_nick(self, message):
nick, metadata = self._parse_user(message.source)
new = message.params[0]
self._sync_user(nick, metadata)
# Acknowledgement of nickname change: set it internally, too.
# Alternatively, we were force nick-changed. Nothing much we can do about it.
if self.is_same_nick(self.nickname, nick):
self.nickname = new
# Go through all user lists and replace.
self._rename_user(nick, new)
# Call handler.
await self.on_nick_change(nick, new) | [
"async",
"def",
"on_raw_nick",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"new",
"=",
"message",
".",
"params",
"[",
"0",
"]",
"self",
".",
"_sync_user",
"(",
"... | NICK command. | [
"NICK",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L645-L660 |
25,282 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_notice | async def on_raw_notice(self, message):
""" NOTICE command. """
nick, metadata = self._parse_user(message.source)
target, message = message.params
self._sync_user(nick, metadata)
await self.on_notice(target, nick, message)
if self.is_channel(target):
await self.on_channel_notice(target, nick, message)
else:
await self.on_private_notice(target, nick, message) | python | async def on_raw_notice(self, message):
nick, metadata = self._parse_user(message.source)
target, message = message.params
self._sync_user(nick, metadata)
await self.on_notice(target, nick, message)
if self.is_channel(target):
await self.on_channel_notice(target, nick, message)
else:
await self.on_private_notice(target, nick, message) | [
"async",
"def",
"on_raw_notice",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"target",
",",
"message",
"=",
"message",
".",
"params",
"self",
".",
"_sync_user",
"(",... | NOTICE command. | [
"NOTICE",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L662-L673 |
25,283 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_part | async def on_raw_part(self, message):
""" PART command. """
nick, metadata = self._parse_user(message.source)
channels = message.params[0].split(',')
if len(message.params) > 1:
reason = message.params[1]
else:
reason = None
self._sync_user(nick, metadata)
if self.is_same_nick(self.nickname, nick):
# We left the channel. Remove from channel list. :(
for channel in channels:
if self.in_channel(channel):
self._destroy_channel(channel)
await self.on_part(channel, nick, reason)
else:
# Someone else left. Remove them.
for channel in channels:
self._destroy_user(nick, channel)
await self.on_part(channel, nick, reason) | python | async def on_raw_part(self, message):
nick, metadata = self._parse_user(message.source)
channels = message.params[0].split(',')
if len(message.params) > 1:
reason = message.params[1]
else:
reason = None
self._sync_user(nick, metadata)
if self.is_same_nick(self.nickname, nick):
# We left the channel. Remove from channel list. :(
for channel in channels:
if self.in_channel(channel):
self._destroy_channel(channel)
await self.on_part(channel, nick, reason)
else:
# Someone else left. Remove them.
for channel in channels:
self._destroy_user(nick, channel)
await self.on_part(channel, nick, reason) | [
"async",
"def",
"on_raw_part",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"channels",
"=",
"message",
".",
"params",
"[",
"0",
"]",
".",
"split",
"(",
"','",
")... | PART command. | [
"PART",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L675-L695 |
25,284 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_privmsg | async def on_raw_privmsg(self, message):
""" PRIVMSG command. """
nick, metadata = self._parse_user(message.source)
target, message = message.params
self._sync_user(nick, metadata)
await self.on_message(target, nick, message)
if self.is_channel(target):
await self.on_channel_message(target, nick, message)
else:
await self.on_private_message(target, nick, message) | python | async def on_raw_privmsg(self, message):
nick, metadata = self._parse_user(message.source)
target, message = message.params
self._sync_user(nick, metadata)
await self.on_message(target, nick, message)
if self.is_channel(target):
await self.on_channel_message(target, nick, message)
else:
await self.on_private_message(target, nick, message) | [
"async",
"def",
"on_raw_privmsg",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"target",
",",
"message",
"=",
"message",
".",
"params",
"self",
".",
"_sync_user",
"("... | PRIVMSG command. | [
"PRIVMSG",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L702-L713 |
25,285 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_quit | async def on_raw_quit(self, message):
""" QUIT command. """
nick, metadata = self._parse_user(message.source)
self._sync_user(nick, metadata)
if message.params:
reason = message.params[0]
else:
reason = None
await self.on_quit(nick, reason)
# Remove user from database.
if not self.is_same_nick(self.nickname, nick):
self._destroy_user(nick)
# Else, we quit.
elif self.connected:
await self.disconnect(expected=True) | python | async def on_raw_quit(self, message):
nick, metadata = self._parse_user(message.source)
self._sync_user(nick, metadata)
if message.params:
reason = message.params[0]
else:
reason = None
await self.on_quit(nick, reason)
# Remove user from database.
if not self.is_same_nick(self.nickname, nick):
self._destroy_user(nick)
# Else, we quit.
elif self.connected:
await self.disconnect(expected=True) | [
"async",
"def",
"on_raw_quit",
"(",
"self",
",",
"message",
")",
":",
"nick",
",",
"metadata",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"self",
".",
"_sync_user",
"(",
"nick",
",",
"metadata",
")",
"if",
"message",
".",
"par... | QUIT command. | [
"QUIT",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L715-L731 |
25,286 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_topic | async def on_raw_topic(self, message):
""" TOPIC command. """
setter, settermeta = self._parse_user(message.source)
target, topic = message.params
self._sync_user(setter, settermeta)
# Update topic in our own channel list.
if self.in_channel(target):
self.channels[target]['topic'] = topic
self.channels[target]['topic_by'] = setter
self.channels[target]['topic_set'] = datetime.datetime.now()
await self.on_topic_change(target, topic, setter) | python | async def on_raw_topic(self, message):
setter, settermeta = self._parse_user(message.source)
target, topic = message.params
self._sync_user(setter, settermeta)
# Update topic in our own channel list.
if self.in_channel(target):
self.channels[target]['topic'] = topic
self.channels[target]['topic_by'] = setter
self.channels[target]['topic_set'] = datetime.datetime.now()
await self.on_topic_change(target, topic, setter) | [
"async",
"def",
"on_raw_topic",
"(",
"self",
",",
"message",
")",
":",
"setter",
",",
"settermeta",
"=",
"self",
".",
"_parse_user",
"(",
"message",
".",
"source",
")",
"target",
",",
"topic",
"=",
"message",
".",
"params",
"self",
".",
"_sync_user",
"("... | TOPIC command. | [
"TOPIC",
"command",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L733-L746 |
25,287 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_004 | async def on_raw_004(self, message):
""" Basic server information. """
target, hostname, ircd, user_modes, channel_modes = message.params[:5]
# Set valid channel and user modes.
self._channel_modes = set(channel_modes)
self._user_modes = set(user_modes) | python | async def on_raw_004(self, message):
target, hostname, ircd, user_modes, channel_modes = message.params[:5]
# Set valid channel and user modes.
self._channel_modes = set(channel_modes)
self._user_modes = set(user_modes) | [
"async",
"def",
"on_raw_004",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"hostname",
",",
"ircd",
",",
"user_modes",
",",
"channel_modes",
"=",
"message",
".",
"params",
"[",
":",
"5",
"]",
"# Set valid channel and user modes.",
"self",
".",
"_cha... | Basic server information. | [
"Basic",
"server",
"information",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L757-L763 |
25,288 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_301 | async def on_raw_301(self, message):
""" User is away. """
target, nickname, message = message.params
info = {
'away': True,
'away_message': message
}
if nickname in self.users:
self._sync_user(nickname, info)
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | python | async def on_raw_301(self, message):
target, nickname, message = message.params
info = {
'away': True,
'away_message': message
}
if nickname in self.users:
self._sync_user(nickname, info)
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | [
"async",
"def",
"on_raw_301",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"nickname",
",",
"message",
"=",
"message",
".",
"params",
"info",
"=",
"{",
"'away'",
":",
"True",
",",
"'away_message'",
":",
"message",
"}",
"if",
"nickname",
"in",
... | User is away. | [
"User",
"is",
"away",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L776-L787 |
25,289 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_311 | async def on_raw_311(self, message):
""" WHOIS user info. """
target, nickname, username, hostname, _, realname = message.params
info = {
'username': username,
'hostname': hostname,
'realname': realname
}
self._sync_user(nickname, info)
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | python | async def on_raw_311(self, message):
target, nickname, username, hostname, _, realname = message.params
info = {
'username': username,
'hostname': hostname,
'realname': realname
}
self._sync_user(nickname, info)
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | [
"async",
"def",
"on_raw_311",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"nickname",
",",
"username",
",",
"hostname",
",",
"_",
",",
"realname",
"=",
"message",
".",
"params",
"info",
"=",
"{",
"'username'",
":",
"username",
",",
"'hostname'"... | WHOIS user info. | [
"WHOIS",
"user",
"info",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L789-L800 |
25,290 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_312 | async def on_raw_312(self, message):
""" WHOIS server info. """
target, nickname, server, serverinfo = message.params
info = {
'server': server,
'server_info': serverinfo
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info)
if nickname in self._pending['whowas']:
self._whowas_info[nickname].update(info) | python | async def on_raw_312(self, message):
target, nickname, server, serverinfo = message.params
info = {
'server': server,
'server_info': serverinfo
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info)
if nickname in self._pending['whowas']:
self._whowas_info[nickname].update(info) | [
"async",
"def",
"on_raw_312",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"nickname",
",",
"server",
",",
"serverinfo",
"=",
"message",
".",
"params",
"info",
"=",
"{",
"'server'",
":",
"server",
",",
"'server_info'",
":",
"serverinfo",
"}",
"i... | WHOIS server info. | [
"WHOIS",
"server",
"info",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L802-L813 |
25,291 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_313 | async def on_raw_313(self, message):
""" WHOIS operator info. """
target, nickname = message.params[:2]
info = {
'oper': True
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | python | async def on_raw_313(self, message):
target, nickname = message.params[:2]
info = {
'oper': True
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | [
"async",
"def",
"on_raw_313",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"nickname",
"=",
"message",
".",
"params",
"[",
":",
"2",
"]",
"info",
"=",
"{",
"'oper'",
":",
"True",
"}",
"if",
"nickname",
"in",
"self",
".",
"_pending",
"[",
"... | WHOIS operator info. | [
"WHOIS",
"operator",
"info",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L815-L823 |
25,292 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_314 | async def on_raw_314(self, message):
""" WHOWAS user info. """
target, nickname, username, hostname, _, realname = message.params
info = {
'username': username,
'hostname': hostname,
'realname': realname
}
if nickname in self._pending['whowas']:
self._whowas_info[nickname].update(info) | python | async def on_raw_314(self, message):
target, nickname, username, hostname, _, realname = message.params
info = {
'username': username,
'hostname': hostname,
'realname': realname
}
if nickname in self._pending['whowas']:
self._whowas_info[nickname].update(info) | [
"async",
"def",
"on_raw_314",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"nickname",
",",
"username",
",",
"hostname",
",",
"_",
",",
"realname",
"=",
"message",
".",
"params",
"info",
"=",
"{",
"'username'",
":",
"username",
",",
"'hostname'"... | WHOWAS user info. | [
"WHOWAS",
"user",
"info",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L825-L835 |
25,293 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_317 | async def on_raw_317(self, message):
""" WHOIS idle time. """
target, nickname, idle_time = message.params[:3]
info = {
'idle': int(idle_time),
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | python | async def on_raw_317(self, message):
target, nickname, idle_time = message.params[:3]
info = {
'idle': int(idle_time),
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | [
"async",
"def",
"on_raw_317",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"nickname",
",",
"idle_time",
"=",
"message",
".",
"params",
"[",
":",
"3",
"]",
"info",
"=",
"{",
"'idle'",
":",
"int",
"(",
"idle_time",
")",
",",
"}",
"if",
"nic... | WHOIS idle time. | [
"WHOIS",
"idle",
"time",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L839-L847 |
25,294 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_319 | async def on_raw_319(self, message):
""" WHOIS active channels. """
target, nickname, channels = message.params[:3]
channels = {channel.lstrip() for channel in channels.strip().split(' ')}
info = {
'channels': channels
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | python | async def on_raw_319(self, message):
target, nickname, channels = message.params[:3]
channels = {channel.lstrip() for channel in channels.strip().split(' ')}
info = {
'channels': channels
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | [
"async",
"def",
"on_raw_319",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"nickname",
",",
"channels",
"=",
"message",
".",
"params",
"[",
":",
"3",
"]",
"channels",
"=",
"{",
"channel",
".",
"lstrip",
"(",
")",
"for",
"channel",
"in",
"cha... | WHOIS active channels. | [
"WHOIS",
"active",
"channels",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L858-L867 |
25,295 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_324 | async def on_raw_324(self, message):
""" Channel mode. """
target, channel = message.params[:2]
modes = message.params[2:]
if not self.in_channel(channel):
return
self.channels[channel]['modes'] = self._parse_channel_modes(channel, modes) | python | async def on_raw_324(self, message):
target, channel = message.params[:2]
modes = message.params[2:]
if not self.in_channel(channel):
return
self.channels[channel]['modes'] = self._parse_channel_modes(channel, modes) | [
"async",
"def",
"on_raw_324",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"channel",
"=",
"message",
".",
"params",
"[",
":",
"2",
"]",
"modes",
"=",
"message",
".",
"params",
"[",
"2",
":",
"]",
"if",
"not",
"self",
".",
"in_channel",
"(... | Channel mode. | [
"Channel",
"mode",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L869-L876 |
25,296 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_329 | async def on_raw_329(self, message):
""" Channel creation time. """
target, channel, timestamp = message.params
if not self.in_channel(channel):
return
self.channels[channel]['created'] = datetime.datetime.fromtimestamp(int(timestamp)) | python | async def on_raw_329(self, message):
target, channel, timestamp = message.params
if not self.in_channel(channel):
return
self.channels[channel]['created'] = datetime.datetime.fromtimestamp(int(timestamp)) | [
"async",
"def",
"on_raw_329",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"channel",
",",
"timestamp",
"=",
"message",
".",
"params",
"if",
"not",
"self",
".",
"in_channel",
"(",
"channel",
")",
":",
"return",
"self",
".",
"channels",
"[",
"c... | Channel creation time. | [
"Channel",
"creation",
"time",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L878-L884 |
25,297 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_332 | async def on_raw_332(self, message):
""" Current topic on channel join. """
target, channel, topic = message.params
if not self.in_channel(channel):
return
self.channels[channel]['topic'] = topic | python | async def on_raw_332(self, message):
target, channel, topic = message.params
if not self.in_channel(channel):
return
self.channels[channel]['topic'] = topic | [
"async",
"def",
"on_raw_332",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"channel",
",",
"topic",
"=",
"message",
".",
"params",
"if",
"not",
"self",
".",
"in_channel",
"(",
"channel",
")",
":",
"return",
"self",
".",
"channels",
"[",
"chann... | Current topic on channel join. | [
"Current",
"topic",
"on",
"channel",
"join",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L886-L892 |
25,298 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_333 | async def on_raw_333(self, message):
""" Topic setter and time on channel join. """
target, channel, setter, timestamp = message.params
if not self.in_channel(channel):
return
# No need to sync user since this is most likely outdated info.
self.channels[channel]['topic_by'] = self._parse_user(setter)[0]
self.channels[channel]['topic_set'] = datetime.datetime.fromtimestamp(int(timestamp)) | python | async def on_raw_333(self, message):
target, channel, setter, timestamp = message.params
if not self.in_channel(channel):
return
# No need to sync user since this is most likely outdated info.
self.channels[channel]['topic_by'] = self._parse_user(setter)[0]
self.channels[channel]['topic_set'] = datetime.datetime.fromtimestamp(int(timestamp)) | [
"async",
"def",
"on_raw_333",
"(",
"self",
",",
"message",
")",
":",
"target",
",",
"channel",
",",
"setter",
",",
"timestamp",
"=",
"message",
".",
"params",
"if",
"not",
"self",
".",
"in_channel",
"(",
"channel",
")",
":",
"return",
"# No need to sync us... | Topic setter and time on channel join. | [
"Topic",
"setter",
"and",
"time",
"on",
"channel",
"join",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L894-L902 |
25,299 | Shizmob/pydle | pydle/features/rfc1459/client.py | RFC1459Support.on_raw_375 | async def on_raw_375(self, message):
""" Start message of the day. """
await self._registration_completed(message)
self.motd = message.params[1] + '\n' | python | async def on_raw_375(self, message):
await self._registration_completed(message)
self.motd = message.params[1] + '\n' | [
"async",
"def",
"on_raw_375",
"(",
"self",
",",
"message",
")",
":",
"await",
"self",
".",
"_registration_completed",
"(",
"message",
")",
"self",
".",
"motd",
"=",
"message",
".",
"params",
"[",
"1",
"]",
"+",
"'\\n'"
] | Start message of the day. | [
"Start",
"message",
"of",
"the",
"day",
"."
] | 7ec7d65d097318ed0bcdc5d8401470287d8c7cf7 | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L944-L947 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.