Skip to content

Classes

prototype74 edited this page Sep 16, 2021 · 3 revisions

HyperUBot does offer own predefined classes which are used mainly by the core and some built-in modules already. There are few functions which also work for your own modules. Here we will explain all classes which are allowed to be used in your modules.

Table of contents

userbot.sysutils.*

userbot.sysutils.colors

1. Color()

Color offers ANSI coded attributes which allow you to change the color of a wraped text in termial.
Tip: this class works better in combination with the setColorText() function

Syntax:

Color()

Attributes:

RED
GREEN
YELLOW
BLUE
MAGENTA
CYAN
RED_DARK
GREEN_DARK
YELLOW_DARK
BLUE_DARK
MAGENTA_DARK
CYAN_DARK
END

Example usage:

from userbot.sysutils.colors import Color

print(f"{Color.RED}Example text{Color.END}")

Note: always finish the specific text to color with Color.END!

2. ColorBG()

ColorBG offers ANSI coded attributes which allow you to change the background color of a wraped text in termial.
Tip: this class works better in combination with the setColorTextBG() function

Syntax:

ColorBG()

Attributes:

RED
GREEN
YELLOW
BLUE
MAGENTA
CYAN
RED_DARK
GREEN_DARK
YELLOW_DARK
BLUE_DARK
MAGENTA_DARK
CYAN_DARK
END

Example usage:

from userbot.sysutils.colors import ColorBG

print(f"{ColorBG.RED}Example text{ColorBG.END}")

Note: always finish the specific text to color with ColorBG.END!

userbot.sysutils.errors

This script includes custom exceptions

1. AccessError(Exception)

A custom exception that should notify about rejected access to a specific action

Syntax:

AccessError(message: str = "Access denied")

Example usage:

from userbot.sysutils.errors import AccessError

def is_example(name: str):
    if not name.lower() == "example":
        raise AccessError("You're not example!?")
    print("Hello, example!")
    return

2. UnauthorizedAccessError(Exception)

A custom exception that should notify about unauthorized access to a specific action

Syntax:

UnauthorizedAccessError(message: str = "Unauthorized access denied")

Example usage:

from userbot.sysutils.errors import UnauthorizedAccessError

def is_example(name: str):
    if not name.lower() == "example":
        raise UnauthorizedAccessError("You're not example!?")
    print("Hello, example!")
    return

userbot.sysutils.event_handler

One of the essential features of HyperUBot. EventHandler handles Telegram events which Telethon does offer in it's API such as NewMessage or MessageEdited. This class simplify the usage of these events in own handlers which are also wrapped by a try-except block to catch unhandled exceptions caused by the user's functions.

1. EventHandler()

Syntax:

EventHandler(log: Logger = None, traceback: bool = True)

Arguments (init):

log (Logger): passing an already existing logger. Default to None
logging (boolean): create a traceback in case of unhandled exceptions. Default to True

Functions:

def on(self, command: str, alt: str = None,
       hasArgs: bool = False, ignore_edits: bool = False, *args, **kwargs)

Default listen on function which uses MessageEdited and NewMessage events. This functions does handle the patterns automatically. The prefix trigger is .. Recommended for outgoing messages/updates.

Arguments:

command (string): command to listen to
alt (string): alternative way to command. Default to None
hasArgs (bool): if command takes arguments. Default to False
ignore_edits (bool): ignore edited messages. Default to False

Returns:

MessageEdited.Event or NewMessage.Event


def on_NewMessage(self, command: str, alt: str = None,
                  hasArgs: bool = False, *args, **kwargs)

Similar to on() function but listen to NewMessage events only. This functions does handle the patterns automatically. The prefix trigger is ..

Arguments:

command (string): command to listen to
alt (string): alternative way to command. Default to None
hasArgs (bool): if command takes arguments. Default to False

Returns:

NewMessage.Event


def on_ChatAction(self, *args, **kwargs)

Listen to chat activities (join, leave, new pinned message etc.) in any or certain chats.

Arguments:

Function accepts any further arguments as supported by ChatAction events

Returns:

ChatAction.Event


def on_Pattern(self, pattern: str, events, name: str, prefix: str = ".",
               hasArgs: bool = False, no_space_arg: bool = False,
               no_cmd: bool = False, *args, **kwargs)

Listen to given pattern depending on Event(s). This event handler gives the most freedom, however you should guarantee that your pattern doesn't cause conflicts with other registered commands/patterns!

Arguments:

pattern (string): pattern to listen to (regular expression)
events: Event to add to client. Also supported as list of Events
name: name of feature. should match pattern but without regex, not required to match patttern if no_cmd is set
prefix (string): the prefix used at the beginning of your pattern e.g. .example, /example or !example. Default is .. This is set automatically to a 'string wise none' if no_cmd is set
hasArgs (bool): whether pattern takes arguments, default to False, stays False if no_cmd is set
no_space_arg (bool): removes the space between command and argument in usage info. Default to False
no_cmd (bool): if pattern is no command to handle. Default to False

Returns:

the given Event(s) from events


Examples:

from userbot.sysutils.event_handler import EventHandler
from telethon.events import NewMessage, MessageEdited  # for on_Pattern()
from logging import getLogger

log = getLogger(__name__)

# initialize with default logger
ehandler = EventHandler()
# initialize with an already existing logger
ehandler = EventHandler(log)
# initialize with an already existing logger without Tracebacks
ehandler = EventHandler(log, False)

# on()
@ehandler.on(command="example", outgoing=True)
async def example(event):
    await event.edit("I'm an example command!")
    return

# on_NewMessage()
@ehandler.on_NewMessage(command="example", outgoing=True)
async def example(event):
    await event.edit("I'm an example command!")
    return

# on_ChatAction()
@ehandler.on_ChatAction()
async def example(event):
    if event.user_joined:
        await event.reply("Welcome!")
    return

# on_Pattern()
@ehandler.on_Pattern(pattern=r"^\!example(?: |$)(.*)",
                     events=[NewMessage, MessageEdited],
                     name="example",
                     prefix="!",
                     hasArgs=True,
                     outgoing=True)
async def example(event):
    await event.edit("I'm an example command!")
    return

# on_Pattern() auto reply to a certain person
@ehandler.on_Pattern(pattern=r"^Hi Paul$",
                     events=NewMessage,
                     name="autoreplytopaul",
                     chats=[123456789],
                     no_cmd=True,
                     incoming=True)
async def autoreplytopaul(event):
    await event.client.send_message(event.chat_id, "Oh, hi Mark")
    return

userbot.sysutils.properties

Properties gives, specially user modules, a new opportunity to store attributes permanently in an own prop file based on configurations (.ini). This allow the programs to load data from their own prop files e.g. after reboots to avoid any data loss.

1. Properties()

Syntax:

Properties(name: str)

Arguments (init):

name (string): filename

Note: The filename should not include illegal characters which are /, \, \r, \n, \t, <, >, :, ?, *, ", |, specially Windows doesn't accept these. Not all Operating Systems disallow the mentioned characters but the feature has to be universal compatible

Functions:

def init_props(self, sections=None)

Setup the prop file and checks if the file isn't already used by a different program. There is always a DEFAULT section. New sections are addable by passing a list or tuple to sections arg

Arguments:

sections (list or tuple): list of section names. Default to None

Returns:

None


def setprop(self, key: str, value, section=None) -> bool

Add or update an (existing) key with a new value. Key will always be stored to DEFAULT section if no section is given or doesn't exist.

Arguments:

key (string): existing/new key
value: new value
section (string): name of section. Default to None

Returns:

True if action was successful else False


def getprop(self, key: str, section=None)

Load the value from given key. getprop will always check in DEFAULT section if no section is given or doesn't exist.

Arguments:

key (string): existing key
section (string): name of section. Default to None

Returns:

the value from key else None if key doesn't exist


Examples:

from userbot.sysutils.properties import Properties

props = Properties("myprops")
props.init_props(["MySection1", "MySection2"])

props.setprop("testKey1", "testValue1")  # DEFAULT
props.setprop("testKey2", True, "MySection1")

if props.getprop("testKey2", "MySection1"):
    # do stuff

Access getprop and setprop easier:

from userbot.sysutils.properties import Properties

props = Properties("myprops")
props.init_props(["MySection1", "MySection2"])
getprop = props.getprop
setprop = props.setprop

setprop("testKey1", "testValue1")
setprop("testKey2", True, "MySection1")

if getprop("testKey2", "MySection1"):
    # do stuff