Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CLI entrypoint to init an MQ bot #178

Merged
merged 8 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 57 additions & 2 deletions chatbot_core/utils/bot_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
# from socketio import Client
from multiprocessing import Process, Event, synchronize
from threading import Thread, current_thread

import pkg_resources
from mycroft_bus_client import Message, MessageBusClient

from nltk.translate.bleu_score import sentence_bleu
Expand All @@ -43,9 +45,11 @@
import yaml
from klat_connector import start_socket

from chatbot_core.utils.logger import LOG
# from chatbot_core import ChatBot
from ovos_utils.log import LOG

# Causes circular imports
# from chatbot_core import ChatBot
# from chatbot_core.v2 import ChatBot as ChatBotV2

def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Expand Down Expand Up @@ -318,6 +322,19 @@ def start_bots(domain: str = None, bot_dir: str = None, username: str = None, pa
p.join()


def cli_start_mq_bot():
"""
Entrypoint to start an MQ chatbot
"""
import argparse

parser = argparse.ArgumentParser(description="Start a chatbot")
parser.add_argument("--bot", dest="bot_name",
help="Chatbot entrypoint name", type=str)
args = parser.parse_args()
run_mq_bot(args.bot_name)


def cli_start_bots():
"""
Entry Point to start bots from a Console Script
Expand Down Expand Up @@ -624,6 +641,44 @@ def wrapper(*args, **kwargs):
return wrapper


def _find_bot_modules():
try:
from importlib_metadata import entry_points
bot_entrypoints = entry_points(group="neon.plugin.chatbot")
except ImportError:
bot_entrypoints = pkg_resources.iter_entry_points("neon.plugin.chatbot")

return {entry.name: entry.load() for entry in bot_entrypoints}


def run_mq_bot(chatbot_name: str, vhost: str = '/chatbots',
run_kwargs: dict = None, init_kwargs: dict = None):
"""
Get an initialized MQ Chatbot instance
@param chatbot_name: chatbot entrypoint name and configuration key
@param vhost: MQ vhost to connect to (default /chatbots)
@param run_kwargs: kwargs to pass to chatbot `run` method
@param init_kwargs: extra kwargs to pass to chatbot `__init__` method
@returns: Started ChatBotV2 instance
"""
from neon_utils.log_utils import init_log
init_log({"logs": {"level_overrides": {"error": ['pika'],
"warning": ["filelock"]}}})
os.environ['CHATBOT_VERSION'] = 'v2'
run_kwargs = run_kwargs or dict()
init_kwargs = init_kwargs or dict()
bots = _find_bot_modules()
clazz = bots.get(chatbot_name)
if init_kwargs.get('config'):
LOG.info(f"Config specified: {init_kwargs['config']}")
if not clazz:
raise RuntimeError(f"Requested bot `{chatbot_name}` not found in: "
f"{list(bots.keys())}")
bot = clazz(service_name=chatbot_name, vhost=vhost, **init_kwargs)
bot.run(**run_kwargs)
return bot


if __name__ == "__main__":
start_bots("chatbotsforum.org", "~/PycharmProjects/chatbots", "Prompter", "n30nn30n", "2222.us", None, "BLENDER",
None, True, True)
9 changes: 6 additions & 3 deletions chatbot_core/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,23 @@
# US Patents 2008-2021: US7424516, US20140161250, US20140177813, US8638908, US8068604, US8553852, US10530923, US10530924
# China Patent: CN102017585 - Europe Patent: EU2156652 - Patents Pending

import logging
from ovos_utils.log import LOG
LOG.name = "chatbots"

# fmt = '%(asctime)s - %(levelname)-8s - %(name)s:%(filename)s:%(module)s:%(funcName)s:%(lineno)d - %(message)s'
# logging.basicConfig(level=logging.DEBUG, format=fmt, datefmt='%Y-%m-%d:%H:%M:%S')
LOG = logging.getLogger("chatbots")
# LOG = logging.getLogger("chatbots")
# logging.getLogger("socketio.client").setLevel(logging.WARNING)
# logging.getLogger("engineio.client").setLevel(logging.WARNING)
# logging.getLogger("urllib3").setLevel(logging.WARNING)


def make_logger(name, level=logging.DEBUG):
def make_logger(name, level=None):
"""
Create a logger with the specified name (used to create bot loggers)
"""
import logging
level = level or logging.DEBUG
logger = logging.getLogger(name)
logger.setLevel(level)
return logging.getLogger(name)
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ def get_requirements(requirements_filename: str):
entry_points={'console_scripts': ["start-klat-bots=chatbot_core.utils:cli_start_bots",
"stop-klat-bots=chatbot_core.utils:cli_stop_bots",
"debug-klat-bots=chatbot_core.utils:debug_bots",
"start-klat-prompter=chatbot_core.utils:cli_start_prompter"]},
"start-klat-prompter=chatbot_core.utils:cli_start_prompter",
"start-mq-bot=chatbot_core.utils.bot_utils:cli_start_mq_bot"]},
install_requires=get_requirements("requirements.txt"),
extras_requires={"extra-lgpl": get_requirements("extra-lgpl.txt")}
)
Loading