def init(self, bot: ChatbotEngine): """ Initialize chatbot engine :param bot: :return: """ self.bot = bot self.logger = DotFlow2LoggerAdapter(logging.getLogger('df2_ext.csMatch'), self, self.bot, '$chatscriptMatch') bot.register_dotflow2_function('chatscriptMatch', {'object': self, 'method': 'chatscriptMatch', 'cost': 0, 'register_enabled': False})
def init(self, bot: ChatbotEngine): """ Initialize extension :param bot: :return: """ self.bot = bot self.logger = DotFlow2LoggerAdapter(logging.getLogger('df2_ext.ssent_an'), self, self.bot, '$simpleSentimentAnalysis') bot.register_dotflow2_function('simpleSentimentAnalysis', {'object': self, 'method': 'df2_simpleSentimentAnalysis', 'cost': 0.5, 'register_enabled': True})
def test_commands(): """Create bot.""" bot = create_test_bot(None, "flow") request = ChatbotEngine.create_request(":unknown_command", "joe", '7', '1') response = bot.get_response(request) assert response["output"]["text"].startswith('Unknown command.') request = ChatbotEngine.create_request(":help", "joe", '7', '1') response = bot.get_response(request) assert response["output"]["text"].startswith('Commands:') request = ChatbotEngine.create_request(":reset all", "joe", '7', '1') response = bot.get_response(request) assert response["output"]["text"].startswith('User data')
def rest(bot_id): # pylint: disable=W0612 """ Telegram webhook endpoint. """ logger.debug(f'Received a Telegram webhook request for botid {bot_id}') try: params = request.get_json(force=True) org_id = 1 # checks if bot is telegram enabled # if not, it delete the webhook and throw an exception enabled = webhook_check(bot_id) if enabled: dotbot = telegram.dotdb.find_dotbot_by_container_id( bot_id).dotbot token = dotbot['channels']['telegram']['token'] telegram.set_api_token(token) user_id = telegram.get_user_id(params) telegram_recv = telegram.get_message(params) bbot_request = telegram.to_bbot_request(telegram_recv) bbot = create_bot(config, dotbot) req = ChatbotEngine.create_request(bbot_request, user_id, bot_id, org_id) bbot_response = bbot.get_response(req) telegram.send_response(bbot_response) except Exception as e: print("type error: " + str(e)) print(traceback.format_exc()) # be sure to respond 200 code. telegram will keep sending it if doesnt get it return jsonify(success=True)
def rest(): # pylint: disable=W0612 try: params = request.get_json(force=True) logger.debug("Received request:" + str(params)) user_id = params['userId'] bot_id = params['botId'] org_id = params['orgId'] input_params = params['input'] # if 'runBot' in params: # run_bot = params['runBot'] dotbotContainer = restful.dotdb.find_dotbot_by_container_id(bot_id) if not dotbotContainer: raise Exception('Bot not found') bot = create_bot(config, dotbotContainer.dotbot) input_text = "" #for input_type, input_value in input_params.items(): # bot.get_response(input_type, input_value) # _ = input_type # input_text = input_text + input_value req = ChatbotEngine.create_request(input_params, user_id, bot_id, org_id) response = bot.get_response(req) except Exception as e: response = {'error': {'message': str(e)}} logger.debug("Response: " + str(response)) return json.dumps(response)
def test_socket_error(): """Test socket error.""" bot = create_test_bot(None, "chatscript") bot.port = 0 request = ChatbotEngine.create_request("", "Joe") response = bot.get_response(request) assert not response
def get_response(self, request: dict) ->dict: """ Return a response based on the input data. :param request: A dictionary with input data. :return: A response to the input data. """ return ChatbotEngine.create_response("dummy")
def init(self, bot: ChatbotEngine): """ :param bot: :return: """ self.bot = bot self.logger = DotFlow2LoggerAdapter( logging.getLogger('df2_ext.weather'), self, self.bot, '$weather') bot.register_dotflow2_function('weather', { 'object': self, 'method': 'df2_weather' }) bot.register_template_function('weather', { 'object': self, 'method': 'df2_weather' })
def test_create_bot(): """Create bot.""" bot = create_test_bot(None, "chatscript") assert bot.host assert bot.port request = ChatbotEngine.create_request("Hello", "Joe") response = bot.get_response(request) assert response["output"]["text"]
def init(self, core: ChatbotEngine): """ :param bot: :return: """ self.core = core self.logger = BBotLoggerAdapter( logging.getLogger('core_ext.send_email'), self, self.core, '$sendEmail') core.register_function( 'sendEmail', { 'object': self, 'method': 'sendEmail', 'cost': 0.001, 'register_enabled': True })
def process(self): """ @TODO this will be called from a pubsub event, so args might change Call to fallback bots defined in dotbot when the main bot has a no match o or when it doesnt answer or has an invalid response @TODO this might be replaced by a conditional pipeline :param bot: :param response: :return: """ if not self.core.bot.is_fallback and (self.core.response.get('noMatch') or self.core.response.get('error')): self.logger.debug( 'Bot engine has a no match. Looking fallback bots') # try import bots fbbs = self.core.dotbot.get('fallbackBots', []) for bot_name in fbbs: self.logger.debug(f'Trying with bot {bot_name}') bot_dotbot_container = self.core.dotdb.find_dotbot_by_idname( bot_name) if not bot_dotbot_container: raise Exception(f'Fallback bot not found {bot_name}') else: bot_dotbot = bot_dotbot_container.dotbot config_path = os.path.abspath( os.path.dirname(__file__) + "/../instance") config = load_configuration(config_path, "BBOT_ENV") bbot = create_bot(config, bot_dotbot) bbot.is_fallback = True req = ChatbotEngine.create_request(core.request['input'], core.user_id, 1, 1) fallback_response = bbot.get_response(req) if fallback_response.get('error'): self.logger.error( 'Fallback bot returned an invalid response. Discarding.' ) continue if not fallback_response.get('noMatch'): self.logger.debug( 'Fallback bot has a response. Returning this to channel.' ) self.core.response = fallback_response return if fbbs: self.logger.debug( 'Fallback bot don\'t have a response either. Sending original main bot response if any' ) else: self.logger.debug( 'No fallback defined for this bot. Sending original main bot response if any' ) self.logger.debug('Bot responded with a match. No fallback needed.') return
def init(self, bot: ChatbotEngine): """ :param bot: :return: """ self.bot = bot self.logger = DotFlow2LoggerAdapter( logging.getLogger('df2_ext.ssent_an'), self, self.bot, '$simpleSentimentAnalysis') bot.register_dotflow2_function('simpleSentimentAnalysis', { 'object': self, 'method': 'df2_simpleSentimentAnalysis' }) bot.register_template_function('simpleSentimentAnalysis', { 'object': self, 'method': 'df2_simpleSentimentAnalysis' })
def init(self, bot: ChatbotEngine): self.bot = bot self.logger = DotFlow2LoggerAdapter(logging.getLogger('df2_ext.core'), self, self.bot, 'DF2CoreFnc') self.functions = [ 'input', 'eq', 'gt', 'lt', 'gte', 'lte', 'code', 'goto', 'return', 'set', 'get', 'regexMatch', 'and', 'or' ] for f in self.functions: bot.register_dotflow2_function( f, { 'object': self, 'method': 'df2_' + f, 'cost': 0, 'register_enabled': False })
def init(self, bot: ChatbotEngine): """ Initializes extension :param bot: :return: """ self.bot = bot self.logger = DotFlow2LoggerAdapter( logging.getLogger('df2_ext.r_output'), self, self.bot, 'Output Response Ext') for f in self.functions: bot.register_dotflow2_function(f, { 'object': self, 'method': 'df2_' + f }) bot.register_template_function(f, { 'object': self, 'method': 'df2_' + f })
def test_create_bot(): """Create bot.""" config_settings = \ { "bbot": { "default_chatbot_engine": "dummy", "chatbot_engines": { "dummy": { "plugin_class": "tests.bbot.test_core.DummyEngine", "name": "engine", "loader": { "plugin_class": "tests.bbot.test_core.DummyPlugin", "name": "loader" }, "extensions": { "dummy_plugin_1": { "plugin_class": "tests.bbot.test_core.DummyPlugin", "name": "extension 1" }, "dummy_plugin_2": { "plugin_class": "tests.bbot.test_core.DummyPlugin", "name": "extension 2" } } } } }, "logging": { "version": 1 } } bot = create_test_bot(config_settings) info = config_settings["bbot"]["chatbot_engines"]["dummy"] assert bot.name == info["name"] assert bot.loader.name == info["loader"]["name"] assert bot.extensions["dummy_plugin_2"].name == \ info["extensions"]["dummy_plugin_2"]["name"] request = ChatbotEngine.create_request("dummy", "Joe") response = bot.get_response(request) assert response['output']['text'] == "dummy"
print("Usage: make console user_id bot_id org_id\n") sys.exit(255) print("Type \"quit\" or \"bye\" to leave chat\n\n") user_id, bot_id, org_id, debug = sys.argv[1:] dotbotContainer = console.dotdb.find_dotbot_by_idname(bot_id) if not dotbotContainer: raise Exception('Couldn\'t find the bot') while True: input_text = input("You: ") if input_text.lower() in ["!quit", "!bye"]: print("BBot: Bye!\n") sys.exit(0) bot = create_bot( config, dotbotContainer.dotbot ) # create new bot each volley to get same behavior as others stateless channels request = ChatbotEngine.create_request({'text': input_text}, user_id, bot_id, org_id) response = bot.get_response(request) if debug == 'debug': print('Debug: ' + str(response)) for r in response['output']: if r.get('text'): print(bot.dotbot['name'].capitalize() + ': ' + str(r['text']))