コード例 #1
0
    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.
        """
        bot = Plugin.get_class_from_fullyqualified(
            'engines.python.bots.' + self.dotbot['python']['bot_class'] + '.PythonBot')
        bot = bot(self.config)
        bot.logger = logging.getLogger("python")
        response =  bot.get_response(request)

        bot.logger.debug("PythonBot response BBOT format: " + str(response))
        return response
コード例 #2
0
ファイル: chatbot_engine.py プロジェクト: SeedVault/rhizome
    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.
        """
        super().get_response(request)

        pbot = Plugin.get_class_from_fullyqualified(
            'engines.python.bots.' + self.dotbot.chatbot_engine['bot_class'] +
            '.PythonBot')
        pbot = pbot(self.config, self)
        pbot.get_response(request)

        return self.response
コード例 #3
0
ファイル: app.py プロジェクト: theoturner/rhizome
def create_app():
    """Create and configure an instance of the application."""
    app = Flask(__name__)
    config_path = os.path.abspath(
        os.path.dirname(__file__) + "../../../instance")
    config = load_configuration(config_path, "BBOT_ENV")
    app.config.from_mapping(config)
    w_config = config["channel_restful"]
    restful = Plugin.load_plugin(w_config)
    logging.config.dictConfig(config['logging'])
    logger = logging.getLogger("channel_restful")

    @app.route('/Channels/RESTfulWebService', methods=['POST'])
    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)

    @app.route('/TestWebChatBot')
    def test():  # pylint: disable=W0612
        return render_template('test.html')

    return app
コード例 #4
0
ファイル: app.py プロジェクト: SeedVault/rhizome
from flask import Flask, request, render_template, Response, jsonify
from collections import defaultdict

from bbot.core import Plugin
from bbot.config import load_configuration
"""Create and configure an instance of the application."""
app = Flask(__name__)
CORS(app)

config = load_configuration(
    os.path.abspath(os.path.dirname(__file__) + "../../../instance"),
    "BBOT_ENV")
app.config.from_mapping(config)
logging.config.dictConfig(config['logging'])

restful = Plugin.load_plugin(config['channel_restful'])
print("Listening RESTful from path: " + restful.get_endpoint_path())
telegram = Plugin.load_plugin(config['channel_telegram'])
botframework = Plugin.load_plugin(config['channel_botframework'])


@app.route(restful.get_endpoint_path(), methods=['POST'])
@cross_origin(origins=restful.config['cors_origin'])
def restful_endpoint():  # pylint: disable=W0612
    response = restful.endpoint(request)
    return Response(response['response'],
                    status=response['status'],
                    mimetype=response['mimetype'])


@app.route('/TestWebChatBot')
コード例 #5
0
ファイル: webhooks_check.py プロジェクト: theoturner/rhizome
"""Telegram Webhooks check."""
import logging.config
import os
from bbot.core import Plugin
from bbot.config import load_configuration

config_path = os.path.abspath(os.path.dirname(__file__) + "../../../instance")
config = load_configuration(config_path, "BBOT_ENV")
t_config = config["channel_telegram"]
telegram = Plugin.load_plugin(t_config)
logging.config.dictConfig(config['logging'])

telegram.webhooks_check()
コード例 #6
0
ファイル: app.py プロジェクト: theoturner/rhizome
BBot Console App.

run this with: BBOT_ENV=development make console joe 5b9add84e2e290380e4fd3cf 1 nodebug

"""
import os
import sys
import logging.config
from bbot.core import create_bot, ChatbotEngine, Plugin
from bbot.config import load_configuration

# Load setting and start chat
config_path = os.path.abspath(os.path.dirname(__file__) + "../../../instance")
config = load_configuration(config_path, "BBOT_ENV")
c_config = config["channel_console"]
console = Plugin.load_plugin(c_config)
logging.config.dictConfig(config['logging'])
logger = logging.getLogger("channel_console")

print("\nBBot Console App - Version 1.0\n")

if len(sys.argv) <= 4:
    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:
コード例 #7
0
def test_create_plugin_dynamically():
    """Create plugin dynamically."""
    settings = {"plugin_class": "tests.bbot.test_core.DummyPlugin",
                "name": "dummy plugin"}
    instance = Plugin.load_plugin(settings)
    assert instance.name == settings["name"]
コード例 #8
0
ファイル: app.py プロジェクト: theoturner/rhizome
def create_app():
    """Create and configure an instance of the application."""
    app = Flask(__name__)
    config_path = os.path.abspath(
        os.path.dirname(__file__) + "../../../instance")
    config = load_configuration(config_path, "BBOT_ENV")
    app.config.from_mapping(config)
    t_config = config["channel_telegram"]
    telegram = Plugin.load_plugin(t_config)
    logging.config.dictConfig(config['logging'])
    logger = logging.getLogger("channel_telegram")

    @app.route('/channels/telegram/<bot_id>', methods=['POST'])
    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 webhook_check(bot_id):

        dotbot = telegram.dotdb.find_dotbot_by_container_id(bot_id).dotbot

        if dotbot['channels']['telegram']['enabled']:
            return True

        logger.warning(f'Deleting invalid Telegram webhook for botid {bot_id}')
        telegram.set_api_token(dotbot['channels']['telegram']['token'])
        delete_ret = telegram.api.deleteWebhook()
        if delete_ret:
            logger.warning("Successfully deleted.")
            return False
            #raise Exception('Received a telegram webhook request on a telegram disabled bot. The webhook was deleted now.')
        else:
            error = "Received a telegram webhook request on a telegram disabled bot and couldn't delete the invalid webhook"
            logger.error(error)
            raise Exception(error)

    return app
コード例 #9
0
ファイル: api.py プロジェクト: theoturner/rhizome
import os
from flask import Flask, request, jsonify, Response, g
from flask_restful import Resource, Api
from marshmallow import ValidationError

from bbot.config import load_configuration
from bbot.core import Plugin
from .models import AuthenticationError
from .schemas import CredentialsSchema, AuthSchema, DotBotContainerSchema, DotFlowContainerSchema

app = Flask(__name__)
config_path = os.path.abspath(os.path.dirname(__file__) + "/../instance")
config = load_configuration(config_path, "BBOT_ENV")
app.config.from_mapping(config)
dr_config = config["dot_repository"]
dotdb = Plugin.load_plugin(dr_config)
api = Api(app, prefix="/api")


def json_response(data: dict, status_code: int = 200) -> Response:
    """
    Sintax sugar to create a custom HTTP response.

    :param data: A dictionary to be serialized as a JSON string
    :status_code: HTTP status code. Defaults to 200.
    :return: Response
    """
    response = jsonify(data)
    response.status_code = status_code
    return response