INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Add a query to the current transaction. A thin wrapper around ConnectionManager. add_query. | def add_query(self, sql, auto_begin=True, bindings=None,
abridge_sql_log=False):
"""Add a query to the current transaction. A thin wrapper around
ConnectionManager.add_query.
:param str sql: The SQL query to add
:param bool auto_begin: If set and there is no transactio... |
1. Create a new column ( w/ temp name and correct type ) 2. Copy data over to it 3. Drop the existing column ( cascade! ) 4. Rename the new column to existing column | def alter_column_type(self, relation, column_name, new_column_type):
"""
1. Create a new column (w/ temp name and correct type)
2. Copy data over to it
3. Drop the existing column (cascade!)
4. Rename the new column to existing column
"""
kwargs = {
'r... |
Return True if the unique ID matches the given name package and type. | def id_matches(unique_id, target_name, target_package, nodetypes, model):
"""Return True if the unique ID matches the given name, package, and type.
If package is None, any package is allowed.
nodetypes should be a container of NodeTypes that implements the 'in'
operator.
"""
node_type = model.... |
Find an entry in a subgraph by name. Any mapping that implements. items () and maps unique id - > something can be used as the subgraph. | def find_in_subgraph_by_name(subgraph, target_name, target_package, nodetype):
"""Find an entry in a subgraph by name. Any mapping that implements
.items() and maps unique id -> something can be used as the subgraph.
Names are like:
'{nodetype}.{target_package}.{target_name}'
You can use `None... |
Find an entry in the given list by name. | def find_in_list_by_name(haystack, target_name, target_package, nodetype):
"""Find an entry in the given list by name."""
for model in haystack:
name = model.get('unique_id')
if id_matches(name, target_name, target_package, nodetype, model):
return model
return None |
>>> dbt. utils. deep_merge ( { a: 1 b: 2 c: 3 } { a: 2 } { a: 3 b: 1 } ) # noqa { a: 3 b: 1 c: 3 } | def deep_merge(*args):
"""
>>> dbt.utils.deep_merge({'a': 1, 'b': 2, 'c': 3}, {'a': 2}, {'a': 3, 'b': 1}) # noqa
{'a': 3, 'b': 1, 'c': 3}
"""
if len(args) == 0:
return None
if len(args) == 1:
return copy.deepcopy(args[0])
lst = list(args)
last = copy.deepcopy(lst.pop(l... |
map the function func () onto each non - container value in value recursively returning a new value. As long as func does not manipulate value then deep_map will also not manipulate it. | def deep_map(func, value):
"""map the function func() onto each non-container value in 'value'
recursively, returning a new value. As long as func does not manipulate
value, then deep_map will also not manipulate it.
value should be a value returned by `yaml.safe_load` or `json.load` - the
only exp... |
Given a dict of keyword arguments and a dict mapping aliases to their canonical values canonicalize the keys in the kwargs dict. | def translate_aliases(kwargs, aliases):
"""Given a dict of keyword arguments and a dict mapping aliases to their
canonical values, canonicalize the keys in the kwargs dict.
:return: A dict continaing all the values in kwargs referenced by their
canonical key.
:raises: `AliasException`, if a can... |
Performs a shallow clone of the repository into the downloads directory. This function can be called repeatedly. If the project has already been checked out at this version it will be a no - op. Returns the path to the checked out directory. | def _checkout(self, project):
"""Performs a shallow clone of the repository into the downloads
directory. This function can be called repeatedly. If the project has
already been checked out at this version, it will be a no-op. Returns
the path to the checked out directory."""
if ... |
In Redshift DROP TABLE... CASCADE should not be used inside a transaction. Redshift doesn t prevent the CASCADE part from conflicting with concurrent transactions. If we do attempt to drop two tables with CASCADE at once we ll often get the dreaded: | def drop_relation(self, relation):
"""
In Redshift, DROP TABLE ... CASCADE should not be used
inside a transaction. Redshift doesn't prevent the CASCADE
part from conflicting with concurrent transactions. If we do
attempt to drop two tables with CASCADE at once, we'll often
... |
Load and parse documentation in a list of projects. Returns a list of ParsedNodes. | def load_file(cls, package_name, root_dir, relative_dirs):
"""Load and parse documentation in a list of projects. Returns a list
of ParsedNodes.
"""
extension = "[!.#~]*.md"
file_matches = dbt.clients.system.find_matching(
root_dir,
relative_dirs,
... |
Config resolution order: | def config(self):
"""
Config resolution order:
if this is a dependency model:
- own project config
- in-model config
- active project config
if this is a top-level model:
- active project config
- in-model config
"""
... |
Expect a comment end and return the match object. | def expect_comment_end(self):
"""Expect a comment end and return the match object.
"""
match = self._expect_match('#}', COMMENT_END_PATTERN)
self.advance(match.end()) |
Handle a block. The current state of the parser should be after the open block is completed: { % blk foo % } my data { % endblk % } ^ right here | def handle_block(self, match, block_start=None):
"""Handle a block. The current state of the parser should be after the
open block is completed:
{% blk foo %}my data {% endblk %}
^ right here
"""
# we have to handle comments inside blocks because you ... |
This is suspiciously similar to _process_macro_default_arg probably want to figure out how to merge the two. | 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(
... |
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. | 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... |
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 )) % } | 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. | 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. | 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. | 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. | 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 command line.: param threads_override Optional ... | 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. | 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 ] ) | 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 (). | 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. | 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. | 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. | 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: | 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: | 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 | 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 ignore child threads. | 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. | 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 thus ensuring at most one active task per us... | 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 | 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. | 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. | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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. | 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 | 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 | 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 | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.