-
Notifications
You must be signed in to change notification settings - Fork 11
Functions
HyperUBot does offer own predefined functions which are used by the core and built-in modules already. There are functions which also work for your own modules and some are only meant for user modules. Here we will explain all functions which are allowed to be used in your modules.
Table of contents
- userbot.include.*
- userbot.sysutils.*
Syntax:
async def fetch_entity(event=None, full_obj=False, get_chat=False, org_author=False)
Description:
Fetch an user or channel (and a target chat) information from event
Arguments:
event (Event): any event e.g.
NewMessage
full_obj (bool): fetchChatFull/UserFull
object instead. Does not work with groups.
get_chat (bool): fetchesChat/Channel
object too. This changes the return to atuple
org_author (bool): focus to original author of a replied message
Returns:
Channel/User
object (default) orChatFull/UserFull
object iffull_obj
is set toTrue
or- A tuple (
(Channel/User, Chat/Channel)
or(ChatFull/UserFull, Chat/Channel)
) ifget_chat
is set toTrue
Example usage:
from userbot.include.aux_funcs import fetch_entity
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
user = fetch_entity(event, full_obj=True)
await event.edit(f"hi {user.first_name}!")
return
Syntax:
async def event_log(event, event_name: str, user_name=None, user_id=None, username=None, chat_title=None, chat_link=None, chat_id=None, custom_text=None)
Description:
Log any event by sending a message to the targeted chat
Arguments:
event (Event): any event e.g.
NewMessage
event_name (str): name of event (not Telethon event) e.g. ban
user_name: name of user. Default toNone
user_id: ID from user. Default toNone
username: username from user. Default toNone
chat_title: Title of the specific chat. Default toNone
chat_link: link of the specific chat e.g.@example
. Default toNone
chat_id: link of the specific chat e.g.-100123456789
. Default toNone
custom_text: any custom text e.g. a note to the event. Default toNone
Returns:
None
Example usage:
from userbot.include.aux_funcs import fetch_user, event_log
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
user = fetch_user(event)
await event_log(event, "EXAMPLE", user_name=user.first_name, chat_id=event.chat_id)
return
Syntax:
def isRemoteCMD(event, chat_id: int) -> bool
Description:
Check if chat id from event matches
chat_id
. By this we can ensure if the command is remotely used.
Arguments:
event (Event): any event e.g.
NewMessage
chat_id (int): ID from targeted chat
Returns:
True
if it's remote elseFalse
Example usage:
from userbot.include.aux_funcs import fetch_user, isRemoteCMD
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
user, chat = fetch_user(event, get_chat=True)
isRemote = isRemoteCMD(event.chat_id, chat.id)
if isRemote:
await event.edit("Remote!")
else:
await event.edit("Not remote")
return
Syntax:
def format_chat_id(chat) -> int
Description:
Formats the chat id to a correct formation
Arguments:
chat (Channel/Chat): any chat object
Returns:
the id as integer
Example usage:
from userbot.include.aux_funcs import fetch_user, format_chat_id
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
user, chat = fetch_user(event, get_chat=True)
await event.edit(format_chat_id(chat))
return
Syntax:
def pinger(address) -> str
Description:
Ping an IP or DNS server from given address
Arguments:
address (str): IP/DNS address e.g.
8.8.8.8
Returns:
ping result as a string
Example usage:
from userbot.include.aux_funcs import pinger
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
ping = pinger("8.8.8.8")
await event.edit(ping)
return
Syntax:
async def getGitReview()
Description:
Get the last commit ID from HyperUBot's git repository
Arguments:
None
Returns:
commit ID as string else an empty string
Example usage:
from userbot.include.aux_funcs import getGitReview
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
commit = getGitReview()
if commit:
await event.edit("current commit id: " + commit)
else:
await event.edit("HyperUBot's directory is "
"not a git repository")
return
Syntax:
def sizeStrMaker(size: float, value: int = 0)
Description:
Convert given byte size recursively to a readable size
Arguments:
_size (float): size in bytes
value (int): just keep it 0
Returns:
converted size as string
Example usage:
from userbot.include.aux_funcs import sizeStrMaker
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
readable_size = sizeStrMaker(2048) # -> "2KB"
await event.edit(readable_size)
return
This API is based on pyGitHub_API by nunopenim.
Syntax:
def vercheck() -> str
Description:
Check the version of local GitHub API (not server)
Arguments:
None
Returns:
version as string
Example usage:
from userbot.include.git_api import vercheck
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit(f"The local GitHub API version is {vercheck()}")
return
Syntax:
def getRateLimit()
Description:
Get the current user's API Rate Limit
Arguments:
None
Returns:
resources from GitHub as dict
Example usage:
from userbot.include.git_api import getRateLimit
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
res = getRateLimit()
await event.edit(f"REST API: {rest['core']} calls remaining")
return
Syntax:
def getData(repoURL)
Description:
Get all data from all releases of a specific GitHub repository
Arguments:
repoURL (str): a "owner/repo"-combo e.g.
prototype74/HyperUBot
Returns:
a
list
of all releases elseNone
Example usage:
from userbot.include.git_api import getData
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
target_repo = "prototype74/HyperUBot"
releases = getData(target_repo)
count_releases = 0
for release in releases:
count_releases += 1
await event.edit(f"The repo '{target_repo}' has "
f"{count_releases} releases")
return
Syntax:
def getLatestData(repoURL)
Description:
Similar to
getData()
but only get the latest release
Arguments:
repoURL (str): a "owner/repo"-combo e.g.
prototype74/HyperUBot
Returns:
a
dict
with all data included from latest release elseNone
Example usage:
from userbot.include.git_api import getLatestData
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
target_repo = "prototype74/HyperUBot"
release = getLatestData(target_repo)
text = f"Latest release from {target_repo}\n\n"
text += f"URL: {release['html_url']}\n"
text += f"Tag: {release['tag_name']}\n"
text += f"Name: {release['name']}\n"
text += f"Published: {release['published_at']}"
await event.edit(text)
return
Syntax:
def getReleaseData(repoData, index)
Description:
Get a targeted release from index.
getData()
should be called first and passed togetReleaseData()
Arguments:
repoData (list): the list of releases from
getData()
index (int): the index to get a release fromrepoData
Returns:
a
dict
with all data included from targeted release elseNone
Example usage:
from userbot.include.git_api import getData, getReleaseData
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
target_repo = "prototype74/HyperUBot"
releases = getData(target_repo)
release = getReleaseData(releases, 0) # get latest release
text = f"Latest release from {target_repo}\n\n"
text += f"URL: {release['html_url']}\n"
text += f"Tag: {release['tag_name']}\n"
text += f"Name: {release['name']}\n"
text += f"Published: {release['published_at']}"
await event.edit(text)
return
There are a lot of helper functions in git_api
which makes it easier to get the author
, release tag
etc. from a GitHub Release. All helper functions are pretty much self-explained and don't need to be explained here. Check out the API instead.
Note:
getData()
andgetLatestData()
do send request to GitHub's API Server. The API Server has a rate limit which allow unauthenticated requests up to 60 requests per hour. If the API limit has been exceeded you will not be able to get data until the next hour
Syntax:
def getBotLangCode() -> str
Description:
Get the current bot language code from bot configuration. Default is
en
if configUBOT_LANG
doesn't exist
Arguments:
None
Returns:
the bot language code e.g.
en
Example usage:
from userbot.include.language_processor import getBotLangCode
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit(f"The current bot lang code is '{getBotLangCode()}'")
return
Syntax:
def getBotLang() -> str
Description:
Get the current bot language if language pack has
NAME
attribute
Arguments:
None
Returns:
the bot language e.g.
English
elseUnknown
Example usage:
from userbot.include.language_processor import getBotLang
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit(f"The current bot language is '{getBotLang()}'")
return
Syntax:
def checkPkgByDist(dist_name: str) -> bool
Description:
Check if given distribution name (not import name) is installed
Arguments:
dist_name (string): name of distribution
Returns:
True
if distribution is installed elseFalse
Example usage:
import userbot.include.pip_utils as pip
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
# check if requests package does exist
if not pip.checkPkgByDist("requests"):
raise ModuleNotFoundError("requests package not installed")
import requests # noqa: E402
@ehandler.on(command="example", outgoing=True)
async def example(event):
req = requests.get("https://github.com/prototype74/HyperUBot")
if req.status_code == 200:
await event.edit("HyperUBot's repo is online!")
elif req.status_code == 404:
await event.edit("Repo doesn't exist :(")
elif req.status_code == 503:
await event.edit("GitHub server is not reachable :'(")
return
Syntax:
def checkPkgByImport(import_name: str) -> bool
Description:
Checks if the importable name of the distribution exists
Arguments:
import_name (string): name of importable package
Returns:
True
if name is importable elseFalse
Example usage:
import userbot.include.pip_utils as pip
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
# check if requests package does exist
if not pip.checkPkgByImport("requests"):
raise ModuleNotFoundError("requests package not installed")
import requests # noqa: E402
@ehandler.on(command="example", outgoing=True)
async def example(event):
req = requests.get("https://github.com/prototype74/HyperUBot")
if req.status_code == 200:
await event.edit("HyperUBot's repo is online!")
elif req.status_code == 404:
await event.edit("Repo doesn't exist :(")
elif req.status_code == 503:
await event.edit("GitHub server is not reachable :'(")
return
Syntax:
def getVersionFromDist(dist_name)
Description:
Get the version of the distribution
Arguments:
dist_name (string): name of distribution
Returns:
version as string else
None
Example usage:
import userbot.include.pip_utils as pip
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.sys_funcs import verAsTuple
ehandler = EventHandler()
# check if requests package does exist
if pip.checkPkgByImport("requests"):
# get the package version
requests_version = pip.getVersionFromDist("requests")
if verAsTuple(requests_version) < (1, 2, 3): # requires at least v1.2.3
raise ValueError("requests package is outdated. Please update "
"to at least v1.2.3!")
import requests # noqa: E402
@ehandler.on(command="example", outgoing=True)
async def example(event):
req = requests.get("https://github.com/prototype74/HyperUBot")
if req.status_code == 200:
await event.edit("HyperUBot's repo is online!")
elif req.status_code == 404:
await event.edit("Repo doesn't exist :(")
elif req.status_code == 503:
await event.edit("GitHub server is not reachable :'(")
return
Syntax:
def installPkg(dist_name, upgrade: bool = False) -> bool
Description:
Allow the modules to install/upgrade a distribution. Please don't call
installPkg()
unnecessarily as it will spam the terminal logger much. Always check first if it's actually required to install/upgrade a pip package withcheckPkgByDist()
orcheckPkgByImport()
alongside withgetVersionFromDist()
. By this, it will keep the start of HyperUBot fast as it should be.
Arguments:
dist_name (string): name of distribution
upgrade (bool): if the distribution should be upgarded instead. Default set toFalse
Returns:
True
if installation was successful or not required elseFalse
if errors occurred
Example usage:
import userbot.include.pip_utils as pip
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.sys_funcs import verAsTuple
ehandler = EventHandler()
# check if requests package does exist
if pip.checkPkgByImport("requests"):
requests_version = pip.getVersionFromDist("requests")
# get the package version
if verAsTuple(requests_version) < (1, 2, 3): # requires at least v1.2.3
# upgrade the package!
pip.installPkg("requests", upgrade=True)
else:
# install the package
pip.installPkg("requests")
import requests # noqa: E402
@ehandler.on(command="example", outgoing=True)
async def example(event):
req = requests.get("https://github.com/prototype74/HyperUBot")
if req.status_code == 200:
await event.edit("HyperUBot's repo is online!")
elif req.status_code == 404:
await event.edit("Repo doesn't exist :(")
elif req.status_code == 503:
await event.edit("GitHub server is not reachable :'(")
return
Syntax:
def setColorText(text: str, color: Color) -> str
Description:
(Terminal only) Wrap the given text with a color
Arguments:
text (string): any text
color (Color): which color should be applied totext
Returns:
the colored text as string
On Windows: else plain text if packagecolorama
isn't installed
Example usage:
from userbot.sysutils.colors import setColorText, Color
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
print(setColorText("Hello!", Color.BLUE))
await event.edit("I just did print a colored text in your terminal!")
return
Syntax:
def setColorTextBG(text: str, colorbg: ColorBG) -> str
Description:
(Terminal only) Wrap the given text with a background color
Arguments:
text (string): any text
colorbg (ColorBG): which background color should be applied totext
Returns:
the colored background text as string
On Windows: else plain text if packagecolorama
isn't installed
Example usage:
from userbot.sysutils.colors import setColorTextBG, ColorBG
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
print(setColorTextBG("Hello!", ColorBG.BLUE))
await event.edit("I just did print a background colored "
"text in your terminal!")
return
Syntax:
def getConfig(config: str, default=None)
Description:
Get a config from global configurations which were defined in
config.env
,config.ini
orconfig.py
Arguments:
config (string): name of the config e.g.
UBOT_LANG
default: efault value to return ifconfig
doesn't exist. Default toNone
Returns:
the value from config else
default
if config doesn't exist
Example usage:
from userbot.sysutils.configuration import getConfig
from userbot.sysutils.event_handler import EventHandler
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
myConfig = getConfig("MYCUSTOMCONFIG") # get your custom config
await event.edit("This is my custom config: " + myConfig)
return
Syntax:
def register_module_desc(description: str)
Description:
Registers the description of a module which will be viewable in
.mods
Arguments:
description (string): (detailed) description of a module
Returns:
None
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import register_module_desc
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit("I'm an example!")
return
register_module_desc("I'm an example module!")
Syntax:
def register_module_info(name: str, authors=None, version=None)
Description:
Registers the information about a module which will be viewable in
.mods
Arguments:
name (string): name of module
authors (string): name of author(s). Default toNone
version (string): version of module. Default toNone
Returns:
None
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import register_module_info
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit("I'm an example!")
return
register_module_info(
name="Example",
authors="Example",
version="1.0"
)
Syntax:
def register_cmd_usage(cmd: str, args=None, usage=None)
Description:
Registers the usage of a command
Arguments:
cmd (string): command/feature to register usage
args (string): arguments of the command/feature. Default toNone
usage (string): usage of the command/feature. Default toNone
Returns:
None
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import register_cmd_usage
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit("I'm an example!")
return
register_cmd_usage("example", None, "Very example, wow.")
Syntax:
def getRegisteredCMDs()
Description:
Returns all registered commands in a sorted dictionary
Arguments:
None
Returns:
all registered commands in a sorted
dict
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import getRegisteredCMDs
ehandler = EventHandler()
MYCMD = "example"
if "example2" not in getRegisteredCMDs().keys():
MYCMD = "example2"
@ehandler.on(command=MYCMD, outgoing=True)
async def example(event):
await event.edit("I'm an example!")
return
Syntax:
def strlist_to_list(strlist: str) -> list
Description:
Convert a string list to datatype
list
Arguments:
strlist (string): a string formatted list
Returns:
a real
list
from string
Example usage:
from userbot.sysutils.sys_funcs import strlist_to_list
str_list = "['example', 4, 'example2' 1000]"
str_list = strlist_to_list(str_list)
for elem in str_list:
print(elem)
Syntax:
def str_to_bool(strbool: str) -> bool
Description:
Convert a string boolean to datatype
bool
Arguments:
strbool (string): a string formatted boolean
Returns:
a real
bool
from string
Example usage:
from userbot.sysutils.sys_funcs import str_to_bool
str_bool = str_to_bool("False")
if not str_bool:
print("Very false")
Syntax:
def isLinux() -> bool
Description:
Check if HyperUBot is running on a Linux based device
Arguments:
None
Returns:
True
if device runs a linux based system elseFalse
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import isLinux
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
if isLinux():
await event.edit("I'm running on a Linux system!")
else:
await event.edit("¯\_(ツ)_/¯")
return
Syntax:
def isMacOS() -> bool
Description:
Check if HyperUBot is running on a macOS device
Arguments:
None
Returns:
True
if device is running macOS elseFalse
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import isMacOS
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
if isMacOS():
await event.edit("I'm running on an Apple OS!")
else:
await event.edit("Nope my OS is not from Apple")
return
Syntax:
def isWindows() -> bool
Description:
Check if HyperUBot is running on a Windows device
Arguments:
None
Returns:
True
if device is running Windows elseFalse
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import isWindows
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
if isWindows():
await event.edit("Windows forever!")
else:
await event.edit("I'm sorry Microsoft :/")
return
Syntax:
def isAndroid() -> bool
Description:
Check if HyperUBot is running on an Android device
Arguments:
None
Returns:
True
if device is running Android elseFalse
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import isAndroid
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
if isAndroid():
await event.edit("Hello Google!")
else:
await event.edit("Not Google?")
return
Syntax:
def isWSL() -> bool
Description:
Check if HyperUBot is running on Windows Subsystem for Linux (2), a feature Windows 10 does offer.
Arguments:
None
Returns:
True
if HyperUBot is running on WSL elseFalse
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import isWSL
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
if isWSL():
await event.edit("Hi Linux, I'm Windows!")
else:
await event.edit("No? ok...")
return
Syntax:
def getDistro() -> str
Description:
Try to get the name of the current running distro. Works on Linux based Systems only.
Arguments:
None
Returns:
the name of the distro else an empty string
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import getDistro
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit(f"The name of my distro is {getDistro()}")
return
Syntax:
def getDistro() -> str
Description:
Get and return the name of the current operating system. Might return an empty string if OS is unknown.
Arguments:
None
Returns:
the name of the current operating system
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import os_name
ehandler = EventHandler()
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit(f"I'm running on {os_name()}")
return
Syntax:
def verAsTuple(version: str) -> tuple
Description:
Converts a version string to a version tuple. String should be 'well-formed' e.g.
1.2.3
or1.2.3-beta
. Useful to compare 2 different (or equal) versions for a possible case (e.g. limit a feature to a minimum required version)
Arguments:
version (string): a 'well-formed' version as string
Returns:
the version as
tuple
if string is well-formed else an emptytuple
Example usage:
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.sys_funcs import verAsTuple
ehandler = EventHandler()
MY_VERSION = "2.5"
if verAsTuple(MY_VERSION) >= (2, 5):
import xyz_module as my_module
else:
import xyz_module_old as my_module
@ehandler.on(command="example", outgoing=True)
async def example(event):
await event.edit(my_module.function())
return
Syntax:
def requiredVersion(min_ver: str, max_ver: str, empty_func: bool = False)
Description:
Wraps a given function and returns it only if current HyperUBot version is between min and max version. If version does not match required versions, a non callable type (
None
) will be returned instead. Ideal if you want to limit your functions or features to certain versions only
Arguments:
min_ver (string): minimum required version
max_ver (string): maximum required version
empty_func (bool): if a callable empty function should be returned instead ofNone
Returns:
a callable function with it's original content else depending on
empty_func
a callable empty function orNone
Example usage:
from userbot.version import VERSION_TUPLE # import bot version (tuple)
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import (register_cmd_usage,
register_module_desc,
register_module_info)
from userbot.sysutils.sys_funcs import (requiredVersion, # import requiredVersion
verAsTuple) # convert string version to tuple
from logging import getLogger
log = getLogger(__name__)
ehandler = EventHandler(log)
# Add to handler if HyperUBot version is between 4.0.0 and 5.0.0
@ehandler.on(command="example", outgoing=True)
@requiredVersion("4.0.0", "5.0.0")
async def example(event):
await event.edit("I'm an example function!")
return
@ehandler.on(command="example2", outgoing=True)
@requiredVersion("5.0.2", "5.0.2") # version should match exactly v5.0.2
async def example2(event):
await event.edit("I'm an example2 function!")
return
# Register usages only if HyperUBot version match required versions
if verAsTuple("4.0.0") >= VERSION_TUPLE and \
verAsTuple("5.0.0") <= VERSION_TUPLE:
register_cmd_usage("example", None, "Very example, wow.")
if verAsTuple("5.0.2") == VERSION_TUPLE:
register_cmd_usage("example2", None, "Very much example, very wow.")
register_module_desc("I'm an example module!")
register_module_info(
name="Example",
authors="Example",
version="1.0"
)
HyperUBot - A customizable, modular Telegram userbot, with innovative components.
Copyright © 2020-2023 nunopenim & prototype74, licensed under PEL