-
Notifications
You must be signed in to change notification settings - Fork 9
Classes
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
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!
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!
This script includes custom exceptions
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!")
returnA 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!")
returnOne 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.
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 toTrue
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 tocommand. Default toNone
hasArgs (bool): ifcommandtakes arguments. Default toFalse
ignore_edits (bool): ignore edited messages. Default toFalse
Returns:
MessageEdited.EventorNewMessage.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 tocommand. Default toNone
hasArgs (bool): ifcommandtakes arguments. Default toFalse
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 aslistof Events
name: name of feature. should matchpatternbut withoutregex, not required to matchpattternifno_cmdis set
prefix (string): the prefix used at the beginning of your pattern e.g..example,/exampleor!example. Default is.. This is set automatically to a 'string wise none' ifno_cmdis set
hasArgs (bool): whetherpatterntakes arguments, default toFalse, staysFalseifno_cmdis set
no_space_arg (bool): removes the space between command and argument in usage info. Default toFalse
no_cmd (bool): ifpatternis no command to handle. Default toFalse
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")
returnProperties 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.
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) -> boolAdd 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 toNone
Returns:
Trueif action was successful elseFalse
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 toNone
Returns:
the value from
keyelseNoneif 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 stuffAccess 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 stuffHyperUBot - A customizable, modular Telegram userbot, with innovative components.
Copyright © 2020-2023 nunopenim & prototype74, licensed under PEL