INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Handle the bit after an '=' in a macro default argument. This is
probably the trickiest thing. The goal here is to accept all strings
jinja would accept and always handle block start/end correctly: It's
fine to have false positives, jinja can fail later.
Return True if there are more ar... | def _process_macro_default_arg(self):
"""Handle the bit after an '=' in a macro default argument. This is
probably the trickiest thing. The goal here is to accept all strings
jinja would accept and always handle block start/end correctly: It's
fine to have false positives, jinja can fail... |
This is suspiciously similar to _process_macro_default_arg, probably
want to figure out how to merge the two.
Process the rval of an assignment statement or a do-block | def _process_rval_components(self):
"""This is suspiciously similar to _process_macro_default_arg, probably
want to figure out how to merge the two.
Process the rval of an assignment statement or a do-block
"""
while True:
match = self._expect_match(
... |
Macro args are pretty tricky! Arg names themselves are simple, but
you can set arbitrary default values, including doing stuff like:
{% macro my_macro(arg="x" + ("}% {# {% endmacro %}" * 2)) %}
Which makes you a jerk, but is valid jinja. | def _process_macro_args(self):
"""Macro args are pretty tricky! Arg names themselves are simple, but
you can set arbitrary default values, including doing stuff like:
{% macro my_macro(arg="x" + ("}% {# {% endmacro %}" * 2)) %}
Which makes you a jerk, but is valid jinja.
"""
... |
Render an entry, in case it's jinja. This is meant to be passed to
deep_map.
If the parsed entry is a string and has the name 'port', this will
attempt to cast it to an int, and on failure will return the parsed
string.
:param value Any: The value to potentially render
... | def _render_project_entry(self, value, keypath):
"""Render an entry, in case it's jinja. This is meant to be passed to
deep_map.
If the parsed entry is a string and has the name 'port', this will
attempt to cast it to an int, and on failure will return the parsed
string.
... |
Render the parsed data, returning a new dict (or whatever was read). | def render_project(self, as_parsed):
"""Render the parsed data, returning a new dict (or whatever was read).
"""
try:
return deep_map(self._render_project_entry, as_parsed)
except RecursionException:
raise DbtProjectError(
'Cycle detected: Project ... |
Render the chosen profile entry, as it was parsed. | def render_profile_data(self, as_parsed):
"""Render the chosen profile entry, as it was parsed."""
try:
return deep_map(self._render_profile_data, as_parsed)
except RecursionException:
raise DbtProfileError(
'Cycle detected: Profile input has a reference t... |
Load and parse archives in a list of projects. Returns a dict
that maps unique ids onto ParsedNodes | def load_and_parse(self):
"""Load and parse archives in a list of projects. Returns a dict
that maps unique ids onto ParsedNodes"""
archives = []
to_return = {}
for name, project in self.all_projects.items():
archives = archives + self.parse_archives_from_project... |
Unlike to_project_config, this dict is not a mirror of any existing
on-disk data structure. It's used when creating a new profile from an
existing one.
:param serialize_credentials bool: If True, serialize the credentials.
Otherwise, the Credentials object will be copied.
:r... | def to_profile_info(self, serialize_credentials=False):
"""Unlike to_project_config, this dict is not a mirror of any existing
on-disk data structure. It's used when creating a new profile from an
existing one.
:param serialize_credentials bool: If True, serialize the credentials.
... |
Create a profile from an existing set of Credentials and the
remaining information.
:param credentials dict: The credentials dict for this profile.
:param threads int: The number of threads to use for connections.
:param profile_name str: The profile name used for this profile.
... | def from_credentials(cls, credentials, threads, profile_name, target_name,
user_cfg=None):
"""Create a profile from an existing set of Credentials and the
remaining information.
:param credentials dict: The credentials dict for this profile.
:param threads int: ... |
This is a containment zone for the hateful way we're rendering
profiles. | def render_profile(cls, raw_profile, profile_name, target_override,
cli_vars):
"""This is a containment zone for the hateful way we're rendering
profiles.
"""
renderer = ConfigRenderer(cli_vars=cli_vars)
# rendering profiles is a bit complex. Two constrain... |
Create a profile from its raw profile information.
(this is an intermediate step, mostly useful for unit testing)
:param raw_profile dict: The profile data for a single profile, from
disk as yaml and its values rendered with jinja.
:param profile_name str: The profile name used.
... | def from_raw_profile_info(cls, raw_profile, profile_name, cli_vars,
user_cfg=None, target_override=None,
threads_override=None):
"""Create a profile from its raw profile information.
(this is an intermediate step, mostly useful for unit testi... |
:param raw_profiles dict: The profile data, from disk as yaml.
:param profile_name str: The profile name to use.
:param cli_vars dict: The command-line variables passed as arguments,
as a dict.
:param target_override Optional[str]: The target to use, if provided on
the co... | def from_raw_profiles(cls, raw_profiles, profile_name, cli_vars,
target_override=None, threads_override=None):
"""
:param raw_profiles dict: The profile data, from disk as yaml.
:param profile_name str: The profile name to use.
:param cli_vars dict: The command-... |
Given the raw profiles as read from disk and the name of the desired
profile if specified, return the profile component of the runtime
config.
:param args argparse.Namespace: The arguments as parsed from the cli.
:param project_profile_name Optional[str]: The profile name, if
... | def from_args(cls, args, project_profile_name=None):
"""Given the raw profiles as read from disk and the name of the desired
profile if specified, return the profile component of the runtime
config.
:param args argparse.Namespace: The arguments as parsed from the cli.
:param pro... |
Return a function that will process `doc()` references in jinja, look
them up in the manifest, and return the appropriate block contents. | def docs(node, manifest, config, column_name=None):
"""Return a function that will process `doc()` references in jinja, look
them up in the manifest, and return the appropriate block contents.
"""
current_project = config.project_name
def do_docs(*args):
if len(args) == 1:
doc_p... |
Resolve the given documentation. This follows the same algorithm as
resolve_ref except the is_enabled checks are unnecessary as docs are
always enabled. | def resolve_doc(cls, manifest, target_doc_name, target_doc_package,
current_project, node_package):
"""Resolve the given documentation. This follows the same algorithm as
resolve_ref except the is_enabled checks are unnecessary as docs are
always enabled.
"""
... |
Given a ParsedNode, add some fields that might be missing. Return a
reference to the dict that refers to the given column, creating it if
it doesn't yet exist. | def _get_node_column(cls, node, column_name):
"""Given a ParsedNode, add some fields that might be missing. Return a
reference to the dict that refers to the given column, creating it if
it doesn't yet exist.
"""
if not hasattr(node, 'columns'):
node.set('columns', {}... |
Given a manifest and a node in that manifest, process its refs | def process_refs_for_node(cls, manifest, current_project, node):
"""Given a manifest and a node in that manifest, process its refs"""
target_model = None
target_model_name = None
target_model_package = None
for ref in node.refs:
if len(ref) == 1:
targ... |
Given a new node that is not in the manifest, copy the manifest and
insert the new node into it as if it were part of regular ref
processing | def add_new_refs(cls, manifest, current_project, node, macros):
"""Given a new node that is not in the manifest, copy the manifest and
insert the new node into it as if it were part of regular ref
processing
"""
manifest = manifest.deepcopy(config=current_project)
# it's ... |
Parse multiple versions as read from disk. The versions value may be any
one of:
- a single version string ('>0.12.1')
- a single string specifying multiple comma-separated versions
('>0.11.1,<=0.12.2')
- an array of single-version strings (['>0.11.1', '<=0.12.2'])
Regardles... | def _parse_versions(versions):
"""Parse multiple versions as read from disk. The versions value may be any
one of:
- a single version string ('>0.12.1')
- a single string specifying multiple comma-separated versions
('>0.11.1,<=0.12.2')
- an array of single-version strings ([... |
Pre-process certain special keys to convert them from None values
into empty containers, and to turn strings into arrays of strings. | def _preprocess(project_dict):
"""Pre-process certain special keys to convert them from None values
into empty containers, and to turn strings into arrays of strings.
"""
handlers = {
('archive',): _list_if_none,
('on-run-start',): _list_if_none_or_string,
... |
Create a project from its project and package configuration, as read
by yaml.safe_load().
:param project_dict dict: The dictionary as read from disk
:param packages_dict Optional[dict]: If it exists, the packages file as
read from disk.
:raises DbtProjectError: If the projec... | def from_project_config(cls, project_dict, packages_dict=None):
"""Create a project from its project and package configuration, as read
by yaml.safe_load().
:param project_dict dict: The dictionary as read from disk
:param packages_dict Optional[dict]: If it exists, the packages file as... |
Return a dict representation of the config that could be written to
disk with `yaml.safe_dump` to get this configuration.
:param with_packages bool: If True, include the serialized packages
file in the root.
:returns dict: The serialized profile. | def to_project_config(self, with_packages=False):
"""Return a dict representation of the config that could be written to
disk with `yaml.safe_dump` to get this configuration.
:param with_packages bool: If True, include the serialized packages
file in the root.
:returns dict:... |
Create a project from a root directory. Reads in dbt_project.yml and
packages.yml, if it exists.
:param project_root str: The path to the project root to load.
:raises DbtProjectError: If the project is missing or invalid, or if
the packages file exists and is invalid.
:retu... | def from_project_root(cls, project_root, cli_vars):
"""Create a project from a root directory. Reads in dbt_project.yml and
packages.yml, if it exists.
:param project_root str: The path to the project root to load.
:raises DbtProjectError: If the project is missing or invalid, or if
... |
Return a list of lists of strings, where each inner list of strings
represents a type + FQN path of a resource configuration that is not
used. | def get_unused_resource_config_paths(self, resource_fqns, disabled):
"""Return a list of lists of strings, where each inner list of strings
represents a type + FQN path of a resource configuration that is not
used.
"""
disabled_fqns = frozenset(tuple(fqn) for fqn in disabled)
... |
Ensure this package works with the installed version of dbt. | def validate_version(self):
"""Ensure this package works with the installed version of dbt."""
installed = get_installed_version()
if not versions_compatible(*self.dbt_version):
msg = IMPOSSIBLE_VERSION_ERROR.format(
package=self.project_name,
version_... |
returns True if this column can be expanded to the size of the
other column | def can_expand_to(self, other_column):
"""returns True if this column can be expanded to the size of the
other column"""
if not self.is_string() or not other_column.is_string():
return False
return other_column.string_size() > self.string_size() |
On entrance to this context manager, hold an exclusive lock and
create a fresh transaction for redshift, then commit and begin a new
one before releasing the lock on exit.
See drop_relation in RedshiftAdapter for more information.
:param Optional[str] name: The name of the connection t... | def fresh_transaction(self, name=None):
"""On entrance to this context manager, hold an exclusive lock and
create a fresh transaction for redshift, then commit and begin a new
one before releasing the lock on exit.
See drop_relation in RedshiftAdapter for more information.
:par... |
Fetches temporary login credentials from AWS. The specified user
must already exist in the database, or else an error will occur | def fetch_cluster_credentials(cls, db_user, db_name, cluster_id,
duration_s):
"""Fetches temporary login credentials from AWS. The specified user
must already exist in the database, or else an error will occur"""
boto_client = boto3.client('redshift')
t... |
Load and parse models in a list of directories. Returns a dict
that maps unique ids onto ParsedNodes | def load_and_parse(self, package_name, root_dir, relative_dirs,
resource_type, tags=None):
"""Load and parse models in a list of directories. Returns a dict
that maps unique ids onto ParsedNodes"""
extension = "[!.#~]*.sql"
if tags is None:
tags = ... |
Wait for results off the queue. If there is a timeout set, and it is
exceeded, raise an RPCTimeoutException. | def _wait_for_results(self):
"""Wait for results off the queue. If there is a timeout set, and it is
exceeded, raise an RPCTimeoutException.
"""
while True:
get_timeout = self._next_timeout()
try:
msgtype, value = self.queue.get(timeout=get_timeout... |
Add a queue log handler to the global logger. | def add_queue_handler(queue):
"""Add a queue log handler to the global logger."""
handler = QueueLogHandler(queue)
handler.setFormatter(QueueFormatter())
handler.setLevel(DEBUG)
GLOBAL_LOGGER.addHandler(handler) |
Raise a CompilationException when an adapter method available to macros
has changed. | def invalid_type_error(method_name, arg_name, got_value, expected_type,
version='0.13.0'):
"""Raise a CompilationException when an adapter method available to macros
has changed.
"""
got_type = type(got_value)
msg = ("As of {version}, 'adapter.{method_name}' expects argument "... |
`ctes` is a dict of CTEs in the form:
{
"cte_id_1": "__dbt__CTE__ephemeral as (select * from table)",
"cte_id_2": "__dbt__CTE__events as (select id, type from events)"
}
Given `sql` like:
"with internal_cte as (select * from sessions)
select * from internal_cte"
This... | def _inject_ctes_into_sql(sql, ctes):
"""
`ctes` is a dict of CTEs in the form:
{
"cte_id_1": "__dbt__CTE__ephemeral as (select * from table)",
"cte_id_2": "__dbt__CTE__events as (select id, type from events)"
}
Given `sql` like:
"with internal_cte as (select * from sess... |
This is the equivalent of what self.extra_ctes[cte_id] = sql would
do if extra_ctes were an OrderedDict | def set_cte(self, cte_id, sql):
"""This is the equivalent of what self.extra_ctes[cte_id] = sql would
do if extra_ctes were an OrderedDict
"""
for cte in self.extra_ctes:
if cte['id'] == cte_id:
cte['sql'] = sql
break
else:
... |
Build out the directory skeleton and python namespace files:
dbt/
__init__.py
adapters/
${adapter_name}
__init__.py
include/
${adapter_name}
__init__.py | def build_namespace(self):
"""Build out the directory skeleton and python namespace files:
dbt/
__init__.py
adapters/
${adapter_name}
__init__.py
include/
${adapter_name}
... |
A decorator that marks a function as available, but also prints a
deprecation warning. Use like
@available_deprecated('my_new_method')
def my_old_method(self, arg, model_name=None):
args = compatability_shim(arg)
return self.my_new_method(*args, model_name=None)
To make `adapter.my_old... | def available_deprecated(supported_name):
"""A decorator that marks a function as available, but also prints a
deprecation warning. Use like
@available_deprecated('my_new_method')
def my_old_method(self, arg, model_name=None):
args = compatability_shim(arg)
return self.my_new_method(*ar... |
Translates BQ SchemaField dicts into dbt BigQueryColumn objects | def _get_dbt_columns_from_bq_table(self, table):
"Translates BQ SchemaField dicts into dbt BigQueryColumn objects"
columns = []
for col in table.schema:
# BigQuery returns type labels that are not valid type specifiers
dtype = self.Column.translate_type(col.field_type)
... |
Convert agate.Table with column names to a list of bigquery schemas. | def _agate_to_schema(self, agate_table, column_override):
"""Convert agate.Table with column names to a list of bigquery schemas.
"""
bq_schema = []
for idx, col_name in enumerate(agate_table.column_names):
inferred_type = self.convert_agate_type(agate_table, idx)
... |
An iterator over the flattened columns for a given schema and table.
Resolves child columns as having the name "parent.child". | def _flat_columns_in_table(self, table):
"""An iterator over the flattened columns for a given schema and table.
Resolves child columns as having the name "parent.child".
"""
for col in self._get_dbt_columns_from_bq_table(table):
flattened = col.flatten()
for subc... |
Construct a tuple of the column names for stats. Each stat has 4
columns of data. | def _get_stats_column_names(cls):
"""Construct a tuple of the column names for stats. Each stat has 4
columns of data.
"""
columns = []
stats = ('num_bytes', 'num_rows', 'location', 'partitioning_type',
'clustering_fields')
stat_components = ('label', 'va... |
Given a table, return an iterator of key/value pairs for stats
column names/values. | def _get_stats_columns(cls, table, relation_type):
"""Given a table, return an iterator of key/value pairs for stats
column names/values.
"""
column_names = cls._get_stats_column_names()
# agate does not handle the array of column names gracefully
clustering_value = None... |
If the caller has passed the magic 'single-threaded' flag, call the
function directly instead of pool.apply_async. The single-threaded flag
is intended for gathering more useful performance information about
what appens beneath `call_runner`, since python's default profiling
tools ignor... | def _submit(self, pool, args, callback):
"""If the caller has passed the magic 'single-threaded' flag, call the
function directly instead of pool.apply_async. The single-threaded flag
is intended for gathering more useful performance information about
what appens beneath `call_runner`, ... |
Given a pool, submit jobs from the queue to the pool. | def run_queue(self, pool):
"""Given a pool, submit jobs from the queue to the pool.
"""
def callback(result):
"""Note: mark_done, at a minimum, must happen here or dbt will
deadlock during ephemeral result error handling!
"""
self._handle_result(re... |
Mark the result as completed, insert the `CompiledResultNode` into
the manifest, and mark any descendants (potentially with a 'cause' if
the result was an ephemeral model) as skipped. | def _handle_result(self, result):
"""Mark the result as completed, insert the `CompiledResultNode` into
the manifest, and mark any descendants (potentially with a 'cause' if
the result was an ephemeral model) as skipped.
"""
is_ephemeral = result.node.is_ephemeral_model
i... |
Run dbt for the query, based on the graph. | def run(self):
"""
Run dbt for the query, based on the graph.
"""
self._runtime_initialize()
if len(self._flattened_nodes) == 0:
logger.warning("WARNING: Nothing to do. Try checking your model "
"configs and model specification args")
... |
Base64 decode a string. This should only be used for sql in calls.
:param str sql: The base64 encoded form of the original utf-8 string
:return str: The decoded utf-8 string | def decode_sql(self, sql):
"""Base64 decode a string. This should only be used for sql in calls.
:param str sql: The base64 encoded form of the original utf-8 string
:return str: The decoded utf-8 string
"""
# JSON is defined as using "unicode", we'll go a step further and
... |
Create a bigquery table. The caller must supply a callback
that takes one argument, a `google.cloud.bigquery.Table`, and mutates
it. | def create_bigquery_table(self, database, schema, table_name, callback,
sql):
"""Create a bigquery table. The caller must supply a callback
that takes one argument, a `google.cloud.bigquery.Table`, and mutates
it.
"""
conn = self.get_thread_connectio... |
Get a bigquery table for a schema/model. | def get_bq_table(self, database, schema, identifier):
"""Get a bigquery table for a schema/model."""
conn = self.get_thread_connection()
table_ref = self.table_ref(database, schema, identifier, conn)
return conn.handle.get_table(table_ref) |
This is only used for some error handling | def read_profiles(profiles_dir=None):
"""This is only used for some error handling"""
if profiles_dir is None:
profiles_dir = PROFILES_DIR
raw_profiles = read_profile(profiles_dir)
if raw_profiles is None:
profiles = {}
else:
profiles = {k: v for (k, v) in raw_profiles.item... |
Create a task that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the inline query.
If a preceding task is already working for a user, that task is cancelled,
t... | def answer(self, inline_query, compute_fn, *compute_args, **compute_kwargs):
"""
Create a task that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the inline qu... |
Process new updates in infinity loop
:param relax: float
:param offset: int
:param timeout: int
:param allowed_updates: bool | async def run_forever(self, relax=0.1, offset=None, timeout=20, allowed_updates=None):
"""
Process new updates in infinity loop
:param relax: float
:param offset: int
:param timeout: int
:param allowed_updates: bool
"""
while 1:
try:
... |
Return flavor of message or event.
A message's flavor may be one of these:
- ``chat``
- ``callback_query``
- ``inline_query``
- ``chosen_inline_result``
- ``shipping_query``
- ``pre_checkout_query``
An event's flavor is determined by the single top-level key. | def flavor(msg):
"""
Return flavor of message or event.
A message's flavor may be one of these:
- ``chat``
- ``callback_query``
- ``inline_query``
- ``chosen_inline_result``
- ``shipping_query``
- ``pre_checkout_query``
An event's flavor is determined by the single top-level k... |
Extract "headline" info about a message.
Use parameter ``long`` to control whether a short or long tuple is returned.
When ``flavor`` is ``chat``
(``msg`` being a `Message <https://core.telegram.org/bots/api#message>`_ object):
- short: (content_type, ``msg['chat']['type']``, ``msg['chat']['id']``)
... | def glance(msg, flavor='chat', long=False):
"""
Extract "headline" info about a message.
Use parameter ``long`` to control whether a short or long tuple is returned.
When ``flavor`` is ``chat``
(``msg`` being a `Message <https://core.telegram.org/bots/api#message>`_ object):
- short: (content_... |
A combination of :meth:`telepot.flavor` and :meth:`telepot.glance`,
return a 2-tuple (flavor, headline_info), where *headline_info* is whatever extracted by
:meth:`telepot.glance` depending on the message flavor and the ``long`` parameter. | def flance(msg, long=False):
"""
A combination of :meth:`telepot.flavor` and :meth:`telepot.glance`,
return a 2-tuple (flavor, headline_info), where *headline_info* is whatever extracted by
:meth:`telepot.glance` depending on the message flavor and the ``long`` parameter.
"""
f = flavor(msg)
... |
See: https://core.telegram.org/bots/api#sendmessage | def sendMessage(self, chat_id, text,
parse_mode=None,
disable_web_page_preview=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendmessag... |
See: https://core.telegram.org/bots/api#forwardmessage | def forwardMessage(self, chat_id, from_chat_id, message_id,
disable_notification=None):
""" See: https://core.telegram.org/bots/api#forwardmessage """
p = _strip(locals())
return self._api_request('forwardMessage', _rectify(p)) |
See: https://core.telegram.org/bots/api#sendvoice
:param voice: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto` | def sendVoice(self, chat_id, voice,
caption=None,
parse_mode=None,
duration=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/a... |
See: https://core.telegram.org/bots/api#sendvideonote
:param video_note: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto`
:param length:
Although marked as optional, this method does not seem to work without
it being specified. Supply any integer you want. It seems to have no... | def sendVideoNote(self, chat_id, video_note,
duration=None,
length=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#send... |
See: https://core.telegram.org/bots/api#sendmediagroup
:type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects
:param media:
To indicate media locations, each InputMedia object's ``media`` field
should be one of these:
- string: `... | def sendMediaGroup(self, chat_id, media,
disable_notification=None,
reply_to_message_id=None):
"""
See: https://core.telegram.org/bots/api#sendmediagroup
:type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects
... |
See: https://core.telegram.org/bots/api#sendlocation | def sendLocation(self, chat_id, latitude, longitude,
live_period=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendlocation """
p = _strip(loca... |
See: https://core.telegram.org/bots/api#sendgame | def sendGame(self, chat_id, game_short_name,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendgame """
p = _strip(locals())
return self._api_request('sendGame', _rectify(p)) |
See: https://core.telegram.org/bots/api#sendinvoice | def sendInvoice(self, chat_id, title, description, payload,
provider_token, start_parameter, currency, prices,
provider_data=None,
photo_url=None,
photo_size=None,
photo_width=None,
photo_height=None,... |
See: https://core.telegram.org/bots/api#sendchataction | def sendChatAction(self, chat_id, action):
""" See: https://core.telegram.org/bots/api#sendchataction """
p = _strip(locals())
return self._api_request('sendChatAction', _rectify(p)) |
See: https://core.telegram.org/bots/api#getuserprofilephotos | def getUserProfilePhotos(self, user_id,
offset=None,
limit=None):
""" See: https://core.telegram.org/bots/api#getuserprofilephotos """
p = _strip(locals())
return self._api_request('getUserProfilePhotos', _rectify(p)) |
See: https://core.telegram.org/bots/api#promotechatmember | def promoteChatMember(self, chat_id, user_id,
can_change_info=None,
can_post_messages=None,
can_edit_messages=None,
can_delete_messages=None,
can_invite_users=None,
... |
See: https://core.telegram.org/bots/api#exportchatinvitelink | def exportChatInviteLink(self, chat_id):
""" See: https://core.telegram.org/bots/api#exportchatinvitelink """
p = _strip(locals())
return self._api_request('exportChatInviteLink', _rectify(p)) |
See: https://core.telegram.org/bots/api#setchatphoto | def setChatPhoto(self, chat_id, photo):
""" See: https://core.telegram.org/bots/api#setchatphoto """
p = _strip(locals(), more=['photo'])
return self._api_request_with_file('setChatPhoto', _rectify(p), 'photo', photo) |
See: https://core.telegram.org/bots/api#deletechatphoto | def deleteChatPhoto(self, chat_id):
""" See: https://core.telegram.org/bots/api#deletechatphoto """
p = _strip(locals())
return self._api_request('deleteChatPhoto', _rectify(p)) |
See: https://core.telegram.org/bots/api#leavechat | def leaveChat(self, chat_id):
""" See: https://core.telegram.org/bots/api#leavechat """
p = _strip(locals())
return self._api_request('leaveChat', _rectify(p)) |
See: https://core.telegram.org/bots/api#getchat | def getChat(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchat """
p = _strip(locals())
return self._api_request('getChat', _rectify(p)) |
See: https://core.telegram.org/bots/api#getchatadministrators | def getChatAdministrators(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchatadministrators """
p = _strip(locals())
return self._api_request('getChatAdministrators', _rectify(p)) |
See: https://core.telegram.org/bots/api#getchatmemberscount | def getChatMembersCount(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchatmemberscount """
p = _strip(locals())
return self._api_request('getChatMembersCount', _rectify(p)) |
See: https://core.telegram.org/bots/api#answershippingquery | def answerShippingQuery(self, shipping_query_id, ok,
shipping_options=None,
error_message=None):
""" See: https://core.telegram.org/bots/api#answershippingquery """
p = _strip(locals())
return self._api_request('answerShippingQuery', _recti... |
See: https://core.telegram.org/bots/api#answerprecheckoutquery | def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
error_message=None):
""" See: https://core.telegram.org/bots/api#answerprecheckoutquery """
p = _strip(locals())
return self._api_request('answerPreCheckoutQuery', _rectify(p)) |
See: https://core.telegram.org/bots/api#editmessagetext
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``),
a 1-tuple (``inline_message_id``),
or simply ``inline_message_id``.
You may extract this value easily with :meth:`telepot.message_identifier` | def editMessageText(self, msg_identifier, text,
parse_mode=None,
disable_web_page_preview=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagetext
:param msg_identifier:
a 2-tuple (`... |
See: https://core.telegram.org/bots/api#editmessagecaption
:param msg_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText` | def editMessageCaption(self, msg_identifier,
caption=None,
parse_mode=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagecaption
:param msg_identifier: Same as ``msg_identifier`` in :m... |
See: https://core.telegram.org/bots/api#uploadstickerfile | def uploadStickerFile(self, user_id, png_sticker):
"""
See: https://core.telegram.org/bots/api#uploadstickerfile
"""
p = _strip(locals(), more=['png_sticker'])
return self._api_request_with_file('uploadStickerFile', _rectify(p), 'png_sticker', png_sticker) |
See: https://core.telegram.org/bots/api#createnewstickerset | def createNewStickerSet(self, user_id, name, title, png_sticker, emojis,
contains_masks=None,
mask_position=None):
"""
See: https://core.telegram.org/bots/api#createnewstickerset
"""
p = _strip(locals(), more=['png_sticker'])
... |
See: https://core.telegram.org/bots/api#addstickertoset | def addStickerToSet(self, user_id, name, png_sticker, emojis,
mask_position=None):
"""
See: https://core.telegram.org/bots/api#addstickertoset
"""
p = _strip(locals(), more=['png_sticker'])
return self._api_request_with_file('addStickerToSet', _rectify(p),... |
See: https://core.telegram.org/bots/api#setstickerpositioninset | def setStickerPositionInSet(self, sticker, position):
"""
See: https://core.telegram.org/bots/api#setstickerpositioninset
"""
p = _strip(locals())
return self._api_request('setStickerPositionInSet', _rectify(p)) |
See: https://core.telegram.org/bots/api#setgamescore
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText` | def setGameScore(self, user_id, score, game_message_identifier,
force=None,
disable_edit_message=None):
"""
See: https://core.telegram.org/bots/api#setgamescore
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessage... |
See: https://core.telegram.org/bots/api#getgamehighscores
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText` | def getGameHighScores(self, user_id, game_message_identifier):
"""
See: https://core.telegram.org/bots/api#getgamehighscores
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText`
"""
p = _strip(locals(), more=['game_message_identifier'... |
Download a file to local disk.
:param dest: a path or a ``file`` object | def download_file(self, file_id, dest):
"""
Download a file to local disk.
:param dest: a path or a ``file`` object
"""
f = self.getFile(file_id)
try:
d = dest if _isfile(dest) else open(dest, 'wb')
r = api.download((self._token, f['file_path']),... |
:param s:
a list or set of chat id
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns the chat id only if the chat id is in ``s``
and chat type is in ``types``. | def per_chat_id_in(s, types='all'):
"""
:param s:
a list or set of chat id
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns the chat id only if the chat id is in ``s``
and chat type is in ``types... |
:param s:
a list or set of chat id
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns the chat id only if the chat id is *not* in ``s``
and chat type is in ``types``. | def per_chat_id_except(s, types='all'):
"""
:param s:
a list or set of chat id
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns the chat id only if the chat id is *not* in ``s``
and chat type is ... |
:param flavors:
``all`` or a list of flavors
:return:
a seeder function that returns the from id only if the message flavor is
in ``flavors``. | def per_from_id(flavors=chat_flavors+inline_flavors):
"""
:param flavors:
``all`` or a list of flavors
:return:
a seeder function that returns the from id only if the message flavor is
in ``flavors``.
"""
return _wrap_none(lambda msg:
msg['from']['i... |
:param s:
a list or set of from id
:param flavors:
``all`` or a list of flavors
:return:
a seeder function that returns the from id only if the from id is in ``s``
and message flavor is in ``flavors``. | def per_from_id_in(s, flavors=chat_flavors+inline_flavors):
"""
:param s:
a list or set of from id
:param flavors:
``all`` or a list of flavors
:return:
a seeder function that returns the from id only if the from id is in ``s``
and message flavor is in ``flavors``.
... |
:param s:
a list or set of from id
:param flavors:
``all`` or a list of flavors
:return:
a seeder function that returns the from id only if the from id is *not* in ``s``
and message flavor is in ``flavors``. | def per_from_id_except(s, flavors=chat_flavors+inline_flavors):
"""
:param s:
a list or set of from id
:param flavors:
``all`` or a list of flavors
:return:
a seeder function that returns the from id only if the from id is *not* in ``s``
and message flavor is in ``flavo... |
:return:
a seeder function that returns an event's source id only if that event's
source space equals to ``event_space``. | def per_event_source_id(event_space):
"""
:return:
a seeder function that returns an event's source id only if that event's
source space equals to ``event_space``.
"""
def f(event):
if is_event(event):
v = peel(event)
if v['source']['space'] == event_space... |
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns a callback query's originating chat id
if the chat type is in ``types``. | def per_callback_query_chat_id(types='all'):
"""
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns a callback query's originating chat id
if the chat type is in ``types``.
"""
def f(msg):
if (f... |
:param origins:
``all`` or a list of origin types (``chat``, ``inline``)
:return:
a seeder function that returns a callback query's origin identifier if
that origin type is in ``origins``. The origin identifier is guaranteed
to be a tuple. | def per_callback_query_origin(origins='all'):
"""
:param origins:
``all`` or a list of origin types (``chat``, ``inline``)
:return:
a seeder function that returns a callback query's origin identifier if
that origin type is in ``origins``. The origin identifier is guaranteed
... |
:return:
a delegator function that returns a tuple (``func``, (seed tuple,)+ ``args``, ``kwargs``).
That is, seed tuple is inserted before supplied positional arguments.
By default, a thread wrapping ``func`` and all those arguments is spawned. | def call(func, *args, **kwargs):
"""
:return:
a delegator function that returns a tuple (``func``, (seed tuple,)+ ``args``, ``kwargs``).
That is, seed tuple is inserted before supplied positional arguments.
By default, a thread wrapping ``func`` and all those arguments is spawned.
""... |
:return:
a delegator function that calls the ``cls`` constructor whose arguments being
a seed tuple followed by supplied ``*args`` and ``**kwargs``, then returns
the object's ``run`` method. By default, a thread wrapping that ``run`` method
is spawned. | def create_run(cls, *args, **kwargs):
"""
:return:
a delegator function that calls the ``cls`` constructor whose arguments being
a seed tuple followed by supplied ``*args`` and ``**kwargs``, then returns
the object's ``run`` method. By default, a thread wrapping that ``run`` method
... |
:return:
a delegator function that calls the ``cls`` constructor whose arguments being
a seed tuple followed by supplied ``*args`` and ``**kwargs``, then returns
a looping function that uses the object's ``listener`` to wait for messages
and invokes instance method ``open``, ``on_message... | def create_open(cls, *args, **kwargs):
"""
:return:
a delegator function that calls the ``cls`` constructor whose arguments being
a seed tuple followed by supplied ``*args`` and ``**kwargs``, then returns
a looping function that uses the object's ``listener`` to wait for messages
... |
Try a list of seeder functions until a condition is met.
:param condition:
a function that takes one argument - a seed - and returns ``True``
or ``False``
:param fns:
a list of seeder functions
:return:
a "composite" seeder function that calls each supplied function in tur... | def until(condition, fns):
"""
Try a list of seeder functions until a condition is met.
:param condition:
a function that takes one argument - a seed - and returns ``True``
or ``False``
:param fns:
a list of seeder functions
:return:
a "composite" seeder function t... |
The basic pair producer.
:return:
a (seeder, delegator_factory(\*args, \*\*kwargs)) tuple.
:param seeders:
If it is a seeder function or a list of one seeder function, it is returned
as the final seeder. If it is a list of more than one seeder function, they
are chained togethe... | def pair(seeders, delegator_factory, *args, **kwargs):
"""
The basic pair producer.
:return:
a (seeder, delegator_factory(\*args, \*\*kwargs)) tuple.
:param seeders:
If it is a seeder function or a list of one seeder function, it is returned
as the final seeder. If it is a list... |
:return:
a pair producer that ensures the seeder and delegator share the same event space. | def pave_event_space(fn=pair):
"""
:return:
a pair producer that ensures the seeder and delegator share the same event space.
"""
global _event_space
event_space = next(_event_space)
@_ensure_seeders_list
def p(seeders, delegator_factory, *args, **kwargs):
return fn(seeders ... |
:return:
a pair producer that enables static callback query capturing
across seeder and delegator.
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``) | def include_callback_query_chat_id(fn=pair, types='all'):
"""
:return:
a pair producer that enables static callback query capturing
across seeder and delegator.
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
"""
@_ensure_seeders_list
... |
:return:
a pair producer that enables dynamic callback query origin mapping
across seeder and delegator.
:param origins:
``all`` or a list of origin types (``chat``, ``inline``).
Origin mapping is only enabled for specified origin types. | def intercept_callback_query_origin(fn=pair, origins='all'):
"""
:return:
a pair producer that enables dynamic callback query origin mapping
across seeder and delegator.
:param origins:
``all`` or a list of origin types (``chat``, ``inline``).
Origin mapping is only enabled ... |
Access Bot API through a proxy.
:param url: proxy URL
:param basic_auth: 2-tuple ``('username', 'password')`` | def set_proxy(url, basic_auth=None):
"""
Access Bot API through a proxy.
:param url: proxy URL
:param basic_auth: 2-tuple ``('username', 'password')``
"""
global _pools, _onetime_pool_spec
if not url:
_pools['default'] = urllib3.PoolManager(**_default_pool_params)
_onetime_p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.