Skip to main content
Version: Latest

Utils - All Additional Functions of RimTUB

get_root

Returns the path to the directory where RimTUB is located.

Arguments:

  • as_path (bool) = False - If True, the result is returned as a pathlib.Path. If False, it is returned as a string.

Returns: str|Path - the root path of RimTUB.

Example:

print(get_root()) # D:\RimTUB

get_args

Extracts arguments from text.

Arguments:

  • text (str) - the source text containing arguments.
  • default (Any) = '' - default value if the argument is missing.

Returns: str|Any - the argument string or the default value.

Example:

# msg.text = '.command some text'
text = get_args(msg.text)
print(text) # some text

parse_args

Parses an argument string and separates it into positional arguments, flags, and key-value parameters.

warning

This function currently works incorrectly 👍

Arguments:

  • input_str (str) - the string with arguments separated by spaces.

Returns: Tuple[List[str], List[str], Dict[str, Any]] - list of positional arguments, list of flags, dictionary of parameters.

Example:

# msg.text = '.command some text -photo -size X'
args, flags, kwargs = parse_args(get_args(msg.text))
print(args) # ['some', 'text']
print(flags) # ['-photo']
print(kwargs) # {'-size': 'X'}

pnum

Converts a number to an integer if it is equivalent in value; otherwise, keeps it as a float.
In simple terms, removes .0.

Arguments:

  • num (int | float) - the number to convert.

Returns: int | float - the converted number.

Example:

print(pnum(5.5)) # 5.5
print(pnum(9.0)) # 9

fnum

Formats a number with thousand separators if it is greater than or equal to the specified threshold.
Returns the number as a string without a comma if it is below the threshold.

Arguments:

  • num (int) - the number to format.
  • threshold (int) - the threshold value for thousand separators.

Returns: str - the formatted number.

Example:

sec_to_str

Converts a number of seconds into a string representation in the format "d.h.m.s."

Arguments:

  • seconds (int) - the number of seconds to convert.
  • round (bool) = True - whether to round the number of seconds to an integer (default is True).

Returns: str - the string representing the time.

Example:

print(sec_to_str(66666)) # 18h. 31m. 6s.

plural

Determines the correct form of a word based on the quantity.

Arguments:

  • count (int) - the number of objects.
  • words (List[str]) - list of word forms (singular, dual, plural).

Returns: str - the correct word form.

Example:

module = ['module', 'modules', 'modules']
plural(1, module) # module
plural(3, module) # modules
plural(15, module) # modules

restart

Restarts RimTUB.

warning

This is a system function. It is not recommended to modify it.

Arguments:

  • app_id (int) - client ID.
  • chat_id (int) = None - (optional) chat ID for modifying a message.
  • msg_id (int) = None - (optional) message ID for modification.

Returns: None

async check_ping

Checks the ping by sending a message to itself and measuring the delay.

Arguments:

  • app (Client) - the application object used to send the message.

Returns: float - the ping value in milliseconds.

Example:

await check_ping(app) # 82.3

get_numbers_from_string

Extracts all numbers from a string.

Arguments:

  • string (str) - the string to search for numbers.

Returns: List[float] - list of numbers.

Example:

text = "There were 15 apples weighing 123.4 g each, and 1 jar weighing 200 grams."
get_numbers_from_string(text) # [15.0, 123.4, 1.0, 200.0]

find_function_by_id

Searches for a function by its identifier in memory.

Arguments:

  • func_id (int) - the function identifier.

Returns: Callable | None - the function if found, or None if not.

tail

Gets the last n lines from a file.

Arguments:

  • f (TextIO) - the file object.
  • lines (int) = 1 - the number of lines to extract.
  • _buffer (int) = 4098 - the buffer size for reading.

Returns: str - the extracted lines.

Example:

file.txt
Some
text
with many
lines and
here are
the last
two lines
with open('file.txt', 'r', encoding='utf-8') as f:
print(tail(f, 2)) # last\ntwo lines

try_

A universal function for exception handling, performing different actions depending on the result.

Arguments:

  • func_to_try (Callable) - the main function to execute.
  • func_to_except (Callable) = None - the function executed on exception (default is None).
  • func_to_else (Callable) = None - the function executed if no exception occurs (default is None).
  • func_to_finally (Callable) = None - the function executed in any case after the main function (default is None).
  • default (Any) = None - the default value returned on exception (default is None).

Returns: Any - the result of the executed functions.

Example:

try_(os.remove(path)) # Attempts to delete. If an error occurs (file not found), it doesn't matter.

get_tree

Recursively builds a tree of files and directories in the specified folder.
Equivalent to the TREE command on Windows.

Arguments:

  • directory (str) - the path to the directory for which the tree is built.
  • prefix (str) = "" - the prefix string for displaying nesting levels (default is an empty string).
  • html (bool) = False - whether to format the result as HTML (default is False).

Returns: str - the string representation of the directory and file tree.

Example:

print(get_tree(get_root() / 'plugins' / 'MineEvoMiner'))
Output
├── .rimtubignore
├── helplist.py
├── manifest.yaml
├── miner
│ ├── inline.py
│ ├── mine.py
│ ├── scripts.py
│ └──__init__.py
├── stats
│ └── stat.py
├── utils
│ ├── emj.py
│ ├── prettier.py
│ ├── scripts.py
│ ├── types.py
│ └── __init__.py
└── __init__.py

find_file

Searches for the file with the most similar name in the specified directory and its subfolders.

Arguments:

  • filename (str) - the name of the file to find.
  • search_path (str) - the path to the directory where the search is performed.
  • max_depth (int) = None - the maximum depth of recursive search (default is no limit).
  • extensions (List[str]) = None - list of extensions for filtering (default is any files).
  • case_sensitive (bool) = False - whether to consider case sensitivity in the file name (default is False).
  • default (Any) = None - the default value returned if the file is not found.

Returns: str | Any - the full path to the most similar file or the default value if not found.

Example:

UBLog/__init__.py, lines 27-28
logfile = get_args(msg.text, 'general')
file = find_file(logfile, 'logs', 1, ['.log'])

find_directory

Searches for the directory with the most similar name in the specified directory and its subfolders.

Arguments:

  • dirname (str) - the name of the directory to find.
  • search_path (str) - the path to the directory where the search is performed.
  • max_depth (int) = None - the maximum depth of recursive search (default is no limit).
  • case_sensitive (bool) = False - whether to consider case sensitivity in the directory name (default is False).
  • default (Any) = None - the default value returned if the directory is not found.

Returns: str | Any - the full path to the most similar directory or the default value if not found.

Example:

ModuleHelper/__init__.py, line 316
module_path = Path(find_directory(name, 'plugins', 1))

install_requirements

Installs the required libraries.

Arguments:

  • requirements (dict) - A dictionary where keys are how to import the library, and values are how to install it via pip.

Returns: None

Example:

requirements = {
"telebot": "pyTelegramBotAPI==4.26.0"
}
install_requirements(requirements)

read_yaml

Reads a YAML file.

Arguments:

  • file_path (str) - Path to the YAML file.

Returns: dict - Data as a dictionary.

Errors:

  • FileNotFoundError - when the file is not found.
  • yaml.scanner.ScannerError - on parsing error.

Example:

/utils/modify_pyrogram_client.py, line 228, in load_module
manifest = read_yaml(Path(get_root(), 'plugins', module_name, 'manifest.yaml')) or {}

singleton

A decorator for implementing the Singleton pattern.

Arguments: None.

Returns: type - A wrapper class to get a single instance of the class.

Example:

/utils/helplist.py, lines 220-221
@singleton
class HelpList:
...

save_pickle

Saves data to a pickle storage.

See Data Storage > Pickle Storage.

Arguments:

  • path (pathlib.Path|str) - the file path.
    tip

    It is recommended to save files either in the /storage folder or in the module folder.

  • data (Any) - Python object to save.
  • ttl (int) = Config value (DEFAULT_PICKLE_STORAGE_FILES_TTL) (= 259200 = 3 days) - File lifetime in seconds. After this time, the file will be automatically deleted. It is recommended to set no more than 7 days (604800 seconds).

Returns: pathlib.Path - the full file path.

Example:

SomeModule/__init__.py
data = mod # save the entire module object, why not ¯\_(ツ)_/¯

storage_folder = mod.path / 'storage'
storage_folder.mkdir(parents=True, exist_ok=True) # create the folder if it doesn't exist
path = storage_folder / "module_obj.pkl"

# Save data without specifying TTL,
# so the default value is used
# (the user can change it in the config)
path = save_pickle(path, data)

mod.logger.info(f"Saved module object to {path}")

load_pickle

Loads data from a pickle storage.

See Data Storage > Pickle Storage.

Arguments:

  • path (pathlib.Path|str) - the file path.

Returns: Any - the data.

Example:

SomeModule/__init__.py
path = mod.path / 'storage' / 'module_obj.pkl'
loaded_mod = load_pickle(path)

cleanup_expired_storage_files

Deletes expired storage pickle files based on TTL.

warning

This is a system function. It is not recommended to modify it.

Arguments: None.

Returns: None

generate_random_identifier

Generates a random combination of numbers of the specified length.

Arguments:

  • length (int) = 10 - the length of the string.

Returns: str - the generated combination.

Example:

print(generate_random_identifier()) # GXNgL0VQYV