Ejemplo n.º 1
0
def run_telegram_bot(webhook_url, train=False):
    logging.basicConfig(level="INFO")
    try:
        KnowledgeGraph()
    except ServiceUnavailable:
        print('Neo4j connection failed. Program stopped.')
        return

    if train:
        train_bot()

    with open('keys.json') as f:
        data = json.load(f)
    telegram_api_key = data['telegram-api-key']

    # set webhook of telegram bot
    try:
        telegram_url = 'https://api.telegram.org/bot' + telegram_api_key + '/setWebhook?url=' + webhook_url
        urllib.request.urlopen(telegram_url)
    except:
        print("Error setting telegram webhook")
        return

    interpreter = Interpreter()
    agent = Agent.load('./models/dialogue', interpreter)

    input_channel = (TelegramInput(access_token=telegram_api_key,
                                   verify='event123_bot',
                                   webhook_url=webhook_url,
                                   debug_mode=True))

    agent.handle_channel(HttpInputChannel(5004, '/app', input_channel))
Ejemplo n.º 2
0
def _create_external_channel(channel, port, credentials_file):
    if credentials_file is None:
        _raise_missing_credentials_exception(channel)

    credentials = read_yaml_file(credentials_file)
    if channel == "facebook":
        input_blueprint = FacebookInput(credentials.get("verify"),
                                        credentials.get("secret"),
                                        credentials.get("page-access-token"))
    elif channel == "slack":
        input_blueprint = SlackInput(credentials.get("slack_token"),
                                     credentials.get("slack_channel"))
    elif channel == "telegram":
        input_blueprint = TelegramInput(credentials.get("access_token"),
                                        credentials.get("verify"),
                                        credentials.get("webhook_url"))
    elif channel == "mattermost":
        input_blueprint = MattermostInput(credentials.get("url"),
                                          credentials.get("team"),
                                          credentials.get("user"),
                                          credentials.get("pw"))
    elif channel == "twilio":
        input_blueprint = TwilioInput(credentials.get("account_sid"),
                                      credentials.get("auth_token"),
                                      credentials.get("twilio_number"))
    else:
        Exception("This script currently only supports the facebook,"
                  " telegram, mattermost and slack connectors.")

    return HttpInputChannel(port, None, input_blueprint)
Ejemplo n.º 3
0
def run(core_dir, nlu_dir):

    _endpoints = AvailableEndpoints.read_endpoints('endpoints.yml')
    _interpreter = NaturalLanguageInterpreter.create(nlu_dir)

    input_channel = TelegramInput(access_token=os.getenv(
        'TELEGRAM_ACCESS_TOKEN', ''),
                                  verify=os.getenv('VERIFY', ''),
                                  webhook_url=os.getenv('WEBHOOK_URL', ''))

    elastic_user = os.getenv('ELASTICSEARCH_USER')
    if elastic_user is None:
        _tracker_store = ElasticTrackerStore(
            domain=os.getenv('ELASTICSEARCH_URL', 'elasticsearch:9200'))
    else:
        _tracker_store = ElasticTrackerStore(
            domain=os.getenv('ELASTICSEARCH_URL', 'elasticsearch:9200'),
            user=os.getenv('ELASTICSEARCH_USER', 'user'),
            password=os.getenv('ELASTICSEARCH_PASSWORD', 'password'),
            scheme=os.getenv('ELASTICSEARCH_HTTP_SCHEME', 'http'),
            scheme_port=os.getenv('ELASTICSEARCH_PORT', '80'))

    _agent = load_agent(core_dir,
                        interpreter=_interpreter,
                        tracker_store=_tracker_store,
                        endpoints=_endpoints)

    http_server = _agent.handle_channels([input_channel], 5001, "")

    try:
        http_server.serve_forever()
    except Exception as exc:
        logger.exception(exc)
Ejemplo n.º 4
0
def run_telegram_bot(train=False, nlu_name=None, voice_output=False, url=None):
    webhook_url, bot_name, telegram_api_key = load_dm_config()

    if url:
        webhook_url = url + '/app/webhook'

    if train:
        train_bot()

    if not test_neo4j_connection():
        return

    # Set Interpreter (NLU) to th given engine
    interpreter = select_interpreter(nlu_name)

    # load the trained agent model
    agent = Agent.load('./models/dialogue', interpreter)
    logging.info('Agent model loaded.')

    logging.info('Starting Telegram channel...')
    try:
        if voice_output:
            input_channel = (TelegramCustomInput(access_token=telegram_api_key,
                                                 verify=bot_name,
                                                 webhook_url=webhook_url,
                                                 debug_mode=True))
        else:
            input_channel = (TelegramInput(access_token=telegram_api_key,
                                           verify=bot_name,
                                           webhook_url=webhook_url,
                                           debug_mode=True))
        agent.handle_channel(HttpInputChannel(5004, '/app', input_channel))
    except Exception as err:
        logging.error("Error starting Telegram Channel: {}".format(err))
Ejemplo n.º 5
0
def get_input_channel(ip=None):
    if ip is not None:
        input_channel = TelegramInput(
            access_token="583835183:AAF9oo9QpLzWS7I_IQ4f_j0Um-HzH6TK9n4", # you get this when setting up a bot
            verify="KerovAssistantBot", # this is your bots username
            webhook_url="https://"+ ip +".ngrok.io/webhook" # the url your bot should listen for messages
        )
    else:
        input_channel = ConsoleInputChannel()
    return input_channel
Ejemplo n.º 6
0
def run():
    interpreter = RasaNLUInterpreter('models/nlu/default/current')

    agent = Agent.load('models/dialogue', interpreter=interpreter)

    input_channel = TelegramInput(access_token=TELEGRAM_ACCESS_TOKEN,
                                  verify=VERIFY,
                                  webhook_url=WEBHOOK_URL)

    agent.handle_channel(HttpInputChannel(5002, "", input_channel))
Ejemplo n.º 7
0
def _create_single_channel(channel, credentials):
    if channel == "facebook":
        from rasa_core.channels.facebook import FacebookInput

        return FacebookInput(credentials.get("verify"),
                             credentials.get("secret"),
                             credentials.get("page-access-token"))
    elif channel == "slack":
        from rasa_core.channels.slack import SlackInput

        return SlackInput(credentials.get("slack_token"),
                          credentials.get("slack_channel"))
    elif channel == "telegram":
        from rasa_core.channels.telegram import TelegramInput

        return TelegramInput(credentials.get("access_token"),
                             credentials.get("verify"),
                             credentials.get("webhook_url"))
    elif channel == "mattermost":
        from rasa_core.channels.mattermost import MattermostInput

        return MattermostInput(credentials.get("url"), credentials.get("team"),
                               credentials.get("user"), credentials.get("pw"))
    elif channel == "twilio":
        from rasa_core.channels.twilio import TwilioInput

        return TwilioInput(credentials.get("account_sid"),
                           credentials.get("auth_token"),
                           credentials.get("twilio_number"))
    elif channel == "botframework":
        from rasa_core.channels.botframework import BotFrameworkInput
        return BotFrameworkInput(credentials.get("app_id"),
                                 credentials.get("app_password"))
    elif channel == "rocketchat":
        from rasa_core.channels.rocketchat import RocketChatInput
        return RocketChatInput(credentials.get("user"),
                               credentials.get("password"),
                               credentials.get("server_url"))
    elif channel == "rasa":
        from rasa_core.channels.rasa_chat import RasaChatInput

        return RasaChatInput(credentials.get("url"),
                             credentials.get("admin_token"))
    else:
        raise Exception("This script currently only supports the "
                        "{} connectors."
                        "".format(", ".join(BUILTIN_CHANNELS)))
Ejemplo n.º 8
0
def run(core_dir, nlu_dir):

    _endpoints = AvailableEndpoints.read_endpoints('endpoints.yml')
    _interpreter = NaturalLanguageInterpreter.create(nlu_dir)

    input_channel = TelegramInput(access_token=os.getenv(
        'TELEGRAM_ACCESS_TOKEN', ''),
                                  verify=os.getenv('VERIFY', ''),
                                  webhook_url=os.getenv('WEBHOOK_URL', ''))

    _agent = load_agent(core_dir,
                        interpreter=_interpreter,
                        endpoints=_endpoints)

    http_server = _agent.handle_channels([input_channel], 5001, "")

    try:
        http_server.serve_forever()
    except Exception as exc:
        logger.exception(exc)
Ejemplo n.º 9
0
def test_telegram_channel():
    # telegram channel will try to set a webhook, so we need to mock the api

    httpretty.register_uri(
            httpretty.POST,
            'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/setWebhook',
            body='{"ok": true, "result": {}}')

    httpretty.enable()

    from rasa_core.channels.telegram import TelegramInput
    from rasa_core.agent import Agent
    from rasa_core.interpreter import RegexInterpreter

    # load your trained agent
    agent = Agent.load(MODEL_PATH, interpreter=RegexInterpreter())

    input_channel = TelegramInput(
            # you get this when setting up a bot
            access_token="123:YOUR_ACCESS_TOKEN",
            # this is your bots username
            verify="YOUR_TELEGRAM_BOT",
            # the url your bot should listen for messages
            webhook_url="YOUR_WEBHOOK_URL"
    )

    # set serve_forever=False if you want to keep the server running
    s = agent.handle_channels([input_channel], 5004, serve_forever=False)
    # END DOC INCLUDE
    # the above marker marks the end of the code snipped included
    # in the docs
    try:
        assert s.started
        routes_list = utils.list_routes(s.application)
        assert routes_list.get("/webhooks/telegram/").startswith(
                'telegram_webhook.health')
        assert routes_list.get("/webhooks/telegram/webhook").startswith(
                'telegram_webhook.message')
    finally:
        s.stop()
        httpretty.disable()
Ejemplo n.º 10
0
def run(serve_forever=True):
    AvailableEndpoints = namedtuple('AvailableEndpoints', 'nlg'
                                    'nlu'
                                    'action'
                                    'model')

    _endpoints = EndpointConfig(url="http://209.97.146.240:5055/webhook")
    try:
        _interpreter = RasaNLUInterpreter("models/current/nlu/")
        # load your trained agent
        agent = Agent.load("models/current/dialogue",
                           interpreter=_interpreter,
                           action_endpoint=_endpoints)

        facebook_channel = FacebookInput(
            fb_verify="rasa-bot",
            # you need tell facebook this token, to confirm your URL
            fb_secret="a5fd69f298c42b0d87de817c7071a6a4",  # your app secret
            fb_access_token=
            "EAABqmImVq5sBAD0A5VeANePSHM7HJkr1rsJKCytYRtNfZBaIProv0jmXmg6xnZALqgkQ1P3Wtw5ZB8tfvrZChE0JCCHI9FhKDkAorhixyh9Vho49ykQQlPV1dJTVS0gP4JRwMC6fsBEFG7LhpXrgsDaqTgaI6bZCxjNG1AzcLoXXRjQgkHMkZAFxLWfLt2LNoZD"
            # token for the page you subscribed to
        )

        input_channel = TelegramInput(
            # you get this when setting up a bot
            access_token="516790963:AAEgzLnFfhmNk48eEwqb1sfFD-HqAThQHT4",
            # this is your bots username
            verify="regispucmm_bot",
            # the url your bot should listen for messages
            webhook_url="https://www.sysservices.site/webhooks/telegram/webhook"
        )

        # set serve_forever=False if you want to keep the server running
        s = agent.handle_channels([facebook_channel, input_channel],
                                  5005,
                                  serve_forever=True)

    except:
        raise Exception("Failed to run")
Ejemplo n.º 11
0
def test_handling_of_telegram_user_id():
    # telegram channel will try to set a webhook, so we need to mock the api

    httpretty.register_uri(
        httpretty.POST,
        'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/setWebhook',
        body='{"ok": true, "result": {}}')

    # telegram will try to verify the user, so we need to mock the api
    httpretty.register_uri(
        httpretty.GET,
        'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/getMe',
        body='{"result": {"id": 0, "first_name": "Test", "is_bot": true, '
        '"username": "******"}}')

    # The channel will try to send a message back to telegram, so mock it.
    httpretty.register_uri(
        httpretty.POST,
        'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/sendMessage',
        body='{"ok": true, "result": {}}')

    httpretty.enable()

    from rasa_core.channels.telegram import TelegramInput
    from rasa_core.agent import Agent
    from rasa_core.interpreter import RegexInterpreter

    # load your trained agent
    agent = Agent.load(MODEL_PATH, interpreter=RegexInterpreter())

    input_channel = TelegramInput(
        # you get this when setting up a bot
        access_token="123:YOUR_ACCESS_TOKEN",
        # this is your bots username
        verify="YOUR_TELEGRAM_BOT",
        # the url your bot should listen for messages
        webhook_url="YOUR_WEBHOOK_URL")

    from flask import Flask
    import rasa_core
    app = Flask(__name__)
    rasa_core.channels.channel.register([input_channel],
                                        app,
                                        agent.handle_message,
                                        route="/webhooks/")

    data = {
        "message": {
            "chat": {
                "id": 1234,
                "type": "private"
            },
            "text": "Hello",
            "message_id": 0,
            "date": 0
        },
        "update_id": 0
    }
    test_client = app.test_client()
    test_client.post("http://localhost:5004/webhooks/telegram/webhook",
                     data=json.dumps(data),
                     content_type='application/json')

    assert agent.tracker_store.retrieve("1234") is not None
    httpretty.disable()
Ejemplo n.º 12
0
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
#from rasa_telegram_connector import TelegramInput
from rasa_core.channels.telegram import TelegramInput
from rasa_core.utils import EndpointConfig

import logging
logging.basicConfig(level=logging.DEBUG)

nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/nlu')
action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")

agent = Agent.load('./models/dialogue',
                   interpreter=nlu_interpreter,
                   action_endpoint=action_endpoint)

input_channel = TelegramInput(
    # you get this when setting up a bot
    access_token="633716437:AAHU_6G6nyNjXDRpsnGTtPOfTyFy0F_GG9E",
    # this is your bots username
    verify="rasawaybot",
    # the url your bot should listen for messages
    webhook_url="matabares.ngrok.io/webhooks/telegram/webhook")

agent.handle_channels([input_channel], 5004, serve_forever=True)
Ejemplo n.º 13
0
from rasa_core.channels.telegram import TelegramInput
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
import yaml
from rasa_core.utils import EndpointConfig


nlu_interpreter = RasaNLUInterpreter('./models/banque_finalv2/nlu')
action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
agent = Agent.load('./models/banque_finalv2/dialogue', interpreter = nlu_interpreter, action_endpoint = action_endpoint)

input_channel = TelegramInput("699840177:AAF0m4L7MzeyJroyC9Wx944W1VNOsOZjkXY", "JohnnyMonConseiller_bot", "https://1a36a98b.ngrok.io/webhooks/telegram/webhook", True)

agent.handle_channels([input_channel], 5004, serve_forever=True)