text stringlengths 81 112k |
|---|
load yaml file and check file content format
def load_yaml_file(yaml_file):
""" load yaml file and check file content format
"""
with io.open(yaml_file, 'r', encoding='utf-8') as stream:
yaml_content = yaml.load(stream)
_check_format(yaml_file, yaml_content)
return yaml_content |
load json file and check file content format
def load_json_file(json_file):
""" load json file and check file content format
"""
with io.open(json_file, encoding='utf-8') as data_file:
try:
json_content = json.load(data_file)
except exceptions.JSONDecodeError:
err_ms... |
load csv file and check file content format
Args:
csv_file (str): csv file path, csv file content is like below:
Returns:
list: list of parameters, each parameter is in dict format
Examples:
>>> cat csv_file
username,password
test1,111111
test2,222222
... |
load folder path, return all files endswith yml/yaml/json in list.
Args:
folder_path (str): specified folder path to load
recursive (bool): load files recursively if True
Returns:
list: files endswith yml/yaml/json
def load_folder_files(folder_path, recursive=True):
""" load folde... |
load .env file.
Args:
dot_env_path (str): .env file path
Returns:
dict: environment variables mapping
{
"UserName": "debugtalk",
"Password": "123456",
"PROJECT_KEY": "ABCDEFGH"
}
Raises:
exceptions.FileFormat... |
locate filename and return absolute file path.
searching will be recursive upward until current working directory.
Args:
start_path (str): start locating path, maybe file path or directory path
Returns:
str: located file path. None if file not found.
Raises:
exceptions.Fil... |
load python module functions.
Args:
module: python module
Returns:
dict: functions mapping for specified python module
{
"func1_name": func1,
"func2_name": func2
}
def load_module_functions(module):
""" load python module functions.... |
extend with api reference
Raises:
exceptions.ApiNotFound: api not found
def __extend_with_api_ref(raw_testinfo):
""" extend with api reference
Raises:
exceptions.ApiNotFound: api not found
"""
api_name = raw_testinfo["api"]
# api maybe defined in two types:
# 1, individu... |
load api/testcases/testsuites definitions from folder.
Args:
folder_path (str): api/testcases/testsuites files folder.
Returns:
dict: api definition mapping.
{
"tests/api/basic.yml": [
{"api": {"def": "api_login", "request": {}, "validate": []}}... |
load api definitions from api folder.
Args:
api_folder_path (str): api files folder.
api file should be in the following format:
[
{
"api": {
"def": "api_login",
"request": {},
... |
API test: parse command line options and run commands.
def main_hrun():
""" API test: parse command line options and run commands.
"""
import argparse
from httprunner import logger
from httprunner.__about__ import __description__, __version__
from httprunner.api import HttpRunner
from httpr... |
Performance test with locust: parse command line options and run commands.
def main_locust():
""" Performance test with locust: parse command line options and run commands.
"""
# monkey patch ssl at beginning to avoid RecursionError when running locust.
from gevent import monkey; monkey.patch_ssl()
... |
check if variable or function exist
def is_var_or_func_exist(content):
""" check if variable or function exist
"""
if not isinstance(content, basestring):
return False
try:
match_start_position = content.index("$", 0)
except ValueError:
return False
while match_start_p... |
extract all variable names from content, which is in format $variable
Args:
content (str): string content
Returns:
list: variables list extracted from string content
Examples:
>>> regex_findall_variables("$variable")
["variable"]
>>> regex_findall_variables("/blog... |
parse parameters and generate cartesian product.
Args:
parameters (list) parameters: parameter name and value in list
parameter value may be in three types:
(1) data list, e.g. ["iOS/10.1", "iOS/10.2", "iOS/10.3"]
(2) call built-in parameterize function, "${param... |
get variable from variables_mapping.
Args:
variable_name (str): variable name
variables_mapping (dict): variables mapping
Returns:
mapping variable value.
Raises:
exceptions.VariableNotFound: variable is not found.
def get_mapping_variable(variable_name, variables_mapping... |
get function from functions_mapping,
if not found, then try to check if builtin function.
Args:
variable_name (str): variable name
variables_mapping (dict): variables mapping
Returns:
mapping function object.
Raises:
exceptions.FunctionNotFound: function is neither... |
parse function params to args and kwargs.
Args:
params (str): function param in string
Returns:
dict: function meta dict
{
"args": [],
"kwargs": {}
}
Examples:
>>> parse_function_params("")
{'args': [], 'kwargs': {}}... |
make string in content as lazy object with functions_mapping
Raises:
exceptions.VariableNotFound: if any variable undefined in check_variables_set
def prepare_lazy_data(content, functions_mapping=None, check_variables_set=None, cached=False):
""" make string in content as lazy object with functions_ma... |
parse lazy data with evaluated variables mapping.
Notice: variables_mapping should not contain any variable or function.
def parse_lazy_data(content, variables_mapping=None):
""" parse lazy data with evaluated variables mapping.
Notice: variables_mapping should not contain any variable or function.... |
evaluate data instantly.
Notice: variables_mapping should not contain any variable or function.
def eval_lazy_data(content, variables_mapping=None, functions_mapping=None):
""" evaluate data instantly.
Notice: variables_mapping should not contain any variable or function.
"""
variables_mapp... |
extract all variables in content recursively.
def extract_variables(content):
""" extract all variables in content recursively.
"""
if isinstance(content, (list, set, tuple)):
variables = set()
for item in content:
variables = variables | extract_variables(item)
return v... |
eval each prepared variable and function in variables_mapping.
Args:
variables_mapping (dict):
{
"varA": LazyString(123$varB),
"varB": LazyString(456$varC),
"varC": LazyString(${sum_two($a, $b)}),
"a": 1,
"b": 2,
... |
extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
"name": "get token 1",
"request": {...},
... |
parse testcase/testsuite config.
def __prepare_config(config, project_mapping, session_variables_set=None):
""" parse testcase/testsuite config.
"""
# get config variables
raw_config_variables = config.pop("variables", {})
raw_config_variables_mapping = utils.ensure_mapping_format(raw_config_variab... |
init func as lazy functon instance
Args:
function_meta (dict): function meta including name, args and kwargs
def __parse(self, function_meta):
""" init func as lazy functon instance
Args:
function_meta (dict): function meta including name, args and kwargs
"""
... |
parse lazy data with evaluated variables mapping.
Notice: variables_mapping should not contain any variable or function.
def to_value(self, variables_mapping=None):
""" parse lazy data with evaluated variables mapping.
Notice: variables_mapping should not contain any variable or functio... |
parse raw string, replace function and variable with {}
Args:
raw_string(str): string with functions or varialbes
e.g. "ABC${func2($a, $b)}DE$c"
Returns:
string: "ABC{}DE{}"
args: ["${func2($a, $b)}", "$c"]
def __parse(self, raw_string):
""" par... |
parse lazy data with evaluated variables mapping.
Notice: variables_mapping should not contain any variable or function.
def to_value(self, variables_mapping=None):
""" parse lazy data with evaluated variables mapping.
Notice: variables_mapping should not contain any variable or functio... |
get request and response info from Response() object.
def get_req_resp_record(self, resp_obj):
""" get request and response info from Response() object.
"""
def log_print(req_resp_dict, r_type):
msg = "\n================== {} details ==================\n".format(r_type)
... |
Constructs and sends a :py:class:`requests.Request`.
Returns :py:class:`requests.Response` object.
:param method:
method for the new :class:`Request` object.
:param url:
URL for the new :class:`Request` object.
:param name: (optional)
Placeholder, mak... |
Send a HTTP request, and catch any exception that might occur due to connection problems.
Safe mode has been removed from requests 1.x.
def _send_request_safe_mode(self, method, url, **kwargs):
"""
Send a HTTP request, and catch any exception that might occur due to connection problems.
... |
convert comparator alias to uniform name
def get_uniform_comparator(comparator):
""" convert comparator alias to uniform name
"""
if comparator in ["eq", "equals", "==", "is"]:
return "equals"
elif comparator in ["lt", "less_than"]:
return "less_than"
elif comparator in ["le", "less... |
unify validator
Args:
validator (dict): validator maybe in two formats:
format1: this is kept for compatiblity with the previous versions.
{"check": "status_code", "comparator": "eq", "expect": 201}
{"check": "$resp_body_success", "comparator": "eq", "expect": T... |
convert validators list to mapping.
Args:
validators (list): validators in list
Returns:
dict: validators mapping, use (check, comparator) as key.
Examples:
>>> validators = [
{"check": "v1", "expect": 201, "comparator": "eq"},
{"check": {"b": 1}, "... |
extend raw_validators with override_validators.
override_validators will merge and override raw_validators.
Args:
raw_validators (dict):
override_validators (dict):
Returns:
list: extended validators
Examples:
>>> raw_validators = [{'eq': ['v1', 200]}, {"check": "s... |
Takes (name, object) tuple, returns True if it is a variable.
def is_variable(tup):
""" Takes (name, object) tuple, returns True if it is a variable.
"""
name, item = tup
if callable(item):
# function or class
return False
if isinstance(item, types.ModuleType):
# imported m... |
validate JSON testcase format
def validate_json_file(file_list):
""" validate JSON testcase format
"""
for json_file in set(file_list):
if not json_file.endswith(".json"):
logger.log_warning("Only JSON file format can be validated, skip: {}".format(json_file))
continue
... |
generate random string with specified length
def gen_random_string(str_len):
""" generate random string with specified length
"""
return ''.join(
random.choice(string.ascii_letters + string.digits) for _ in range(str_len)) |
get timestamp string, length can only between 0 and 16
def get_timestamp(str_len=13):
""" get timestamp string, length can only between 0 and 16
"""
if isinstance(str_len, integer_types) and 0 < str_len < 17:
return builtin_str(time.time()).replace(".", "")[:str_len]
raise ParamsError("timesta... |
initialize MultipartEncoder with uploading fields.
def multipart_encoder(**kwargs):
""" initialize MultipartEncoder with uploading fields.
"""
def get_filetype(file_path):
file_type = filetype.guess(file_path)
if file_type:
return file_type.mime
else:
return ... |
parse testcase file and return locustfile path.
if file_path is a Python file, assume it is a locustfile
if file_path is a YAML/JSON file, convert it to locustfile
def parse_locustfile(file_path):
""" parse testcase file and return locustfile path.
if file_path is a Python file, assume it i... |
generate locustfile from template.
def gen_locustfile(testcase_file_path):
""" generate locustfile from template.
"""
locustfile_path = 'locustfile.py'
template_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"templates",
"locustfile_template"
)
with i... |
update session with extracted variables mapping.
these variables are valid in the whole running session.
def update_session_variables(self, variables_mapping):
""" update session with extracted variables mapping.
these variables are valid in the whole running session.
"""
... |
evaluate check item in validator.
Args:
check_item: check_item should only be the following 5 formats:
1, variable reference, e.g. $token
2, function reference, e.g. ${is_status_code_200($status_code)}
3, dict or list, maybe containing variable/functi... |
make validation with comparators
def validate(self, validators, resp_obj):
""" make validation with comparators
"""
self.validation_results = []
if not validators:
return
logger.log_debug("start to validate.")
validate_pass = True
failures = []
... |
get summary from test result
Args:
result (instance): HtmlTestResult() instance
Returns:
dict: summary extracted from result.
{
"success": True,
"stat": {},
"time": {},
"records": []
}
def get_summary(res... |
aggregate new_stat to origin_stat.
Args:
origin_stat (dict): origin stat dict, will be updated with new_stat dict.
new_stat (dict): new stat dict.
def aggregate_stat(origin_stat, new_stat):
""" aggregate new_stat to origin_stat.
Args:
origin_stat (dict): origin stat dict, will be ... |
stringify summary, in order to dump json file and generate html report.
def stringify_summary(summary):
""" stringify summary, in order to dump json file and generate html report.
"""
for index, suite_summary in enumerate(summary["details"]):
if not suite_summary.get("name"):
suite_sum... |
stringfy HTTP request data
Args:
request_data (dict): HTTP request data in dict.
{
"url": "http://127.0.0.1:5000/api/get-token",
"method": "POST",
"headers": {
"User-Agent": "python-requests/2.20.0",
"Accep... |
stringfy HTTP response data
Args:
response_data (dict):
{
"status_code": 404,
"headers": {
"Content-Type": "application/json",
"Content-Length": "30",
"Server": "Werkzeug/0.14.1 Python/3.7.0",
... |
expand meta_datas to one level
Args:
meta_datas (dict/list): maybe in nested format
Returns:
list: expanded list in one level
Examples:
>>> meta_datas = [
[
dict1,
dict2
],
dict3
]
... |
caculate total response time of all meta_datas
def __get_total_response_time(meta_datas_expanded):
""" caculate total response time of all meta_datas
"""
try:
response_time = 0
for meta_data in meta_datas_expanded:
response_time += meta_data["stat"]["response_time_ms"]
... |
render html report with specified report name and template
Args:
report_template (str): specify html report template path
report_dir (str): specify html report save directory
def render_html_report(summary, report_template=None, report_dir=None):
""" render html report with specified report na... |
extract field from response content with regex.
requests.Response body could be json or html text.
Args:
field (str): regex string that matched r".*\(.*\).*"
Returns:
str: matched content.
Raises:
exceptions.ExtractFailure: If no content matched... |
response content could be json or html text.
Args:
field (str): string joined by delimiter.
e.g.
"status_code"
"headers"
"cookies"
"content"
"headers.content-type"
"content.person.name.first_... |
extract value from requests.Response.
def extract_field(self, field):
""" extract value from requests.Response.
"""
if not isinstance(field, basestring):
err_msg = u"Invalid extractor! => {}\n".format(field)
logger.log_error(err_msg)
raise exceptions.ParamsEr... |
extract value from requests.Response and store in OrderedDict.
Args:
extractors (list):
[
{"resp_status_code": "status_code"},
{"resp_headers_content_type": "headers.content-type"},
{"resp_content": "content"},
... |
Use this method to request a callback answer from bots.
This is the equivalent of clicking an inline button containing callback data.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Sav... |
Use this method to promote or demote a user in a supergroup or a channel.
You must be an administrator in the chat for this to work and must have the appropriate admin rights.
Pass False for all boolean parameters to demote a user.
Args:
chat_id (``int`` | ``str``):
... |
Use this method to set a new profile photo.
This method only works for Users.
Bots profile photos must be set using BotFather.
Args:
photo (``str``):
Profile photo to set.
Pass a file path as string to upload a new photo that exists on your local mac... |
ERROR: type should be string, got "https://core.telegram.org/mtproto/auth_key\n https://core.telegram.org/mtproto/samples-auth_key\n\ndef create(self):\n \"\"\"\n https://core.telegram.org/mtproto/auth_key\n https://core.telegram.org/mtproto/samples-auth_key\n \"\"\"\n retries_left = self.MAX_RETRIES\n\n # The server may close the connection at any time, causing the auth key creation to fail.\n # If that happens, just try again up to MAX_RETRIES times.\n while True:\n self.connection = Connection(self.dc_id, self.test_mode, self.ipv6, self.proxy)\n\n try:\n log.info(\"Start creating a new auth key on DC{}\".format(self.dc_id))\n\n self.connection.connect()\n\n # Step 1; Step 2\n nonce = int.from_bytes(urandom(16), \"little\", signed=True)\n log.debug(\"Send req_pq: {}\".format(nonce))\n res_pq = self.send(functions.ReqPqMulti(nonce=nonce))\n log.debug(\"Got ResPq: {}\".format(res_pq.server_nonce))\n log.debug(\"Server public key fingerprints: {}\".format(res_pq.server_public_key_fingerprints))\n\n for i in res_pq.server_public_key_fingerprints:\n if i in RSA.server_public_keys:\n log.debug(\"Using fingerprint: {}\".format(i))\n public_key_fingerprint = i\n break\n else:\n log.debug(\"Fingerprint unknown: {}\".format(i))\n else:\n raise Exception(\"Public key not found\")\n\n # Step 3\n pq = int.from_bytes(res_pq.pq, \"big\")\n log.debug(\"Start PQ factorization: {}\".format(pq))\n start = time.time()\n g = Prime.decompose(pq)\n p, q = sorted((g, pq // g)) # p < q\n log.debug(\"Done PQ factorization ({}s): {} {}\".format(round(time.time() - start, 3), p, q))\n\n # Step 4\n server_nonce = res_pq.server_nonce\n new_nonce = int.from_bytes(urandom(32), \"little\", signed=True)\n\n data = types.PQInnerData(\n pq=res_pq.pq,\n p=p.to_bytes(4, \"big\"),\n q=q.to_bytes(4, \"big\"),\n nonce=nonce,\n server_nonce=server_nonce,\n new_nonce=new_nonce,\n ).write()\n\n sha = sha1(data).digest()\n padding = urandom(- (len(data) + len(sha)) % 255)\n data_with_hash = sha + data + padding\n encrypted_data = RSA.encrypt(data_with_hash, public_key_fingerprint)\n\n log.debug(\"Done encrypt data with RSA\")\n\n # Step 5. TODO: Handle \"server_DH_params_fail\". Code assumes response is ok\n log.debug(\"Send req_DH_params\")\n server_dh_params = self.send(\n functions.ReqDHParams(\n nonce=nonce,\n server_nonce=server_nonce,\n p=p.to_bytes(4, \"big\"),\n q=q.to_bytes(4, \"big\"),\n public_key_fingerprint=public_key_fingerprint,\n encrypted_data=encrypted_data\n )\n )\n\n encrypted_answer = server_dh_params.encrypted_answer\n\n server_nonce = server_nonce.to_bytes(16, \"little\", signed=True)\n new_nonce = new_nonce.to_bytes(32, \"little\", signed=True)\n\n tmp_aes_key = (\n sha1(new_nonce + server_nonce).digest()\n + sha1(server_nonce + new_nonce).digest()[:12]\n )\n\n tmp_aes_iv = (\n sha1(server_nonce + new_nonce).digest()[12:]\n + sha1(new_nonce + new_nonce).digest() + new_nonce[:4]\n )\n\n server_nonce = int.from_bytes(server_nonce, \"little\", signed=True)\n\n answer_with_hash = AES.ige256_decrypt(encrypted_answer, tmp_aes_key, tmp_aes_iv)\n answer = answer_with_hash[20:]\n\n server_dh_inner_data = Object.read(BytesIO(answer))\n\n log.debug(\"Done decrypting answer\")\n\n dh_prime = int.from_bytes(server_dh_inner_data.dh_prime, \"big\")\n delta_time = server_dh_inner_data.server_time - time.time()\n\n log.debug(\"Delta time: {}\".format(round(delta_time, 3)))\n\n # Step 6\n g = server_dh_inner_data.g\n b = int.from_bytes(urandom(256), \"big\")\n g_b = pow(g, b, dh_prime).to_bytes(256, \"big\")\n\n retry_id = 0\n\n data = types.ClientDHInnerData(\n nonce=nonce,\n server_nonce=server_nonce,\n retry_id=retry_id,\n g_b=g_b\n ).write()\n\n sha = sha1(data).digest()\n padding = urandom(- (len(data) + len(sha)) % 16)\n data_with_hash = sha + data + padding\n encrypted_data = AES.ige256_encrypt(data_with_hash, tmp_aes_key, tmp_aes_iv)\n\n log.debug(\"Send set_client_DH_params\")\n set_client_dh_params_answer = self.send(\n functions.SetClientDHParams(\n nonce=nonce,\n server_nonce=server_nonce,\n encrypted_data=encrypted_data\n )\n )\n\n # TODO: Handle \"auth_key_aux_hash\" if the previous step fails\n\n # Step 7; Step 8\n g_a = int.from_bytes(server_dh_inner_data.g_a, \"big\")\n auth_key = pow(g_a, b, dh_prime).to_bytes(256, \"big\")\n server_nonce = server_nonce.to_bytes(16, \"little\", signed=True)\n\n # TODO: Handle errors\n\n #######################\n # Security checks\n #######################\n\n assert dh_prime == Prime.CURRENT_DH_PRIME\n log.debug(\"DH parameters check: OK\")\n\n # https://core.telegram.org/mtproto/security_guidelines#g-a-and-g-b-validation\n g_b = int.from_bytes(g_b, \"big\")\n assert 1 < g < dh_prime - 1\n assert 1 < g_a < dh_prime - 1\n assert 1 < g_b < dh_prime - 1\n assert 2 ** (2048 - 64) < g_a < dh_prime - 2 ** (2048 - 64)\n assert 2 ** (2048 - 64) < g_b < dh_prime - 2 ** (2048 - 64)\n log.debug(\"g_a and g_b validation: OK\")\n\n # https://core.telegram.org/mtproto/security_guidelines#checking-sha1-hash-values\n answer = server_dh_inner_data.write() # Call .write() to remove padding\n assert answer_with_hash[:20] == sha1(answer).digest()\n log.debug(\"SHA1 hash values check: OK\")\n\n # https://core.telegram.org/mtproto/security_guidelines#checking-nonce-server-nonce-and-new-nonce-fields\n # 1st message\n assert nonce == res_pq.nonce\n # 2nd message\n server_nonce = int.from_bytes(server_nonce, \"little\", signed=True)\n assert nonce == server_dh_params.nonce\n assert server_nonce == server_dh_params.server_nonce\n # 3rd message\n assert nonce == set_client_dh_params_answer.nonce\n assert server_nonce == set_client_dh_params_answer.server_nonce\n server_nonce = server_nonce.to_bytes(16, \"little\", signed=True)\n log.debug(\"Nonce fields check: OK\")\n\n # Step 9\n server_salt = AES.xor(new_nonce[:8], server_nonce[:8])\n\n log.debug(\"Server salt: {}\".format(int.from_bytes(server_salt, \"little\")))\n\n log.info(\n \"Done auth key exchange: {}\".format(\n set_client_dh_params_answer.__class__.__name__\n )\n )\n except Exception as e:\n if retries_left:\n retries_left -= 1\n else:\n raise e\n\n time.sleep(1)\n continue\n else:\n return auth_key\n finally:\n self.connection.close()" |
Use this method to iterate through a chat history sequentially.
This convenience method does the same as repeatedly calling :meth:`get_history` in a loop, thus saving you from
the hassle of setting up boilerplate code. It is useful for getting the whole chat history with a single call.
Args:
... |
Use this method to send phone contacts.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists in your Tele... |
Use this method to edit text messages.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists in your Teleg... |
Use this method to retrieve a chunk of the history of a chat.
You can get up to 100 messages at once.
For a more convenient way of getting a chat history see :meth:`iter_history`.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the ta... |
Use this decorator to automatically register a function for handling user status updates.
This does the same thing as :meth:`add_handler` using the :class:`UserStatusHandler`.
Args:
filters (:obj:`Filters <pyrogram.Filters>`):
Pass one or more filters to allow only a subset ... |
Use this method to get the number of members in a chat.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
Returns:
On success, an integer is returned.
Raises:
:class:`RPCError <pyrogram.RPCError... |
Use this decorator to automatically register a function for handling disconnections.
This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`.
def on_disconnect(self=None) -> callable:
"""Use this decorator to automatically register a function for handling disconnections.
... |
Use this method to start the Client after creating it.
Requires no parameters.
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
``ConnectionError`` in case you try to start an already started Client.
def start(self):
"""Use this method to s... |
Use this method to manually stop the Client.
Requires no parameters.
Raises:
``ConnectionError`` in case you try to stop an already stopped Client.
def stop(self):
"""Use this method to manually stop the Client.
Requires no parameters.
Raises:
``Connect... |
Blocks the program execution until one of the signals are received,
then gently stop the Client by closing the underlying connection.
Args:
stop_signals (``tuple``, *optional*):
Iterable containing signals the signal handler will listen to.
Defaults to (SIGIN... |
Use this method to register an update handler.
You can register multiple handlers, but at most one handler within a group
will be used for a single update. To handle the same update more than once, register
your handler using a different group id (lower group id == higher priority).
Ar... |
Removes a previously-added update handler.
Make sure to provide the right group that the handler was added in. You can use
the return value of the :meth:`add_handler` method, a tuple of (handler, group), and
pass it directly.
Args:
handler (``Handler``):
The... |
Use this method to send Raw Function queries.
This method makes possible to manually call every single Telegram API method in a low-level manner.
Available functions are listed in the :obj:`functions <pyrogram.api.functions>` package and may accept compound
data types from :obj:`types <pyrogram... |
Use this method to get the InputPeer of a known peer_id.
This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API
method you wish to use which is not available yet in the Client class as an easy-to-use method), whenever an
InputPeer type is requ... |
Use this method to upload a file onto Telegram servers, without actually sending the message to anyone.
This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API
method you wish to use which is not available yet in the Client class as an easy-to-use meth... |
Use this method when you need to tell the other party that something is happening on your side.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self"... |
Use this method to send answers to an inline query.
No more than 50 results per query are allowed.
Args:
inline_query_id (``str``):
Unique identifier for the answered query.
results (List of :obj:`InlineQueryResult <pyrogram.InlineQueryResult>`):
... |
Use this method to send points on the map.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists in your T... |
Use this method to retract your vote in a poll.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists in y... |
Use this method to get a list of profile pictures for a user.
Args:
user_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact th... |
Use this method to update your own username.
This method only works for users, not bots. Bot usernames must be changed via Bot Support or by recreating
them from scratch using BotFather. To update a channel or supergroup username you can use
:meth:`update_chat_username`.
Args:
... |
Bound method *reply* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_message(
chat_id=message.chat.id,
text="hello",
reply_to_message_id=message.message_id
)
Example:
... |
Bound method *reply_animation* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_animation(
chat_id=message.chat.id,
animation=animation
)
Example:
.. code-block:: python
... |
Bound method *reply_audio* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_audio(
chat_id=message.chat.id,
audio=audio
)
Example:
.. code-block:: python
messag... |
Bound method *reply_cached_media* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_cached_media(
chat_id=message.chat.id,
file_id=file_id
)
Example:
.. code-block:: python
... |
Bound method *reply_chat_action* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_chat_action(
chat_id=message.chat.id,
action="typing"
)
Example:
.. code-block:: python
... |
Bound method *reply_contact* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_contact(
chat_id=message.chat.id,
phone_number=phone_number,
first_name=first_name
)
Example:
... |
Bound method *reply_document* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_document(
chat_id=message.chat.id,
document=document
)
Example:
.. code-block:: python
... |
Bound method *reply_game* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_game(
chat_id=message.chat.id,
game_short_name="lumberjack"
)
Example:
.. code-block:: python
... |
Bound method *reply_inline_bot_result* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_inline_bot_result(
chat_id=message.chat.id,
query_id=query_id,
result_id=result_id
)
... |
Bound method *reply_location* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_location(
chat_id=message.chat.id,
latitude=41.890251,
longitude=12.492373
)
Example:
... |
Bound method *reply_media_group* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_media_group(
chat_id=message.chat.id,
media=list_of_media
)
Example:
.. code-block:: python
... |
Bound method *reply_photo* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_photo(
chat_id=message.chat.id,
photo=photo
)
Example:
.. code-block:: python
messag... |
Bound method *reply_poll* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_poll(
chat_id=message.chat.id,
question="Is Pyrogram the best?",
options=["Yes", "Yes"]
)
Example:... |
Bound method *reply_sticker* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_sticker(
chat_id=message.chat.id,
sticker=sticker
)
Example:
.. code-block:: python
... |
Bound method *reply_venue* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_venue(
chat_id=message.chat.id,
latitude=41.890251,
longitude=12.492373,
title="Coliseum",
... |
Bound method *reply_video* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_video(
chat_id=message.chat.id,
video=video
)
Example:
.. code-block:: python
messag... |
Bound method *reply_video_note* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_video_note(
chat_id=message.chat.id,
video_note=video_note
)
Example:
.. code-block:: python
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.