docstring
stringlengths 52
499
| function
stringlengths 67
35.2k
| __index_level_0__
int64 52.6k
1.16M
|
---|---|---|
This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
- in: path
name: todo_id
required: true
description: The ID of the task, try 42!
type: string
responses:
201:
description: The task has been updated
schema:
$ref: '#/definitions/Task' | def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201 | 142,530 |
This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
responses:
201:
description: The task has been created
schema:
$ref: '#/definitions/Task' | def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201 | 142,531 |
Post a message on the screen with Messenger.
Arguments:
message: The message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the program waits until the message completes.
style: "info", "success", or "error".
You can also post messages by using =>
self.execute_script('Messenger().post("My Message")') | def post_message(self, message, duration=None, pause=True, style="info"):
if not duration:
if not self.message_duration:
duration = settings.DEFAULT_MESSAGE_DURATION
else:
duration = self.message_duration
js_utils.post_message(
self.driver, message, duration, style=style)
if pause:
duration = float(duration) + 0.15
time.sleep(float(duration)) | 143,799 |
Validate value of `key` in `obj` using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
key (str): key to be validated in `obj`.
validation_fun (function): function used to validate the value
of `key`.
Returns:
None: indicates validation successful
Raises:
ValidationError: `validation_fun` will raise exception on failure | def validate_txn_obj(obj_name, obj, key, validation_fun):
backend = bigchaindb.config['database']['backend']
if backend == 'localmongodb':
data = obj.get(key, {})
if isinstance(data, dict):
validate_all_keys_in_obj(obj_name, data, validation_fun)
elif isinstance(data, list):
validate_all_items_in_list(obj_name, data, validation_fun) | 144,847 |
Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the value
of `key`.
Returns:
None: indicates validation successful
Raises:
ValidationError: `validation_fun` will raise this error on failure | def validate_all_keys_in_obj(obj_name, obj, validation_fun):
for key, value in obj.items():
validation_fun(obj_name, key)
if isinstance(value, dict):
validate_all_keys_in_obj(obj_name, value, validation_fun)
elif isinstance(value, list):
validate_all_items_in_list(obj_name, value, validation_fun) | 144,849 |
Validate value for all (nested) occurrence of `key` in `obj`
using `validation_fun`.
Args:
obj (dict): dictionary object.
key (str): key whose value is to be validated.
validation_fun (function): function used to validate the value
of `key`.
Raises:
ValidationError: `validation_fun` will raise this error on failure | def validate_all_values_for_key_in_obj(obj, key, validation_fun):
for vkey, value in obj.items():
if vkey == key:
validation_fun(value)
elif isinstance(value, dict):
validate_all_values_for_key_in_obj(value, key, validation_fun)
elif isinstance(value, list):
validate_all_values_for_key_in_list(value, key, validation_fun) | 144,850 |
Check if `key` contains ".", "$" or null characters.
https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
Args:
obj_name (str): object name to use when raising exception
key (str): key to validated
Returns:
None: validation successful
Raises:
ValidationError: will raise exception in case of regex match. | def validate_key(obj_name, key):
if re.search(r'^[$]|\.|\x00', key):
error_str = ('Invalid key name "{}" in {} object. The '
'key name cannot contain characters '
'".", "$" or null characters').format(key, obj_name)
raise ValidationError(error_str) | 144,852 |
Return an instance of the Flask application.
Args:
debug (bool): a flag to activate the debug mode for the app
(default: False).
threads (int): number of threads to use
Return:
an instance of the Flask application. | def create_app(*, debug=False, threads=1, bigchaindb_factory=None):
if not bigchaindb_factory:
bigchaindb_factory = BigchainDB
app = Flask(__name__)
app.wsgi_app = StripContentTypeMiddleware(app.wsgi_app)
CORS(app)
app.debug = debug
app.config['bigchain_pool'] = utils.pool(bigchaindb_factory, size=threads)
add_routes(app)
return app | 144,853 |
Wrap and return an application ready to be run.
Args:
settings (dict): a dictionary containing the settings, more info
here http://docs.gunicorn.org/en/latest/settings.html
Return:
an initialized instance of the application. | def create_server(settings, log_config=None, bigchaindb_factory=None):
settings = copy.deepcopy(settings)
if not settings.get('workers'):
settings['workers'] = (multiprocessing.cpu_count() * 2) + 1
if not settings.get('threads'):
# Note: Threading is not recommended currently, as the frontend workload
# is largely CPU bound and parallisation across Python threads makes it
# slower.
settings['threads'] = 1
settings['custom_log_config'] = log_config
app = create_app(debug=settings.get('debug', False),
threads=settings['threads'],
bigchaindb_factory=bigchaindb_factory)
standalone = StandaloneApplication(app, options=settings)
return standalone | 144,854 |
Initialize a new standalone application.
Args:
app: A wsgi Python application.
options (dict): the configuration. | def __init__(self, app, *, options=None):
self.options = options or {}
self.application = app
super().__init__() | 144,855 |
Decorator to be used by command line functions, such that the
configuration of bigchaindb is performed before the execution of
the command.
Args:
command: The command to decorate.
Returns:
The command wrapper function. | def configure_bigchaindb(command):
@functools.wraps(command)
def configure(args):
config_from_cmdline = None
try:
if args.log_level is not None:
config_from_cmdline = {
'log': {
'level_console': args.log_level,
'level_logfile': args.log_level,
},
'server': {'loglevel': args.log_level},
}
except AttributeError:
pass
bigchaindb.config_utils.autoconfigure(
filename=args.config, config=config_from_cmdline, force=True)
command(args)
return configure | 144,863 |
Output a string to stderr and wait for input.
Args:
prompt (str): the message to display.
default: the default value to return if the user
leaves the field empty
convert (callable): a callable to be used to convert
the value the user inserted. If None, the type of
``default`` will be used. | def input_on_stderr(prompt='', default=None, convert=None):
print(prompt, end='', file=sys.stderr)
value = builtins.input()
return _convert(value, default, convert) | 144,865 |
API endpoint to perform a text search on the assets.
Args:
search (str): Text search string to query the text index
limit (int, optional): Limit the number of returned documents.
Return:
A list of assets that match the query. | def get(self):
parser = reqparse.RequestParser()
parser.add_argument('search', type=str, required=True)
parser.add_argument('limit', type=int)
args = parser.parse_args()
if not args['search']:
return make_error(400, 'text_search cannot be empty')
if not args['limit']:
# if the limit is not specified do not pass None to `text_search`
del args['limit']
pool = current_app.config['bigchain_pool']
with pool() as bigchain:
assets = bigchain.text_search(**args)
try:
# This only works with MongoDB as the backend
return list(assets)
except OperationError as e:
return make_error(
400,
'({}): {}'.format(type(e).__name__, e)
) | 144,867 |
Validate the transaction before entry into
the mempool.
Args:
raw_tx: a raw string (in bytes) transaction. | def check_tx(self, raw_transaction):
self.abort_if_abci_chain_is_not_synced()
logger.debug('check_tx: %s', raw_transaction)
transaction = decode_transaction(raw_transaction)
if self.bigchaindb.is_valid_transaction(transaction):
logger.debug('check_tx: VALID')
return ResponseCheckTx(code=CodeTypeOk)
else:
logger.debug('check_tx: INVALID')
return ResponseCheckTx(code=CodeTypeError) | 144,873 |
Initialize list of transaction.
Args:
req_begin_block: block object which contains block header
and block hash. | def begin_block(self, req_begin_block):
self.abort_if_abci_chain_is_not_synced()
chain_shift = 0 if self.chain is None else self.chain['height']
logger.debug('BEGIN BLOCK, height:%s, num_txs:%s',
req_begin_block.header.height + chain_shift,
req_begin_block.header.num_txs)
self.block_txn_ids = []
self.block_transactions = []
return ResponseBeginBlock() | 144,874 |
Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction. | def deliver_tx(self, raw_transaction):
self.abort_if_abci_chain_is_not_synced()
logger.debug('deliver_tx: %s', raw_transaction)
transaction = self.bigchaindb.is_valid_transaction(
decode_transaction(raw_transaction), self.block_transactions)
if not transaction:
logger.debug('deliver_tx: INVALID')
return ResponseDeliverTx(code=CodeTypeError)
else:
logger.debug('storing tx')
self.block_txn_ids.append(transaction.id)
self.block_transactions.append(transaction)
return ResponseDeliverTx(code=CodeTypeOk) | 144,875 |
Calculate block hash using transaction ids and previous block
hash to be stored in the next block.
Args:
height (int): new height of the chain. | def end_block(self, request_end_block):
self.abort_if_abci_chain_is_not_synced()
chain_shift = 0 if self.chain is None else self.chain['height']
height = request_end_block.height + chain_shift
self.new_height = height
# store pre-commit state to recover in case there is a crash during
# `end_block` or `commit`
logger.debug(f'Updating pre-commit state: {self.new_height}')
pre_commit_state = dict(height=self.new_height,
transactions=self.block_txn_ids)
self.bigchaindb.store_pre_commit_state(pre_commit_state)
block_txn_hash = calculate_hash(self.block_txn_ids)
block = self.bigchaindb.get_latest_block()
if self.block_txn_ids:
self.block_txn_hash = calculate_hash([block['app_hash'], block_txn_hash])
else:
self.block_txn_hash = block['app_hash']
validator_update = Election.process_block(self.bigchaindb,
self.new_height,
self.block_transactions)
return ResponseEndBlock(validator_updates=validator_update) | 144,876 |
Creates a new event.
Args:
event_type (int): the type of the event, see
:class:`~bigchaindb.events.EventTypes`
event_data (obj): the data of the event. | def __init__(self, event_type, event_data):
self.type = event_type
self.data = event_data | 144,882 |
Initialize the configured backend for use with BigchainDB.
Creates a database with :attr:`dbname` with any required tables
and supporting indexes.
Args:
connection (:class:`~bigchaindb.backend.connection.Connection`): an
existing connection to use to initialize the database.
Creates one if not given.
dbname (str): the name of the database to create.
Defaults to the database name given in the BigchainDB
configuration. | def init_database(connection=None, dbname=None):
connection = connection or connect()
dbname = dbname or bigchaindb.config['database']['name']
create_database(connection, dbname)
create_tables(connection, dbname) | 144,897 |
Validate all nested "language" key in `obj`.
Args:
obj (dict): dictionary whose "language" key is to be validated.
Returns:
None: validation successful
Raises:
ValidationError: will raise exception in case language is not valid. | def validate_language_key(obj, key):
backend = bigchaindb.config['database']['backend']
if backend == 'localmongodb':
data = obj.get(key, {})
if isinstance(data, dict):
validate_all_values_for_key_in_obj(data, 'language', validate_language)
elif isinstance(data, list):
validate_all_values_for_key_in_list(data, 'language', validate_language) | 144,898 |
API endpoint to get details about a block.
Args:
block_id (str): the id of the block.
Return:
A JSON string containing the data about the block. | def get(self, block_id):
pool = current_app.config['bigchain_pool']
with pool() as bigchain:
block = bigchain.get_block(block_id=block_id)
if not block:
return make_error(404)
return block | 144,900 |
Encode a fulfillment as a details dictionary
Args:
fulfillment: Crypto-conditions Fulfillment object | def _fulfillment_to_details(fulfillment):
if fulfillment.type_name == 'ed25519-sha-256':
return {
'type': 'ed25519-sha-256',
'public_key': base58.b58encode(fulfillment.public_key).decode(),
}
if fulfillment.type_name == 'threshold-sha-256':
subconditions = [
_fulfillment_to_details(cond['body'])
for cond in fulfillment.subconditions
]
return {
'type': 'threshold-sha-256',
'threshold': fulfillment.threshold,
'subconditions': subconditions,
}
raise UnsupportedTypeError(fulfillment.type_name) | 144,904 |
Load a fulfillment for a signing spec dictionary
Args:
data: tx.output[].condition.details dictionary | def _fulfillment_from_details(data, _depth=0):
if _depth == 100:
raise ThresholdTooDeep()
if data['type'] == 'ed25519-sha-256':
public_key = base58.b58decode(data['public_key'])
return Ed25519Sha256(public_key=public_key)
if data['type'] == 'threshold-sha-256':
threshold = ThresholdSha256(data['threshold'])
for cond in data['subconditions']:
cond = _fulfillment_from_details(cond, _depth+1)
threshold.add_subfulfillment(cond)
return threshold
raise UnsupportedTypeError(data.get('type')) | 144,905 |
Transforms a Python dictionary to an Input object.
Note:
Optionally, this method can also serialize a Cryptoconditions-
Fulfillment that is not yet signed.
Args:
data (dict): The Input to be transformed.
Returns:
:class:`~bigchaindb.common.transaction.Input`
Raises:
InvalidSignature: If an Input's URI couldn't be parsed. | def from_dict(cls, data):
fulfillment = data['fulfillment']
if not isinstance(fulfillment, (Fulfillment, type(None))):
try:
fulfillment = Fulfillment.from_uri(data['fulfillment'])
except ASN1DecodeError:
# TODO Remove as it is legacy code, and simply fall back on
# ASN1DecodeError
raise InvalidSignature("Fulfillment URI couldn't been parsed")
except TypeError:
# NOTE: See comment about this special case in
# `Input.to_dict`
fulfillment = _fulfillment_from_details(data['fulfillment'])
fulfills = TransactionLink.from_dict(data['fulfills'])
return cls(fulfillment, data['owners_before'], fulfills) | 144,909 |
Transforms a Python dictionary to an Output object.
Note:
To pass a serialization cycle multiple times, a
Cryptoconditions Fulfillment needs to be present in the
passed-in dictionary, as Condition URIs are not serializable
anymore.
Args:
data (dict): The dict to be transformed.
Returns:
:class:`~bigchaindb.common.transaction.Output` | def from_dict(cls, data):
try:
fulfillment = _fulfillment_from_details(data['condition']['details'])
except KeyError:
# NOTE: Hashlock condition case
fulfillment = data['condition']['uri']
try:
amount = int(data['amount'])
except ValueError:
raise AmountError('Invalid amount: %s' % data['amount'])
return cls(fulfillment, data['public_keys'], amount) | 144,917 |
Adds an input to a Transaction's list of inputs.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`): An Input to be added to the Transaction. | def add_input(self, input_):
if not isinstance(input_, Input):
raise TypeError('`input_` must be a Input instance')
self.inputs.append(input_) | 144,924 |
Adds an output to a Transaction's list of outputs.
Args:
output (:class:`~bigchaindb.common.transaction.
Output`): An Output to be added to the
Transaction. | def add_output(self, output):
if not isinstance(output, Output):
raise TypeError('`output` must be an Output instance or None')
self.outputs.append(output) | 144,925 |
Signs a single Input.
Note:
This method works only for the following Cryptoconditions
currently:
- Ed25519Fulfillment
- ThresholdSha256.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The Input to be signed.
message (str): The message to be signed
key_pairs (dict): The keys to sign the Transaction with. | def _sign_input(cls, input_, message, key_pairs):
if isinstance(input_.fulfillment, Ed25519Sha256):
return cls._sign_simple_signature_fulfillment(input_, message,
key_pairs)
elif isinstance(input_.fulfillment, ThresholdSha256):
return cls._sign_threshold_signature_fulfillment(input_, message,
key_pairs)
else:
raise ValueError("Fulfillment couldn't be matched to "
'Cryptocondition fulfillment type.') | 144,927 |
Signs a Ed25519Fulfillment.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The input to be signed.
message (str): The message to be signed
key_pairs (dict): The keys to sign the Transaction with. | def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
# NOTE: To eliminate the dangers of accidentally signing a condition by
# reference, we remove the reference of input_ here
# intentionally. If the user of this class knows how to use it,
# this should never happen, but then again, never say never.
input_ = deepcopy(input_)
public_key = input_.owners_before[0]
message = sha3_256(message.encode())
if input_.fulfills:
message.update('{}{}'.format(
input_.fulfills.txid, input_.fulfills.output).encode())
try:
# cryptoconditions makes no assumptions of the encoding of the
# message to sign or verify. It only accepts bytestrings
input_.fulfillment.sign(
message.digest(), base58.b58decode(key_pairs[public_key].encode()))
except KeyError:
raise KeypairMismatchException('Public key {} is not a pair to '
'any of the private keys'
.format(public_key))
return input_ | 144,928 |
Signs a ThresholdSha256.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The Input to be signed.
message (str): The message to be signed
key_pairs (dict): The keys to sign the Transaction with. | def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs):
input_ = deepcopy(input_)
message = sha3_256(message.encode())
if input_.fulfills:
message.update('{}{}'.format(
input_.fulfills.txid, input_.fulfills.output).encode())
for owner_before in set(input_.owners_before):
# TODO: CC should throw a KeypairMismatchException, instead of
# our manual mapping here
# TODO FOR CC: Naming wise this is not so smart,
# `get_subcondition` in fact doesn't return a
# condition but a fulfillment
# TODO FOR CC: `get_subcondition` is singular. One would not
# expect to get a list back.
ccffill = input_.fulfillment
subffills = ccffill.get_subcondition_from_vk(
base58.b58decode(owner_before))
if not subffills:
raise KeypairMismatchException('Public key {} cannot be found '
'in the fulfillment'
.format(owner_before))
try:
private_key = key_pairs[owner_before]
except KeyError:
raise KeypairMismatchException('Public key {} is not a pair '
'to any of the private keys'
.format(owner_before))
# cryptoconditions makes no assumptions of the encoding of the
# message to sign or verify. It only accepts bytestrings
for subffill in subffills:
subffill.sign(
message.digest(), base58.b58decode(private_key.encode()))
return input_ | 144,929 |
Validates an Input against a given set of Outputs.
Note:
The number of `output_condition_uris` must be equal to the
number of Inputs a Transaction has.
Args:
output_condition_uris (:obj:`list` of :obj:`str`): A list of
Outputs to check the Inputs against.
Returns:
bool: If all Outputs are valid. | def _inputs_valid(self, output_condition_uris):
if len(self.inputs) != len(output_condition_uris):
raise ValueError('Inputs and '
'output_condition_uris must have the same count')
tx_dict = self.tx_dict if self.tx_dict else self.to_dict()
tx_dict = Transaction._remove_signatures(tx_dict)
tx_dict['id'] = None
tx_serialized = Transaction._to_str(tx_dict)
def validate(i, output_condition_uri=None):
return self._input_valid(self.inputs[i], self.operation,
tx_serialized, output_condition_uri)
return all(validate(i, cond)
for i, cond in enumerate(output_condition_uris)) | 144,930 |
Validate the transaction ID of a transaction
Args:
tx_body (dict): The Transaction to be transformed. | def validate_id(tx_body):
# NOTE: Remove reference to avoid side effects
# tx_body = deepcopy(tx_body)
tx_body = rapidjson.loads(rapidjson.dumps(tx_body))
try:
proposed_tx_id = tx_body['id']
except KeyError:
raise InvalidHash('No transaction id found!')
tx_body['id'] = None
tx_body_serialized = Transaction._to_str(tx_body)
valid_tx_id = Transaction._to_hash(tx_body_serialized)
if proposed_tx_id != valid_tx_id:
err_msg = ("The transaction's id '{}' isn't equal to "
"the hash of its body, i.e. it's not valid.")
raise InvalidHash(err_msg.format(proposed_tx_id)) | 144,934 |
Transforms a Python dictionary to a Transaction object.
Args:
tx_body (dict): The Transaction to be transformed.
Returns:
:class:`~bigchaindb.common.transaction.Transaction` | def from_dict(cls, tx, skip_schema_validation=True):
operation = tx.get('operation', Transaction.CREATE) if isinstance(tx, dict) else Transaction.CREATE
cls = Transaction.resolve_class(operation)
if not skip_schema_validation:
cls.validate_id(tx)
cls.validate_schema(tx)
inputs = [Input.from_dict(input_) for input_ in tx['inputs']]
outputs = [Output.from_dict(output) for output in tx['outputs']]
return cls(tx['operation'], tx['asset'], inputs, outputs,
tx['metadata'], tx['version'], hash_id=tx['id'], tx_dict=tx) | 144,935 |
Returns the config values found in a configuration file.
Args:
filename (str): the JSON file with the configuration values.
If ``None``, CONFIG_DEFAULT_PATH will be used.
Returns:
dict: The config values in the specified config file (or the
file at CONFIG_DEFAULT_PATH, if filename == None) | def file_config(filename=None):
logger.debug('On entry into file_config(), filename = {}'.format(filename))
if filename is None:
filename = CONFIG_DEFAULT_PATH
logger.debug('file_config() will try to open `{}`'.format(filename))
with open(filename) as f:
try:
config = json.load(f)
except ValueError as err:
raise exceptions.ConfigurationError(
'Failed to parse the JSON configuration from `{}`, {}'.format(filename, err)
)
logger.info('Configuration loaded from `{}`'.format(filename))
return config | 144,964 |
Set bigchaindb.config equal to the default config dict,
then update that with whatever is in the provided config dict,
and then set bigchaindb.config['CONFIGURED'] = True
Args:
config (dict): the config dict to read for changes
to the default config
Note:
Any previous changes made to ``bigchaindb.config`` will be lost. | def set_config(config):
# Deep copy the default config into bigchaindb.config
bigchaindb.config = copy.deepcopy(bigchaindb._config)
# Update the default config with whatever is in the passed config
update(bigchaindb.config, update_types(config, bigchaindb.config))
bigchaindb.config['CONFIGURED'] = True | 144,967 |
Update bigchaindb.config with whatever is in the provided config dict,
and then set bigchaindb.config['CONFIGURED'] = True
Args:
config (dict): the config dict to read for changes
to the default config | def update_config(config):
# Update the default config with whatever is in the passed config
update(bigchaindb.config, update_types(config, bigchaindb.config))
bigchaindb.config['CONFIGURED'] = True | 144,968 |
Write the provided configuration to a specific location.
Args:
config (dict): a dictionary with the configuration to load.
filename (str): the name of the file that will store the new configuration. Defaults to ``None``.
If ``None``, the HOME of the current user and the string ``.bigchaindb`` will be used. | def write_config(config, filename=None):
if not filename:
filename = CONFIG_DEFAULT_PATH
with open(filename, 'w') as f:
json.dump(config, f, indent=4) | 144,969 |
Find and load the chosen validation plugin.
Args:
name (string): the name of the entry_point, as advertised in the
setup.py of the providing package.
Returns:
an uninstantiated subclass of ``bigchaindb.validation.AbstractValidationRules`` | def load_validation_plugin(name=None):
if not name:
return BaseValidationRules
# TODO: This will return the first plugin with group `bigchaindb.validation`
# and name `name` in the active WorkingSet.
# We should probably support Requirements specs in the config, e.g.
# validation_plugin: 'my-plugin-package==0.0.1;default'
plugin = None
for entry_point in iter_entry_points('bigchaindb.validation', name):
plugin = entry_point.load()
# No matching entry_point found
if not plugin:
raise ResolutionError(
'No plugin found in group `bigchaindb.validation` with name `{}`'.
format(name))
# Is this strictness desireable?
# It will probably reduce developer headaches in the wild.
if not issubclass(plugin, (BaseValidationRules,)):
raise TypeError('object of type "{}" does not implement `bigchaindb.'
'validation.BaseValidationRules`'.format(type(plugin)))
return plugin | 144,971 |
Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True if the public key is found in the condition details, False otherwise | def condition_details_has_owner(condition_details, owner):
if 'subconditions' in condition_details:
result = condition_details_has_owner(condition_details['subconditions'], owner)
if result:
return True
elif isinstance(condition_details, list):
for subcondition in condition_details:
result = condition_details_has_owner(subcondition, owner)
if result:
return True
else:
if 'public_key' in condition_details \
and owner == condition_details['public_key']:
return True
return False | 144,974 |
Run the recorded chain of methods on `instance`.
Args:
instance: an object. | def run(self, instance):
last = instance
for item in self.stack:
if isinstance(item, str):
last = getattr(last, item)
else:
last = last(*item[0], **item[1])
self.stack = []
return last | 144,981 |
API endpoint to get details about a transaction.
Args:
tx_id (str): the id of the transaction.
Return:
A JSON string containing the data about the transaction. | def get(self, tx_id):
pool = current_app.config['bigchain_pool']
with pool() as bigchain:
tx = bigchain.get_transaction(tx_id)
if not tx:
return make_error(404)
return tx.to_dict() | 144,989 |
Remove outputs that have been spent
Args:
outputs: list of TransactionLink | def filter_spent_outputs(self, outputs):
links = [o.to_dict() for o in outputs]
txs = list(query.get_spending_transactions(self.connection, links))
spends = {TransactionLink.from_dict(input_['fulfills'])
for tx in txs
for input_ in tx['inputs']}
return [ff for ff in outputs if ff not in spends] | 144,993 |
Update the UTXO set given ``transaction``. That is, remove
the outputs that the given ``transaction`` spends, and add the
outputs that the given ``transaction`` creates.
Args:
transaction (:obj:`~bigchaindb.models.Transaction`): A new
transaction incoming into the system for which the UTXO
set needs to be updated. | def update_utxoset(self, transaction):
spent_outputs = [
spent_output for spent_output in transaction.spent_outputs
]
if spent_outputs:
self.delete_unspent_outputs(*spent_outputs)
self.store_unspent_outputs(
*[utxo._asdict() for utxo in transaction.unspent_outputs]
) | 145,002 |
Store the given ``unspent_outputs`` (utxos).
Args:
*unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable
length tuple or list of unspent outputs. | def store_unspent_outputs(self, *unspent_outputs):
if unspent_outputs:
return backend.query.store_unspent_outputs(
self.connection, *unspent_outputs) | 145,003 |
Deletes the given ``unspent_outputs`` (utxos).
Args:
*unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable
length tuple or list of unspent outputs. | def delete_unspent_outputs(self, *unspent_outputs):
if unspent_outputs:
return backend.query.delete_unspent_outputs(
self.connection, *unspent_outputs) | 145,006 |
Get a list of output links filtered on some criteria
Args:
owner (str): base58 encoded public_key.
spent (bool): If ``True`` return only the spent outputs. If
``False`` return only unspent outputs. If spent is
not specified (``None``) return all outputs.
Returns:
:obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s
pointing to another transaction's condition | def get_outputs_filtered(self, owner, spent=None):
outputs = self.fastquery.get_outputs_by_public_key(owner)
if spent is None:
return outputs
elif spent is True:
return self.fastquery.filter_unspent_outputs(outputs)
elif spent is False:
return self.fastquery.filter_spent_outputs(outputs) | 145,010 |
Get the block with the specified `block_id`.
Returns the block corresponding to `block_id` or None if no match is
found.
Args:
block_id (int): block id of the block to get. | def get_block(self, block_id):
block = backend.query.get_block(self.connection, block_id)
latest_block = self.get_latest_block()
latest_block_height = latest_block['height'] if latest_block else 0
if not block and block_id > latest_block_height:
return
result = {'height': block_id,
'transactions': []}
if block:
transactions = backend.query.get_transactions(self.connection, block['transactions'])
result['transactions'] = [t.to_dict() for t in Transaction.from_db(self, transactions)]
return result | 145,012 |
Retrieve the list of blocks (block ids) containing a
transaction with transaction id `txid`
Args:
txid (str): transaction id of the transaction to query
Returns:
Block id list (list(int)) | def get_block_containing_tx(self, txid):
blocks = list(backend.query.get_block_with_transaction(self.connection, txid))
if len(blocks) > 1:
logger.critical('Transaction id %s exists in multiple blocks', txid)
return [block['height'] for block in blocks] | 145,013 |
Return an iterator of assets that match the text search
Args:
search (str): Text search string to query the text index
limit (int, optional): Limit the number of returned documents.
Returns:
iter: An iterator of assets that match the text search. | def text_search(self, search, *, limit=0, table='assets'):
return backend.query.text_search(self.connection, search, limit=limit,
table=table) | 145,016 |
Bridge between a synchronous multiprocessing queue
and an asynchronous asyncio queue.
Args:
in_queue (multiprocessing.Queue): input queue
out_queue (asyncio.Queue): output queue | def _multiprocessing_to_asyncio(in_queue, out_queue, loop):
while True:
value = in_queue.get()
loop.call_soon_threadsafe(out_queue.put_nowait, value) | 145,021 |
Computes the merkle root for a given list.
Args:
hashes (:obj:`list` of :obj:`bytes`): The leaves of the tree.
Returns:
str: Merkle root in hexadecimal form. | def merkleroot(hashes):
# XXX TEMPORARY -- MUST REVIEW and possibly CHANGE
# The idea here is that the UTXO SET would be empty and this function
# would be invoked to compute the merkle root, and since there is nothing,
# i.e. an empty list, then the hash of the empty string is returned.
# This seems too easy but maybe that is good enough? TO REVIEW!
if not hashes:
return sha3_256(b'').hexdigest()
# XXX END TEMPORARY -- MUST REVIEW ...
if len(hashes) == 1:
return hexlify(hashes[0]).decode()
if len(hashes) % 2 == 1:
hashes.append(hashes[-1])
parent_hashes = [
sha3_256(hashes[i] + hashes[i+1]).digest()
for i in range(0, len(hashes)-1, 2)
]
return merkleroot(parent_hashes) | 145,030 |
Validate transaction spend
Args:
bigchain (BigchainDB): an instantiated bigchaindb.BigchainDB object.
Returns:
The transaction (Transaction) if the transaction is valid else it
raises an exception describing the reason why the transaction is
invalid.
Raises:
ValidationError: If the transaction is invalid | def validate(self, bigchain, current_transactions=[]):
input_conditions = []
if self.operation == Transaction.CREATE:
duplicates = any(txn for txn in current_transactions if txn.id == self.id)
if bigchain.is_committed(self.id) or duplicates:
raise DuplicateTransaction('transaction `{}` already exists'
.format(self.id))
if not self.inputs_valid(input_conditions):
raise InvalidSignature('Transaction signature is invalid.')
elif self.operation == Transaction.TRANSFER:
self.validate_transfer_inputs(bigchain, current_transactions)
return self | 145,041 |
Create a new Connection instance.
Args:
replicaset (str, optional): the name of the replica set to
connect to.
**kwargs: arbitrary keyword arguments provided by the
configuration's ``database`` settings | def __init__(self, replicaset=None, ssl=None, login=None, password=None,
ca_cert=None, certfile=None, keyfile=None,
keyfile_passphrase=None, crlfile=None, **kwargs):
super().__init__(**kwargs)
self.replicaset = replicaset or bigchaindb.config['database'].get('replicaset')
self.ssl = ssl if ssl is not None else bigchaindb.config['database'].get('ssl', False)
self.login = login or bigchaindb.config['database'].get('login')
self.password = password or bigchaindb.config['database'].get('password')
self.ca_cert = ca_cert or bigchaindb.config['database'].get('ca_cert', None)
self.certfile = certfile or bigchaindb.config['database'].get('certfile', None)
self.keyfile = keyfile or bigchaindb.config['database'].get('keyfile', None)
self.keyfile_passphrase = keyfile_passphrase or bigchaindb.config['database'].get('keyfile_passphrase', None)
self.crlfile = crlfile or bigchaindb.config['database'].get('crlfile', None) | 145,043 |
Initialize the middleware.
Inherited initializer must call the "super init" method
at the beginning.
Args:
instance_id: Instance ID of the middleware. | def __init__(self, instance_id: Optional[str] = None):
self.instance_id = instance_id
if instance_id:
self.middleware_id += "#" + instance_id | 145,057 |
Initialize the channel.
Inherited initializer must call the "super init" method
at the beginning.
Args:
instance_id: Instance ID of the channel. | def __init__(self, instance_id: str = None):
self.instance_id = instance_id
if instance_id:
self.channel_id += "#" + instance_id | 145,087 |
Decorator for slave channel's "additional features" interface.
Args:
name (str): A human readable name for the function.
desc (str): A short description and usage of it. Use
``{function_name}`` in place of the function name
in the description.
Returns:
The decorated method. | def extra(name: str, desc: str) -> Callable:
def attr_dec(f):
f.__setattr__("extra_fn", True)
f.__setattr__("name", name)
f.__setattr__("desc", desc)
return f
return attr_dec | 145,104 |
Get the path for persistent storage of a module.
This method creates the queried path if not existing.
Args:
module_id (str): Module ID
Returns:
The data path of indicated module. | def get_data_path(module_id: str) -> Path:
profile = coordinator.profile
data_path = get_base_path() / 'profiles' / profile / module_id
if not data_path.exists():
data_path.mkdir(parents=True)
return data_path | 145,106 |
Get path for configuration file. Defaulted to
``~/.ehforwarderbot/profiles/profile_name/channel_id/config.yaml``.
This method creates the queried path if not existing. The config file will
not be created, however.
Args:
module_id (str): Module ID.
ext (Optional[Str]): Extension name of the config file.
Defaulted to ``"yaml"``.
Returns:
The path to the configuration file. | def get_config_path(module_id: str = None, ext: str = 'yaml') -> Path:
if module_id:
config_path = get_data_path(module_id)
else:
profile = coordinator.profile
config_path = get_base_path() / 'profiles' / profile
if not config_path.exists():
config_path.mkdir(parents=True)
return config_path / "config.{}".format(ext) | 145,107 |
Locate module by module ID
Args:
module_id: Module ID
module_type: Type of module, one of ``'master'``, ``'slave'`` and ``'middleware'`` | def locate_module(module_id: str, module_type: str = None):
entry_point = None
if module_type:
entry_point = 'ehforwarderbot.%s' % module_type
module_id = module_id.split('#', 1)[0]
if entry_point:
for i in pkg_resources.iter_entry_points(entry_point):
if i.name == module_id:
return i.load()
return pydoc.locate(module_id) | 145,109 |
Register the channel with the coordinator.
Args:
channel (EFBChannel): Channel to register | def add_channel(channel: EFBChannel):
global master, slaves
if isinstance(channel, EFBChannel):
if channel.channel_type == ChannelType.Slave:
slaves[channel.channel_id] = channel
else:
master = channel
else:
raise TypeError("Channel instance is expected") | 145,112 |
Register a middleware with the coordinator.
Args:
middleware (EFBMiddleware): Middleware to register | def add_middleware(middleware: EFBMiddleware):
global middlewares
if isinstance(middleware, EFBMiddleware):
middlewares.append(middleware)
else:
raise TypeError("Middleware instance is expected") | 145,113 |
Deliver a message to the destination channel.
Args:
msg (EFBMsg): The message
Returns:
The message sent by the destination channel,
includes the updated message ID from there.
Returns ``None`` if the message is not sent. | def send_message(msg: 'EFBMsg') -> Optional['EFBMsg']:
global middlewares, master, slaves
if msg is None:
return
# Go through middlewares
for i in middlewares:
m = i.process_message(msg)
if m is None:
return None
# for mypy type check
assert m is not None
msg = m
msg.verify()
if msg.deliver_to.channel_id == master.channel_id:
return master.send_message(msg)
elif msg.deliver_to.channel_id in slaves:
return slaves[msg.deliver_to.channel_id].send_message(msg)
else:
raise EFBChannelNotFound(msg) | 145,114 |
Deliver a message to the destination channel.
Args:
status (EFBStatus): The status | def send_status(status: 'EFBStatus'):
global middlewares, master
if status is None:
return
s: 'Optional[EFBStatus]' = status
# Go through middlewares
for i in middlewares:
s = i.process_status(cast('EFBStatus', s))
if s is None:
return
status = cast('EFBStatus', s)
status.verify()
status.destination_channel.send_status(status) | 145,115 |
Return the module instance of a provided module ID
Args:
module_id: Module ID, with instance ID if available.
Returns:
Module instance requested.
Raises:
NameError: When the module is not found. | def get_module_by_id(module_id: str) -> Union[EFBChannel, EFBMiddleware]:
try:
if master.channel_id == module_id:
return master
except NameError:
pass
if module_id in slaves:
return slaves[module_id]
for i in middlewares:
if i.middleware_id == module_id:
return i
raise NameError("Module ID {} is not found".format(module_id)) | 145,116 |
__init__(channel: EFBChannel, new_chats: Iterable[str]=tuple(), removed_chats: Iterable[str]=tuple(), modified_chats: Iterable[str]=tuple())
Args:
channel (:obj:`.EFBChannel`): Slave channel that issues the update
new_chats (Optional[Iterable[str]]): Unique ID of new chats
removed_chats (Optional[Iterable[str]]): Unique ID of removed chats
modified_chats (Optional[Iterable[str]]): Unique ID of modified chats | def __init__(self, channel: 'EFBChannel', new_chats: Iterable[str] = tuple(),
removed_chats: Iterable[str] = tuple(), modified_chats: Iterable[str] = tuple()):
self.channel: 'EFBChannel' = channel
self.new_chats: Iterable[str] = new_chats
self.removed_chats: Iterable[str] = removed_chats
self.modified_chats: Iterable[str] = modified_chats
self.destination_channel: 'EFBChannel' = coordinator.master | 145,125 |
Sends a typing indicator to the specified channel.
This indicates that this app is currently
writing a message to send to a channel.
Args:
channel (str): The channel id. e.g. 'C024BE91L'
Raises:
SlackClientNotConnectedError: Websocket connection is closed. | def typing(self, *, channel: str):
payload = {"id": self._next_msg_id(), "type": "typing", "channel": channel}
self.send_over_websocket(payload=payload) | 145,176 |
Checks if the specified callback is callable and accepts a kwargs param.
Args:
callback (obj): Any object or a list of objects that can be called.
e.g. <function say_hello at 0x101234567>
Raises:
SlackClientError: The specified callback is not callable.
SlackClientError: The callback must accept keyword arguments (**kwargs). | def _validate_callback(callback):
cb_name = callback.__name__ if hasattr(callback, "__name__") else callback
if not callable(callback):
msg = "The specified callback '{}' is not callable.".format(cb_name)
raise client_err.SlackClientError(msg)
callback_params = inspect.signature(callback).parameters.values()
if not any(
param for param in callback_params if param.kind == param.VAR_KEYWORD
):
msg = "The callback '{}' must accept keyword arguments (**kwargs).".format(
cb_name
)
raise client_err.SlackClientError(msg) | 145,177 |
Renames a channel.
Args:
channel (str): The channel id. e.g. 'C1234567890'
name (str): The new channel name. e.g. 'newchannel' | def channels_rename(self, *, channel: str, name: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"channel": channel, "name": name})
return self.api_call("channels.rename", json=kwargs) | 145,190 |
Retrieve a thread of messages posted to a channel
Args:
channel (str): The channel id. e.g. 'C1234567890'
thread_ts (str): The timestamp of an existing message with 0 or more replies.
e.g. '1234567890.123456' | def channels_replies(self, *, channel: str, thread_ts: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel, "thread_ts": thread_ts})
return self.api_call("channels.replies", http_verb="GET", params=kwargs) | 145,191 |
Unarchives a channel.
Args:
channel (str): The channel id. e.g. 'C1234567890' | def channels_unarchive(self, *, channel: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"channel": channel})
return self.api_call("channels.unarchive", json=kwargs) | 145,192 |
Deletes a message.
Args:
channel (str): Channel containing the message to be deleted. e.g. 'C1234567890'
ts (str): Timestamp of the message to be deleted. e.g. '1234567890.123456' | def chat_delete(self, *, channel: str, ts: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel, "ts": ts})
return self.api_call("chat.delete", json=kwargs) | 145,193 |
Retrieve a permalink URL for a specific extant message
Args:
channel (str): The channel id. e.g. 'C1234567890'
message_ts (str): The timestamp. e.g. '1234567890.123456' | def chat_getPermalink(
self, *, channel: str, message_ts: str, **kwargs
) -> SlackResponse:
kwargs.update({"channel": channel, "message_ts": message_ts})
return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs) | 145,194 |
Share a me message into a channel.
Args:
channel (str): The channel id. e.g. 'C1234567890'
text (str): The message you'd like to share. e.g. 'Hello world' | def chat_meMessage(self, *, channel: str, text: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel, "text": text})
return self.api_call("chat.meMessage", json=kwargs) | 145,195 |
Provide custom unfurl behavior for user-posted URLs.
Args:
channel (str): The Channel ID of the message. e.g. 'C1234567890'
ts (str): Timestamp of the message to add unfurl behavior to. e.g. '1234567890.123456'
unfurls (dict): a dict of the specific URLs you're offering an unfurl for.
e.g. {"https://example.com/": {"text": "Every day is the test."}} | def chat_unfurl(
self, *, channel: str, ts: str, unfurls: dict, **kwargs
) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"channel": channel, "ts": ts, "unfurls": unfurls})
return self.api_call("chat.unfurl", json=kwargs) | 145,197 |
Invites users to a channel.
Args:
channel (str): The channel id. e.g. 'C1234567890'
users (list): An list of user id's to invite. e.g. ['U2345678901', 'U3456789012'] | def conversations_invite(
self, *, channel: str, users: List[str], **kwargs
) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"channel": channel, "users": users})
return self.api_call("conversations.invite", json=kwargs) | 145,198 |
Retrieve a thread of messages posted to a conversation
Args:
channel (str): Conversation ID to fetch thread from. e.g. 'C1234567890'
ts (str): Unique identifier of a thread's parent message. e.g. '1234567890.123456' | def conversations_replies(self, *, channel: str, ts: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel, "ts": ts})
return self.api_call("conversations.replies", http_verb="GET", params=kwargs) | 145,199 |
Sets the topic for a conversation.
Args:
channel (str): The channel id. e.g. 'C1234567890'
topic (str): The new topic for the channel. e.g. 'My Topic' | def conversations_setTopic(
self, *, channel: str, topic: str, **kwargs
) -> SlackResponse:
kwargs.update({"channel": channel, "topic": topic})
return self.api_call("conversations.setTopic", json=kwargs) | 145,200 |
Turns on Do Not Disturb mode for the current user, or changes its duration.
Args:
num_minutes (int): The snooze duration. e.g. 60 | def dnd_setSnooze(self, *, num_minutes: int, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"num_minutes": num_minutes})
return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs) | 145,204 |
Add a comment to an existing file.
Args:
comment (str): The body of the comment.
e.g. 'Everyone should take a moment to read this file.'
file (str): The file id. e.g. 'F1234467890' | def files_comments_add(self, *, comment: str, file: str, **kwargs) -> SlackResponse:
kwargs.update({"comment": comment, "file": file})
return self.api_call("files.comments.add", json=kwargs) | 145,205 |
Deletes an existing comment on a file.
Args:
file (str): The file id. e.g. 'F1234467890'
id (str): The file comment id. e.g. 'Fc1234567890' | def files_comments_delete(self, *, file: str, id: str, **kwargs) -> SlackResponse:
kwargs.update({"file": file, "id": id})
return self.api_call("files.comments.delete", json=kwargs) | 145,206 |
Edit an existing file comment.
Args:
comment (str): The body of the comment.
e.g. 'Everyone should take a moment to read this file.'
file (str): The file id. e.g. 'F1234467890'
id (str): The file comment id. e.g. 'Fc1234567890' | def files_comments_edit(
self, *, comment: str, file: str, id: str, **kwargs
) -> SlackResponse:
kwargs.update({"comment": comment, "file": file, "id": id})
return self.api_call("files.comments.edit", json=kwargs) | 145,207 |
Deletes a file.
Args:
id (str): The file id. e.g. 'F1234467890' | def files_delete(self, *, id: str, **kwargs) -> SlackResponse:
kwargs.update({"id": id})
return self.api_call("files.delete", json=kwargs) | 145,208 |
Gets information about a team file.
Args:
id (str): The file id. e.g. 'F1234467890' | def files_info(self, *, id: str, **kwargs) -> SlackResponse:
kwargs.update({"id": id})
return self.api_call("files.info", http_verb="GET", params=kwargs) | 145,209 |
Enables a file for public/external sharing.
Args:
id (str): The file id. e.g. 'F1234467890' | def files_sharedPublicURL(self, *, id: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"id": id})
return self.api_call("files.sharedPublicURL", json=kwargs) | 145,211 |
Uploads or creates a file.
Args:
file (str): Supply a file path.
when you'd like to upload a specific file. e.g. 'dramacat.gif'
content (str): Supply content when you'd like to create an
editable text file containing the specified text. e.g. 'launch plan'
Raises:
SlackRequestError: If niether or both the `file` and `content` args are specified. | def files_upload(
self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> SlackResponse:
if file is None and content is None:
raise e.SlackRequestError("The file or content argument must be specified.")
if file is not None and content is not None:
raise e.SlackRequestError(
"You cannot specify both the file and the content argument."
)
if file:
return self.api_call("files.upload", files={"file": file}, data=kwargs)
elif content:
data = kwargs.copy()
data.update({"content": content})
return self.api_call("files.upload", data=data) | 145,212 |
Clones and archives a private channel.
Args:
channel (str): The group id. e.g. 'G1234567890' | def groups_createChild(self, *, channel: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"channel": channel})
return self.api_call("groups.createChild", http_verb="GET", params=kwargs) | 145,213 |
Invites a user to a private channel.
Args:
channel (str): The group id. e.g. 'G1234567890'
user (str): The user id. e.g. 'U1234567890' | def groups_invite(self, *, channel: str, user: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"channel": channel, "user": user})
return self.api_call("groups.invite", json=kwargs) | 145,214 |
Retrieve a thread of messages posted to a private channel
Args:
channel (str): The channel id. e.g. 'C1234567890'
thread_ts (str): The timestamp of an existing message with 0 or more replies.
e.g. '1234567890.123456' | def groups_replies(self, *, channel: str, thread_ts: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"channel": channel, "thread_ts": thread_ts})
return self.api_call("groups.replies", http_verb="GET", params=kwargs) | 145,215 |
Sets the purpose for a private channel.
Args:
channel (str): The channel id. e.g. 'G1234567890'
purpose (str): The new purpose for the channel. e.g. 'My Purpose' | def groups_setPurpose(self, *, channel: str, purpose: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel, "purpose": purpose})
return self.api_call("groups.setPurpose", json=kwargs) | 145,216 |
Opens a direct message channel.
Args:
user (str): The user id to open a DM with. e.g. 'W1234567890' | def im_open(self, *, user: str, **kwargs) -> SlackResponse:
kwargs.update({"user": user})
return self.api_call("im.open", json=kwargs) | 145,217 |
For Enterprise Grid workspaces, map local user IDs to global user IDs
Args:
users (list): A list of user ids, up to 400 per request.
e.g. ['W1234567890', 'U2345678901', 'U3456789012'] | def migration_exchange(self, *, users: List[str], **kwargs) -> SlackResponse:
kwargs.update({"users": users})
return self.api_call("migration.exchange", http_verb="GET", params=kwargs) | 145,218 |
Closes a multiparty direct message channel.
Args:
channel (str): Multiparty Direct message channel to close. e.g. 'G1234567890' | def mpim_close(self, *, channel: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel})
return self.api_call("mpim.close", json=kwargs) | 145,219 |
Fetches history of messages and events from a multiparty direct message.
Args:
channel (str): Multiparty direct message to fetch history for. e.g. 'G1234567890' | def mpim_history(self, *, channel: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel})
return self.api_call("mpim.history", http_verb="GET", params=kwargs) | 145,220 |
This method opens a multiparty direct message.
Args:
users (list): A lists of user ids. The ordering of the users
is preserved whenever a MPIM group is returned.
e.g. ['W1234567890', 'U2345678901', 'U3456789012'] | def mpim_open(self, *, users: List[str], **kwargs) -> SlackResponse:
kwargs.update({"users": users})
return self.api_call("mpim.open", json=kwargs) | 145,221 |
Exchanges a temporary OAuth verifier code for an access token.
Args:
client_id (str): Issued when you created your application. e.g. '4b39e9-752c4'
client_secret (str): Issued when you created your application. e.g. '33fea0113f5b1'
code (str): The code param returned via the OAuth callback. e.g. 'ccdaa72ad' | def oauth_access(
self, *, client_id: str, client_secret: str, code: str, **kwargs
) -> SlackResponse:
kwargs.update(
{"client_id": client_id, "client_secret": client_secret, "code": code}
)
return self.api_call("oauth.access", data=kwargs) | 145,222 |
Adds a reaction to an item.
Args:
name (str): Reaction (emoji) name. e.g. 'thumbsup'
channel (str): Channel where the message to add reaction to was posted.
e.g. 'C1234567890'
timestamp (str): Timestamp of the message to add reaction to. e.g. '1234567890.123456' | def reactions_add(self, *, name: str, **kwargs) -> SlackResponse:
kwargs.update({"name": name})
return self.api_call("reactions.add", json=kwargs) | 145,223 |
Creates a reminder.
Args:
text (str): The content of the reminder. e.g. 'eat a banana'
time (str): When this reminder should happen:
the Unix timestamp (up to five years from now e.g. '1602288000'),
the number of seconds until the reminder (if within 24 hours),
or a natural language description (Ex. 'in 15 minutes' or 'every Thursday') | def reminders_add(self, *, text: str, time: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"text": text, "time": time})
return self.api_call("reminders.add", json=kwargs) | 145,224 |
Marks a reminder as complete.
Args:
reminder (str): The ID of the reminder to be marked as complete.
e.g. 'Rm12345678' | def reminders_complete(self, *, reminder: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"reminder": reminder})
return self.api_call("reminders.complete", json=kwargs) | 145,225 |
Gets information about a reminder.
Args:
reminder (str): The ID of the reminder. e.g. 'Rm12345678' | def reminders_info(self, *, reminder: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"reminder": reminder})
return self.api_call("reminders.info", http_verb="GET", params=kwargs) | 145,226 |
Searches for messages matching a query.
Args:
query (str): Search query. May contains booleans, etc.
e.g. 'pickleface' | def search_messages(self, *, query: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"query": query})
return self.api_call("search.messages", http_verb="GET", params=kwargs) | 145,228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.