Skip to content

Commit

Permalink
Fixed #195 issue (#202)
Browse files Browse the repository at this point in the history
* added docs and readablity to api/main.py

* added docs and readablity to api/main.py

* Fixed #195 issue
  • Loading branch information
OussamaERrafif authored Sep 6, 2024
1 parent 9ee6068 commit f5aa167
Show file tree
Hide file tree
Showing 2 changed files with 113 additions and 19 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Let us inspire more folks !
### **[Claim Now!](https://aviyel.com/projects/84/pyhoneybot/rewards)**

<hr>
🇲🇺 🇺🇸 🇨🇦 🇦🇷 🇮🇳 🇬🇧 🇬🇬 🇧🇷 🇸🇽 🇵🇱 🇩🇪 🇲🇼
🇲🇺 🇺🇸 🇨🇦 🇦🇷 🇮🇳 🇬🇧 🇬🇬 🇧🇷 🇸🇽 🇵🇱 🇩🇪 🇲🇼 🇲🇦

</div>
<div align="center">
Expand Down
130 changes: 112 additions & 18 deletions src/honeybot/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,58 @@


class BotCore:
"""
The main class that represents the core functionality of the bot.
Args:
info (dict): A dictionary containing information about the bot.
password (str, optional): The password for the bot. Defaults to "".
Attributes:
info (dict): A dictionary containing information about the bot.
configs (dict): A dictionary containing the bot's configurations.
settings_path (str): The path to the bot's settings file.
root_path (str): The root path of the bot.
server_url (str): The URL of the server the bot connects to.
port (int): The port number the bot uses to connect to the server.
name (str): The name of the bot.
owners (list): A list of usernames who are the owners of the bot.
password (str): The password for the bot.
friends (list): A list of usernames who are friends of the bot.
autojoin_channels (list): A list of channels the bot automatically joins.
downloaded_plugins_to_load (list): A list of downloaded plugins to load.
required_modules (list): A list of required modules for the bot.
time (float): The current time.
irc (socket.socket): The socket object for the bot's IRC connection.
is_listen_on (int): A flag indicating whether the bot is listening for incoming messages.
domain (str): The domain of the server the bot connects to.
sp_command (str): The special command for the bot.
plugins (list): A list of loaded plugins.
core_plugins (list): A list of core plugins.
Methods:
message_info(s): Parses a message string and returns a dictionary containing information about the message.
bot_info(): Returns a dictionary containing information about the bot.
methods(): Returns a dictionary of methods that can be used by plugins.
send(msg): Sends a raw message to the server.
send_target(target, msg): Sends a message to a specific target (channel or user).
join(channel): Joins a channel.
is_valid_plug_name(name): Checks if a plugin name is valid.
print_running_infos(): Prints the running information of the bot.
load_plugins_from_folder(category_folder, from_conf, from_dir): Loads plugins from a folder.
load_plugins(): Loads the plugins specified in the plugins list.
run_plugins(incoming): Runs the loaded plugins on an incoming message.
core_commands_parse(incoming): Parses the core commands in an incoming message.
connect(): Connects to the server.
identify(): Sends the identification command to the server.
greet(): Sends the initial commands to the server after connecting.
pull(): Listens for incoming messages from the server.
quit(): Sends the quit command to the server.
stay_alive(incoming): Handles the stay alive functionality of the bot.
registered_run(): Runs the bot as a registered bot.
unregistered_run(): Runs the bot as an unregistered bot.
"""

def __init__(self, info, password=""):
self.info = info
with open(info["toml_path"], "rb") as f:
Expand Down Expand Up @@ -57,7 +109,22 @@ def __init__(self, info, password=""):

def message_info(self, s):
"""
s : incoming
Parses a message string and returns a dictionary containing information about the message.
Args:
s (str): The message string to parse.
Returns:
dict: A dictionary containing the following keys:
- 'prefix': The prefix of the message (if present).
- 'command': The command of the message.
- 'args': A list of arguments of the message.
- 'address': The address of the message (either a channel or a user).
- 'user': The user who sent the message.
Raises:
None.
"""
try:
prefix = ""
Expand All @@ -76,7 +143,6 @@ def message_info(self, s):
command = args.pop(0)
address = args[0] if "#" in args[0] else prefix.split("!~")[0]
user = prefix.split("!")[0]
# return prefix, command, args, address
return {
"prefix": prevent_none(prefix),
"command": prevent_none(command),
Expand All @@ -85,7 +151,6 @@ def message_info(self, s):
"user": prevent_none(user),
}
except Exception as e:
# logger.error(e)
pass

def bot_info(self):
Expand Down Expand Up @@ -126,6 +191,15 @@ def join(self, channel):
"""

def is_valid_plug_name(self, name):
"""
Checks if the given plug name is valid.
Args:
name (str): The name of the plug.
Returns:
bool: True if the name is valid, False otherwise.
"""
if name.startswith("__") or name == "":
return False

Expand All @@ -142,6 +216,14 @@ def print_running_infos(self):
print(output.line())

def load_plugins_from_folder(self, category_folder, from_conf=None, from_dir=None):
"""
Load plugins from a specified folder.
Args:
category_folder (str): The category folder from which to load the plugins.
from_conf (bool, optional): If True, load plugins specified in the configuration file. Defaults to None.
from_dir (bool, optional): If True, load plugins from the core directory. Defaults to None.
"""
if from_dir is True:
dir_path = os.path.join(self.info["plugins_path"], "core")
to_load = [f for f in os.listdir(dir_path) if self.is_valid_plug_name(f)]
Expand Down Expand Up @@ -183,15 +265,19 @@ def load_plugins_from_folder(self, category_folder, from_conf=None, from_dir=Non

def load_plugins(self):
"""
Load plugins that are specified in the plugins list.
Load plugins from the 'downloaded' and 'core' folders.
Args:
plugins_to_load (list of str): List of plugins to load.
This method loads plugins from two folders: 'downloaded' and 'core'. It first loads plugins from the 'downloaded'
folder using the 'load_plugins_from_folder' method with the 'from_conf' parameter set to True. Then, it loads plugins
from the 'core' folder using the same method with the 'from_dir' parameter set to True.
After loading the plugins, it prints a status message indicating that the plugins have been loaded.
Returns:
None
Examples:
TODO
"""

print(output.status("i") + " Loading plugins...")

self.load_plugins_from_folder("downloaded", from_conf=True)
Expand All @@ -202,13 +288,16 @@ def load_plugins(self):

def run_plugins(self, incoming):
"""
incoming is the unparsed string. refer to test.py
"""
Runs the plugins on the incoming message.
Args:
incoming (str): The incoming message.
Returns:
str: The modified incoming message after running the plugins.
"""
for plugin in self.plugins:
P = getattr(plugin, "Plugin")
# print(f"\033[0;33mTrying {plugin}\033[0;0m")
# print(self.plugins)
incoming = incoming
methods = self.methods()
info = self.message_info(incoming)
Expand Down Expand Up @@ -241,6 +330,9 @@ def greet(self):
print(output.status("x"), "Joined channels:", ", ".join(self.autojoin_channels))

def pull(self):
"""
Listens to incoming messages and parses them using core_commands_parse method.
"""
print(output.status("i"), "Listening to incoming messages")
while self.is_listen_on:
try:
Expand All @@ -253,13 +345,6 @@ def pull(self):
self.is_listen_on = False
self.quit()
except Exception as e:
# logger.error(e)
# print(e)
# logger.debug("there was an error")
# logger.debug(data)
# logger.debug("!!")
# logger.debug(line)
# logger.debug("-" * 50)
pass

def quit(self):
Expand All @@ -271,6 +356,15 @@ def quit(self):
"""

def stay_alive(self, incoming):
"""
Handles the stay alive functionality of the bot.
Args:
incoming (str): The incoming message.
Returns:
None
"""
if not incoming:
logger.critical("<must handle reconnection - incoming is not True>")
sys.exit()
Expand Down

0 comments on commit f5aa167

Please sign in to comment.