Esempio n. 1
0
class bot():
    """This is a bare minimal example for how to write your own RiveScript bot!

For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.

example.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.

Type /quit when you're done to exit this example.
"""

    def __init__(self):
        self.currentOperation = None
        self.rs = RiveScript()
        self.rs.load_directory(os.path.dirname(__file__) + "/rep_src")
        self.rs.sort_replies()

    def sanitizeUserQuery(self, userQuery):
        return userQuery

    def identifyOperation(self, userQuery):
        """
        function identifyOperation(string: userQuery)
        Output: ([keywords_in_input], [action_in_input])
        """
        userQuery = self.sanitizeUserQuery(userQuery)
        queryTokens = nltk.word_tokenize(userQuery)
        pos = nltk.pos_tag(queryTokens)
        keywords = []
        verbs = []
        adjective = []
        for w in pos:
            if w[1] == 'NN' or w[1] == 'NNP':
                keywords.append(str(w[0]))
            if w[1] == 'VB' or w[1] == 'VBD' or w[1] == 'VBN':
                verbs.append(w[0])
            if w[1] == 'JJ':
                adjective.append(w[0])

        # print(str(keywords).rsplit() + " " + str(verbs).rsplit() + " " + str(adjective).rsplit())
        return (keywords, verbs, adjective)

    def reply(self, user, msg):
        # t = self.identifyOperation(msg)
        # print(' '.join(t[0] + t[1] + t[2]))
        return self.rs.reply(user, msg)
Esempio n. 2
0
 def Agente(self):
     self.agente = RiveScript()
     self.agente.load_directory("./recursos")
     self.agente.sort_replies()
     self.lector = Dispatch("SAPI.SpVoice")
     if time.localtime().tm_hour < 12:
         self.agente.set_variable("time", "dia")
     else:
         if time.localtime().tm_hour < 18:
             self.agente.set_variable("time", "tarde")
         else:
             self.agente.set_variable("time", "noche")        
Esempio n. 3
0
    def reload_brain(self):
        """(Re)load the RiveScript brain for the bot."""
        self.log.info("Loading RiveScript brain from {}".format(
            self.c.personality.replies
        ))

        self.rs = RiveScript(
            debug=self.c.debug.rivescript,
            utf8=True,
        )
        self.rs.load_directory(self.c.personality.replies)
        self.rs.sort_replies()
Esempio n. 4
0
class RiveScriptTestCase(unittest.TestCase):
    """Base class for all RiveScript test cases, with helper functions."""

    def setUp(self, **kwargs):
        self.rs = None # Local RiveScript bot object
        self.username = "******"


    def tearDown(self):
        pass


    def new(self, code, **kwargs):
        """Make a bot and stream in the code."""
        self.rs = RiveScript(**kwargs)
        self.extend(code)


    def extend(self, code):
        """Stream code into the bot."""
        self.rs.stream(code)
        self.rs.sort_replies()


    def reply(self, message, expected):
        """Test that the user's message gets the expected response."""
        reply = self.rs.reply(self.username, message)
        self.assertEqual(reply, expected)


    def uservar(self, var, expected):
        """Test the value of a user variable."""
        value = self.rs.get_uservar(self.username, var)
        self.assertEqual(value, expected)
Esempio n. 5
0
def bot_talk():
    from rivescript import RiveScript
    import sys, os

    bot = RiveScript(utf8=True)
    bot.load_directory("/home/mate/Downloads/web2py/applications/saria/static/riverscript/brain/")
    #bot.load_directory("/home/relsi/Projetos/Web2py/pris/applications/saria/static/riverscript/brain")
    bot.sort_replies()

    msg = request.post_vars.chat_text

    reply = bot.reply("localuser", msg.decode('utf-8'))
    
    return reply
Esempio n. 6
0
	def __init__(self, script_dir, user, ss, debug=False):
		self._user     = user
		self._redirect = None

		# init RiveScript
		self._rs = RiveScript(debug=debug)
		self._rs.load_directory(script_dir)
		self._rs.sort_replies()

		# restore session
		if isinstance(ss, SessionStore):
			self._ss = ss
		else:
			raise RuntimeError("RiveBot init error: provided session store object is not a SessionStore instance.")

		self._restore_session()

		# register event callbacks
		self._rs.on('topic',    self._topic_cb)
		self._rs.on('uservar',  self._uservar_cb)
Esempio n. 7
0
 def __init__(self):
     self.currentOperation = None
     self.rs = RiveScript()
     self.rs.load_directory(os.path.dirname(__file__) + "/rep_src")
     self.rs.sort_replies()
Esempio n. 8
0
from rivescript import RiveScript
import os.path
import re
bot = RiveScript(utf8=True)
bot.unicode_punctuation = re.compile(r'[.,!?;:]')

file = os.path.dirname(__file__)
data = os.path.join(file, 'data')

bot = RiveScript()
bot.load_directory(data)
bot.sort_replies()

print(
    'You are now talking to Chatty. Type \"/q\" to end the conversation. Have fun!'
)

while True:
    msg = input('You> ')
    if msg == '/q':
        print('Bot>', "Bye Bye")
        quit()

    reply = bot.reply("localuser", msg)
    print('Bot>', reply)
Esempio n. 9
0
import sys
import os
import json
from rivescript import RiveScript
bot = RiveScript(utf8=True)
bot.load_file(sys.argv[1])
bot.sort_replies()
deparsed = bot.deparse()
full_dump = {"sub_clause": [], "array_clauses": [], "include_clauses": [], "raw_rule_clauses": []}
for raw_rule_topic in deparsed["topic"].keys():
  for raw_rule_key in deparsed["topic"][raw_rule_topic].keys():
    raw_rule = {"topic": raw_rule_topic, "name": raw_rule_key, "reply": [], "condition": [], "previous": []}
    if "reply" in deparsed["topic"][raw_rule_topic][raw_rule_key].keys():
      for reply in deparsed["topic"][raw_rule_topic][raw_rule_key]["reply"]:
        raw_rule["reply"].append(reply)
    if "condition" in deparsed["topic"][raw_rule_topic][raw_rule_key].keys():
      for reply in deparsed["topic"][raw_rule_topic][raw_rule_key]["condition"]:
        raw_rule["condition"].append(reply)
    if "previous" in deparsed["topic"][raw_rule_topic][raw_rule_key].keys():
      raw_rule["previous"].append(deparsed["topic"][raw_rule_topic][raw_rule_key]["previous"])
    full_dump["raw_rule_clauses"].append(raw_rule)

for raw_rule_topic in deparsed["that"].keys():
  for raw_rule_key in deparsed["that"][raw_rule_topic].keys():
    raw_rule = {"topic": raw_rule_topic, "name": raw_rule_key, "reply": [], "condition": [], "previous": []}
    if "reply" in deparsed["that"][raw_rule_topic][raw_rule_key].keys():
      for reply in deparsed["that"][raw_rule_topic][raw_rule_key]["reply"]:
        raw_rule["reply"].append(reply)
    if "condition" in deparsed["that"][raw_rule_topic][raw_rule_key].keys():
      for reply in deparsed["that"][raw_rule_topic][raw_rule_key]["condition"]:
        raw_rule["condition"].append(reply)
Esempio n. 10
0
def interactive_mode():
    # Get command line options.
    options, remainder = [], []
    try:
        options, remainder = getopt.getopt(sys.argv[1:], 'dju', ['debug',
                                                                'json',
                                                                'utf8',
                                                                'log=',
                                                                'strict',
                                                                'nostrict',
                                                                'depth=',
                                                                'help'])
    except:
        print("Unrecognized options given, try " + sys.argv[0] + " --help")
        exit()

    # Handle the options.
    debug, depth, strict = False, 50, True
    with_json, help, log = False, False, None
    utf8 = False
    for opt in options:
        if opt[0] == '--debug' or opt[0] == '-d':
            debug = True
        elif opt[0] == '--strict':
            strict = True
        elif opt[0] == '--nostrict':
            strict = False
        elif opt[0] == '--json':
            with_json = True
        elif opt[0] == '--utf8' or opt[0] == '-u':
            utf8 = True
        elif opt[0] == '--help' or opt[0] == '-h':
            help = True
        elif opt[0] == '--depth':
            depth = int(opt[1])
        elif opt[0] == '--log':
            log = opt[1]

    # Help?
    if help:
        print("""Usage: rivescript [options] <directory>

Options:

    --debug, -d
        Enable debug mode.

    --log FILE
        Log debug output to a file (instead of the console). Use this instead
        of --debug.

    --json, -j
        Communicate using JSON. Useful for third party programs.

    --strict, --nostrict
        Enable or disable strict mode (enabled by default).

    --depth=50
        Set the recursion depth limit (default is 50).

    --help
        Display this help.

JSON Mode:

    In JSON mode, input and output is done using JSON data structures. The
    format for incoming JSON data is as follows:

    {
        'username': '******',
        'message': 'Hello bot!',
        'vars': {
            'name': 'Aiden'
        }
    }

    The format that would be expected from this script is:

    {
        'status': 'ok',
        'reply': 'Hello, human!',
        'vars': {
            'name': 'Aiden'
        }
    }

    If the calling program sends an EOF signal at the end of their JSON data,
    this script will print its response and exit. To keep a session going,
    send the string '__END__' on a line by itself at the end of your message.
    The script will do the same after its response. The pipe can then be used
    again for further interactions.""")
        quit()

    # Given a directory?
    if len(remainder) == 0:
        print("Usage: rivescript [options] <directory>")
        print("Try rivescript --help")
        quit()
    root = remainder[0]

    # Make the bot.
    bot = RiveScript(
        debug=debug,
        strict=strict,
        depth=depth,
        utf8=utf8,
        log=log
    )
    bot.load_directory(root)
    bot.sort_replies()

    # Interactive mode?
    if with_json:
        # Read from standard input.
        buffer = ""
        stateful = False
        while True:
            line = ""
            try:
                line = _input()
            except EOFError:
                break

            # Look for the __END__ line.
            end = re.match(r'^__END__$', line)
            if end:
                # Process it.
                stateful = True  # This is a stateful session
                json_in(bot, buffer, stateful)
                buffer = ""
                continue
            else:
                buffer += line + "\n"

        # We got the EOF. If the session was stateful, just exit,
        # otherwise process what we just read.
        if stateful:
            quit()
        json_in(bot, buffer, stateful)
        quit()

    print("""RiveScript Interpreter (Python) -- Interactive Mode"
---------------------------------------------------"
rivescript version: %s
        Reply Root: %s

You are now chatting with the RiveScript bot. Type a message and press Return"
to send it. When finished, type '/quit' to exit the program."
Type '/help' for other options."
""" % (str(bot.VERSION()), root))

    while True:
        msg = _input("You> ")

        # Commands
        if msg == '/help':
            print("> Supported Commands:")
            print("> /help   - Displays this message.")
            print("> /quit   - Exit the program.")
        elif msg == '/quit':
            exit()
        else:
            reply = bot.reply("localuser", msg)
            print("Bot>", reply)
Esempio n. 11
0
#!/usr/bin/python3

# Python 3 example

from rivescript import RiveScript

rs = RiveScript()
rs.load_directory("./brain")
rs.sort_replies()

print("""This is a bare minimal example for how to write your own RiveScript bot!

For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.

example3.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.

Type /quit when you're done to exit this example.
""")

while True:
    msg = input("You> ")
    if msg == '/quit':
        quit()
    reply = rs.reply("localuser", msg)
    print("Bot>", reply)

# vim:expandtab
Esempio n. 12
0
# I.R.I.S.
# br4in

########## Imports #########
from rivescript import RiveScript
import time
from os import system
from speech_rec import get_command
from memory import read, write, get_reply

# Env variables
bot_name = 'AIris'

# Load RiveScript 
rs = RiveScript()
rs.load_directory("./brain")
rs.sort_replies()

def say(reply):

    output = system('say "{}" &'.format(reply))
 

def login():
    log_name = raw_input('Username: '******'{}_>'.format(log_name))
Esempio n. 13
0
class RiveBot(object):
	"""An example RiveScript bot using callbacks to manage user session data.

	This example assumes single user per RiveScript instance and as
	such it's suitable for use in stateless services (e.g. in web apps
	receiving webhooks). Just init, get reply and teardown. Of course,
	it will also work in RTM implementations with custom longer-lived 
	bot threads.

	Session state is persisted to a single JSON file. This wouldn't be 
	thread-safe in a concurrent environment (e.g. web server). In such
	case it would be recommended to subclass SessionStore and implement
	database persistence (preferably via one of great Python ORMs such
	as SQLAlchemy or peewee).
	"""
	def __init__(self, script_dir, user, ss, debug=False):
		self._user     = user
		self._redirect = None

		# init RiveScript
		self._rs = RiveScript(debug=debug)
		self._rs.load_directory(script_dir)
		self._rs.sort_replies()

		# restore session
		if isinstance(ss, SessionStore):
			self._ss = ss
		else:
			raise RuntimeError("RiveBot init error: provided session store object is not a SessionStore instance.")

		self._restore_session()

		# register event callbacks
		self._rs.on('topic',    self._topic_cb)
		self._rs.on('uservar',  self._uservar_cb)

	def _topic_cb(self, user, topic, redirect=None):
		"""Topic callback.

		This is a single-user-per-rive (stateless instance) scenario; in a multi-user
		scenario within a single thread, callback functions should delegate the 
		execution to proper user session objects.
		"""
		log.debug("Topic callback: user={}, topic={}, redirect={}".format(user, topic, redirect))
		self._session.set_topic(topic, redirect)

	def _uservar_cb(self, user, name, value):
		"""Topic callback. See comment for `_topic_cb()`"""
		log.debug("User variable callback: user={}, name={}, value={}".format(user, name, value))
		self._session.set_variable(name, value)		

	def _restore_session(self):
		self._session = self._ss.load(self._user)

		# set saved user variables
		for name, value in self._session.variables():
			self._rs.set_uservar(self._user, name, value)

		# set saved topic
		topic = self._session.get_topic()
		if topic:
			if '/' in topic:
				topic, self._redirect = topic.split('/')
			self._rs.set_topic(self._user, topic)

	def _save_session(self):
		self._ss.save(self._session)

	def run(self):
		log.info("RiveBot starting...")
		if self._redirect:
			# Repeat saved redirect so that the user gets the context
			# after session restart.
			redir_reply = self._rs.redirect(self._user, self._redirect)
			print("bot> Welcome back!")
			print("bot>", redir_reply)

		while True:
		    msg = raw_input("{}> ".format(self._user))
		    if msg == '/quit':
		        self.stop()
		        break
		    reply = self._rs.reply(self._user, msg)
		    print("bot>", reply)

	def stop(self):
		log.info("RiveBot shutting down...")
		print("\nbot> Bye.")
		self._save_session()
Esempio n. 14
0
from rivescript import RiveScript

bot = RiveScript(utf8=True)
bot.load_directory("./Body")
bot.sort_replies()


def reply(text: str) -> str:
    res = bot.reply("localuser", text)
    return res if res != "[ERR: No Reply Matched]" else ""


if __name__ == "__main__":
    while True:
        print(reply(input()))
Esempio n. 15
0
from flask import Flask, render_template, jsonify, request, Response
from rivescript import RiveScript
import pymongo
from pymongo import MongoClient
import json
from bson import json_util

cluster = MongoClient("mongodb+srv://Omar:[email protected]/Callcenter?retryWrites=true&w=majority")
db = cluster["callcenter1"]
collection = db["food orders"]

app = Flask(__name__, template_folder='templates')

# initialize RiveScript stuff
bot = RiveScript()
bot.load_directory(os.path.join(os.getcwd(), 'brain'))
bot.sort_replies()

# setup log file
file_handler = FileHandler('error_log.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(
    Formatter('%(asctime)s,%(msecs)d %(levelname)-5s [%(filename)s:%(lineno)d] %(message)s',
              datefmt='%d-%m-%Y:%H:%M:%S'
              )
)
app.logger.addHandler(file_handler)


@app.route('/')
Esempio n. 16
0
    def onMessage(self, messageProtocolEntity):
        #send receipt otherwise we keep receiving the same message over and over
	client = MongoClient()
	db = client.data
        if True:

            rs=RiveScript()
            rs.load_directory("./brain")
            rs.sort_replies()
		
            messageOut = ""
            #print(messageProtocolEntity.getType() )
            if messageProtocolEntity.getType() == "text":
                #self.output(message.getBody(), tag = "%s [%s]"%(message.getFrom(), formattedDate))
                """
                c = check()
                para = messageProtocolEntity.getBody()                
                messageOut =c.func(para)
                """
                messageOut = messageProtocolEntity.getBody()+' '
                print(messageOut)
            elif messageProtocolEntity.getType() == "media":
                #self.getMediaMessageBody(messageProtocolEntity)
                if self.onMediaMessage(messageProtocolEntity) == 1:
                	messageOut = "location code one "
		elif self.onMediaMessage(messageProtocolEntity) == 2:
                        messageOut = "image code one "
		elif self.onMediaMessage(messageProtocolEntity) == 3:
                        messageOut = "vcard recieved  "
		else:
			messageOut = "location code zero "
            else:
                messageOut = "Unknown message type %s " % messageProtocolEntity.getType()
                print(messageOut.toProtocolTreeNode())
            
            messageOut=formstring(messageOut)
	    print(messageOut)
            reply=rs.reply("localuser",messageOut)
            receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant())
	    result = db.session.find({"from":messageProtocolEntity.getFrom()})
	    if result.count() == 1:
	    	stime= datetime.datetime.now().hour*60+datetime.datetime.now().minute
		print(stime)
	   	if stime<=result[0]['expiry']:
		 	#Customer in citizen
			
			r = db.session.find({"from":messageProtocolEntity.getFrom()})
			qid = r[0]['qid']
			if messageProtocolEntity.getType() == "text":
				db.query.update({"_id":qid},{"$set":{"text":db.query.find({"_id":qid})[0]['text']+[messageProtocolEntity.getBody()]}})	
           		elif messageProtocolEntity.getMediaType() == "image":
				db.query.update({"_id":qid},{"$set":{"image":db.query.find({"_id":qid})[0]['image']+[messageProtocolEntity.url]}})
			
                        elif messageProtocolEntity.getMediaType() == "location":
                                db.query.update({"_id":qid},{"$set":{"location":db.query.find({"_id":qid})[0]['location']+[[messageProtocolEntity.getLatitude(), messageProtocolEntity.getLongitude()]]}})
			
                        elif messageProtocolEntity.getMediaType() == "vcard":
                                db.query.update({"_id":qid},{"$set":{"vcard":db.query.find({"_id":qid})[0]['vcard']+[messageProtocolEntity.getCardData()]}})
			else:
                                db.query.update({"_id":qid},{"$set":{"text":db.query.find({"_id":qid})[0]['text']+[messageProtocolEntity.getBody()]}})
			outgoingMessageProtocolEntity = TextMessageProtocolEntity(reply,
                		to = messageProtocolEntity.getFrom())
            		self.toLower(receipt)
            		self.toLower(outgoingMessageProtocolEntity)
		else:                                                                                                                                                                                         
                        r = db.session.find({"from":messageProtocolEntity.getFrom()})
                        qid = r[0]['qid']
			db.session.remove({"from":messageProtocolEntity.getFrom()})                                                                                                                                                                                    
                	outgoingMessageProtocolEntity = TextMessageProtocolEntity("Your complaint id:"+str(qid)+"\n\nYour session has been expired!!\nYou need to register again.",to = messageProtocolEntity.getFrom())                                                                                                                                             
                	self.toLower(receipt)                                                                                                                                                         
			self.toLower(outgoingMessageProtocolEntity)   
	    else:
		
		outgoingMessageProtocolEntity = TextMessageProtocolEntity("I need your location to register you",
                        to = messageProtocolEntity.getFrom())
                self.toLower(receipt)
                self.toLower(outgoingMessageProtocolEntity)
Esempio n. 17
0
from threading import Thread

from rivescript import RiveScript

bot = RiveScript(utf8=True)
bot.load_directory("./brain")
bot.sort_replies()


class Conversation(Thread):

    def __init__(self, chat):
        self.thread = Thread.__init__(self)
        self.daemon = True
        self.chat = chat

    def run(self, user, username, message):
        user = "******".format(user=user)
        line = ":%s PRIVMSG #jtv :/w %s %s" % (user, username, message)
        reply = bot.reply(username, message)
        if reply == "[ERR: No reply matched]":
            return
        return str(reply)
from config import Config
from rivescript import RiveScript
from bot_interface.bot_interface import BotInterface
from message_processor.message_processor import ExternalApiParser, MessageProcessor
from nyt_interface.nyt_interface import NytimesApi
from pymongo import MongoClient


config = ConfigParser.ConfigParser()
config.read("local_test_config.cfg")

bot = BotInterface(Config.FB_API_VERSION, config.get('SECRET', 'fb_access_token'))
nyt_api = NytimesApi(config.get('NYTIMES', 'nyt_key'))

rive = RiveScript()
rive.load_directory(
    os.path.join(os.path.dirname(__file__), "..", "rivescripts")
)
rive.sort_replies()

mongo = MongoClient()
mongo = mongo.app
external_api_parser = ExternalApiParser(config.get('WITAI', 'wit_key'),
                                        rive, bot, nyt_api, mongo)

Config = {'DEBUG': True, 'NYT_NUM_ARTICLES_RETURNED': 3}
msgproc = MessageProcessor(bot, external_api_parser, Config)
recipient_id = config.get('SECRET', 'fb_test_recipient_id')

Esempio n. 19
0
#! /usr/bin/python3

import json 
import requests
import time
import urllib

from rivescript import RiveScript

# Initialise the bot
bot = RiveScript()
bot.load_directory("./eg/brain")
bot.sort_replies()

TOKEN = "586907789:AAHuE1tPNHyU9MZnmYoBhD48N7bJFcYy4NQ"
URL = "https://api.telegram.org/bot{}/".format(TOKEN)

def get_url(url):
    response = requests.get(url)
    content = response.content.decode("utf8")
    return content


def get_json_from_url(url):
    content = get_url(url)
    js = json.loads(content)
    return js


def get_updates(offset=None):
    url = URL + "getUpdates?timeout=100"
Esempio n. 20
0
class AdmiralBot(object):
    """Chatbot instance for Admiral."""

    ###
    # Initialization and Configuration
    ###

    def __init__(self, debug=False, config="settings.yml",
                 defaults="defaults.yml", log_console=True):
        """Initialize the Admiral chatbot.

        Parameters:
        * debug:  Enable debug logging to the console.
        * config: The configuration file to use (default settings.yml)
        * defaults: The name of the default config file (defaults.yml)
        * log_console: Write logs to the console (STDOUT) as well as to the
                       log file on disk (default True).
        """

        # Configurable parameters.
        self.debug = debug
        self.config = config
        self.config_defaults = defaults

        # Internal state variables.
        self.running = False  # Whether we're up and running
        self.c = dict()       # App configuration
        self.bots = dict()    # Individual bot interfaces
        self.rs = None        # RiveScript brain

        # Load the bot's config.
        self.load_config()
        self.log = Logger(filename=self.c.logging.status,
                          console=log_console,
                          log_format=self.c.logging.format)
        if debug:
            self.log.set_level(logging.DEBUG)
            self.log.debug("Debug logging enabled.")

        # Run post-config initialization routines.
        self.setup()

    def load_config(self):
        """Load the configuration file from disk."""
        project_settings = YamlSettings(self.config_defaults, self.config,
                                        default_section="admiral")
        self.c = project_settings.get_settings()

    ###
    # Initial Setup Steps
    ###

    def setup(self):
        """Run the setup steps."""
        self.log.info("Welcome to Admiral.")

        # Initialize the RiveScript brain.
        self.reload_brain()

        # Scan through the interfaces and find active bots.
        self.log.info("Setting up interfaces...")
        for interface in self.c.interfaces:
            if not interface.enabled:
                continue

            if interface.id in self.bots:
                self.panic("Duplicate ID: you have two or more interfaces "
                    "that use the ID name `{}` in your bot settings. You "
                    "should pick a unique ID name for each interface!")
            self.bots[interface.id] = interface

            # Get the interface class.
            module = Interface.import_interface(interface.interface)
            self.bots[interface.id].inst = module(master=self)
            self.bots[interface.id].inst.setup(interface)

    def reload_brain(self):
        """(Re)load the RiveScript brain for the bot."""
        self.log.info("Loading RiveScript brain from {}".format(
            self.c.personality.replies
        ))

        self.rs = RiveScript(
            debug=self.c.debug.rivescript,
            utf8=True,
        )
        self.rs.load_directory(self.c.personality.replies)
        self.rs.sort_replies()

    ###
    # Start, stop, run commands.
    ###

    def start(self):
        """Start up all the bots."""
        if not self.running:
            for name, bot in self.bots.items():
                bot.inst.connect()
            self.running = True

    def run(self):
        """Start and run the bot's main loop."""
        self.start()
        while self.running:
            for name, bot in self.bots.items():
                bot.inst.do_one_loop()

    ###
    # Event handlers.
    ###

    def on_message(self, bot, username, remote_username, message):
        """Handle a message from an end user.

        Parameters:
        * bot: A reference to the interface that received the message.
        * username: A unique name for the end user, typically with the
                    interface name prefixed, like `SLACK-kirsle`
        * remote_username: The 'real' username, as the interface knows it.
        * message: The text of the user's message.
        """

        # Load this user's variables.
        self.load_uservars(username)

        # Get a reply for the user.
        reply = self.rs.reply(username, message)

        # Log the transaction.
        self.log_chat(username, message, reply)

        # Store the user's variables.
        self.save_uservars(username)

        # Send the response back.
        # TODO: handle queueing and delayed responses.
        bot.send_message(remote_username, reply)

    def log_chat(self, username, message, reply):
        """Log the chat transaction to disk."""

        # Each user gets their own log directory.
        sanitized = re.sub(r'[^A-Za-z0-9_\-@]+', '', username)
        outdir = os.path.join("logs", "chats", sanitized)
        outfile = os.path.join(outdir, "{}.log".format(sanitized))
        if not os.path.isdir(outdir):
            os.makedirs(outdir, mode=0o755)

        self.log.info("[{}] {}".format(username, message))
        self.log.info("[{}] {}".format(self.c.personality.name, reply))

        with open(outfile, "a", encoding="utf-8") as fh:
            today = datetime.datetime.today()
            ts = today.strftime(self.c.logging.date_format)
            fh.write("{today}\n"
                "[{username}] {message}\n"
                "[{bot}] {reply}\n\n".format(
                today=ts,
                username=username,
                message=message,
                bot=self.c.personality.name,
                reply=reply,
                ))

    def load_uservars(self, username):
        """Load a user's variables from disk."""
        if not os.path.isdir("users"):
            os.mkdir("users")

        sanitized = re.sub(r'[^A-Za-z0-9_\-@]+', '', username)
        filename = "users/{}.json".format(sanitized)
        if not os.path.isfile(filename):
            return

        with open(filename, "r", encoding="utf-8") as fh:
            data = fh.read()
            try:
                params = json.loads(data)
                print(params)
                for key, value in params.items():
                    if type(value) is str:
                        self.rs.set_uservar(username, key, value)
                        print("SET VAR:", username, key, value)
            except:
                pass

    def save_uservars(self, username):
        """Save a user's variables to disk."""
        if not os.path.isdir("users"):
            os.mkdir("users")

        sanitized = re.sub(r'[^A-Za-z0-9_\-@]+', '', username)
        filename = "users/{}.json".format(sanitized)

        with open(filename, "w", encoding="utf-8") as fh:
            fh.write(json.dumps(self.rs.get_uservars(username)))

    ###
    # Utility/Misc functions.
    ###

    def panic(self, error):
        """Exit with a fatal error message."""
        self.log.error(error)
        raise RuntimeError(error)
Esempio n. 21
0
from rivescript import RiveScript

bot = RiveScript()
bot.load_directory("D:\CurrentLooks\Projects\minor project\shopping-chatbot")
bot.sort_replies()


Esempio n. 22
0
import os
sys.path.append(os.path.join(
    os.path.dirname(__file__),
    "..", "..",
))
sys.path.append(os.path.join(
    os.path.dirname(__file__),
    "..", "..",
    "contrib", "redis",
))

from rivescript import RiveScript
from rivescript_redis import RedisSessionManager

bot = RiveScript(
    session_manager=RedisSessionManager(),
)
bot.load_directory("../brain")
bot.sort_replies()

print("""RiveScript Redis Session Storage Example

This example uses a Redis server to store user variables. For the sake of the
example, choose a username to store your variables under. You can re-run this
script with the same username (or a different one!) and verify that your
variables are kept around!

Type '/quit' to quit.
""")

username = input("What is your username? ").strip()
Esempio n. 23
0
from flask import request, g, make_response, jsonify
from rivescript import RiveScript
from . import Resource
from .. import schemas, config
import jwt
import os
import json
from googletrans import Translator
from wit import Wit
from .. import config
import datetime
# the access token for wit ai
access_token = "ABJWGG53QBEVM6UY6AUMBPNP42EQCXOZ"
client = Wit(access_token)
rs = RiveScript()
rs1 = RiveScript()

print(os.getcwd())


class Chatbot(Resource):
    def wit_response(self, text):
        message = "Analysing the code " + text["_text"] + " : "
        entities = list(text["entities"].keys())
        # print(entities)
        # if the intent cannot be detected, redirect to rs
        if "intent" not in entities:
            return None

        # using different ways to avoid mistranslate
def interactive_mode():
    """The built-in RiveScript Interactive Mode.

    This feature of RiveScript allows you to test and debug a chatbot in your
    terminal window. There are two ways to invoke this mode::

        # By running the Python RiveScript module directly:
        python rivescript eg/brain

        # By running the shell.py in the source distribution:
        python shell.py eg/brain

    The only required command line parameter is a filesystem path to a directory
    containing RiveScript source files (with the ``*.rive`` file extension).

    Additionally, it accepts command line flags.

    Parameters:
        --utf8: Enable UTF-8 mode.
        --json: Use JSON to communicate with the bot instead of plain text.
            See the JSON Mode documentation below for advanced details.
        --debug: Enable verbose debug logging.
        --log (str): The path to a text file you want the debug logging to
            be written to. This is to be used in conjunction with ``--debug``,
            for the case where you don't want your terminal window to be flooded
            with debug messages.
        --depth (int): Override the recursion depth limit (default ``50``).
        --nostrict: Disable strict syntax checking when parsing the RiveScript
            files. By default a syntax error raises an exception and will
            terminate the interactive mode.
        --help: Show the documentation of command line flags.
        path (str): The path to a directory containing ``.rive`` files.

    **JSON Mode**

    By invoking the interactive mode with the ``--json`` (or ``-j``) flag,
    the interactive mode will communicate with you via JSON messages. This
    can be used as a "bridge" to enable the use of RiveScript from another
    programming language that doesn't have its own native RiveScript
    implementation.

    For example, a program could open a shell pipe to the RiveScript interactive
    mode and send/receive JSON payloads to communicate with the bot.

    In JSON mode, you send a message to the bot in the following format::

        {
            "username": "******",
            "message": "str message",
            "vars": {
                "topic": "random",
                "name": "Alice"
            }
        }

    The ``username`` and ``message`` keys are required, and ``vars`` is a
    key/value object of all the variables about the user.

    After sending the JSON payload over standard input, you can either close the
    input file handle (send the EOF signal; or Ctrl-D in a terminal), or send
    the string ``__END__`` on a line of text by itself. This will cause the bot
    to parse your payload, get a reply for the message, and respond with a
    similar JSON payload::

        {
            "status": "ok",
            "reply": "str response",
            "vars": {
                "topic": "random",
                "name": "Alice"
            }
        }

    The ``vars`` structure in the response contains all of the key/value pairs
    the bot knows about the username you passed in. This will also contain a
    lot of internal data, such as the user's history and last matched trigger.

    To keep a stateful session, you should parse the ``vars`` returned by
    RiveScript and pass them in with your next request so that the bot can
    remember them for the next reply.

    If you closed the filehandle (Ctrl-D, EOF) after your input payload, the
    interactive mode will exit after giving the response. If, on the other
    hand, you sent the string ``__END__`` on a line by itself after your
    payload, the RiveScript interactive mode will do the same after its response
    is returned. This way, you can re-use the shell pipe to send and receive
    many messages over a single session.
    """

    parser = argparse.ArgumentParser(description="RiveScript interactive mode.")
    parser.add_argument("--debug", "-d",
        help="Enable debug logging within RiveScript.",
        action="store_true",
    )
    parser.add_argument("--json", "-j",
        help="Enable JSON mode. In this mode, you communicate with the bot by "
            "sending a JSON-encoded object with keys 'username', 'message' and "
            "'vars' (an object of user variables) over standard input, and "
            "then close the input (^D) or send the string '__END__' on a line "
            "by itself. The bot will respond with a similarly formatted JSON "
            "response over standard output, and then will either exit or send "
            "'__END__' depending on how you ended your input.",
        action="store_true",
    )
    parser.add_argument("--utf8", "-u",
        help="Enable UTF-8 mode (default is disabled)",
        action="store_true",
    )
    parser.add_argument("--log",
        help="The path to a log file to send debugging output to (when debug "
            "mode is enabled) instead of standard output.",
        type=text_type,
    )
    parser.add_argument("--nostrict",
        help="Disable strict mode (where syntax errors are fatal)",
        action="store_true",
    )
    parser.add_argument("--depth",
        help="Override the default recursion depth limit when fetching a reply "
            "(default 50)",
        type=int,
        default=50,
    )
    parser.add_argument("path",
        help="A directory containing RiveScript files (*.rive) to load.",
        type=text_type,
        # required=True,
    )
    args = parser.parse_args()

    # Make the bot.
    bot = RiveScript(
        debug=args.debug,
        strict=not args.nostrict,
        depth=args.depth,
        utf8=args.utf8,
        log=args.log
    )
    bot.load_directory(args.path)
    bot.sort_replies()

    # Interactive mode?
    if args.json:
        # Read from standard input.
        buffer = ""
        stateful = False
        while True:
            line = ""
            try:
                line = input()
            except EOFError:
                break

            # Look for the __END__ line.
            end = re.match(r'^__END__$', line)
            if end:
                # Process it.
                stateful = True  # This is a stateful session
                json_in(bot, buffer, stateful)
                buffer = ""
                continue
            else:
                buffer += line + "\n"

        # We got the EOF. If the session was stateful, just exit,
        # otherwise process what we just read.
        if stateful:
            quit()
        json_in(bot, buffer, stateful)
        quit()

    print(
        "      .   .       \n"
        "     .:...::      RiveScript Interpreter (Python)\n"
        "    .::   ::.     Library Version: v{version}\n"
        " ..:;;. ' .;;:..  \n"
        "    .  '''  .     Type '/quit' to quit.\n"
        "     :;,:,;:      Type '/help' for more options.\n"
        "     :     :      \n"
        "\n"
        "Using the RiveScript bot found in: {path}\n"
        "Type a message to the bot and press Return to send it.\n"
        .format(version=bot.VERSION(), path=args.path)
    )

    while True:
        msg = input("You> ")
        if PY2:
            # For Python 2 only: cast the message to Unicode.
            msg = msg.decode("utf-8")

        # Commands
        if msg == '/help':
            print("> Supported Commands:")
            print("> /help   - Displays this message.")
            print("> /quit   - Exit the program.")
        elif msg == '/quit':
            exit()
        else:
            reply = bot.reply("localuser", msg)
            print("Bot>", reply)
Esempio n. 25
0
class ChatBot:
    def __init__(self, replies, **botvars):
        self.logs = io.StringIO()
        self.brain = RiveScript(debug=True, log=self.logs)

        self.brain.load_directory(replies)
        self.brain.sort_replies()

        for key, value in botvars.items():
            self.brain.set_variable(key, str(value))

    def get_response(self, message, name, ID):
        if self.brain.get_uservar(ID,
                                  "name") is None or self.brain.get_uservar(
                                      ID, "name") == "undefined":
            self.brain.set_uservar(ID, "name", name)

        try:
            return self.brain.reply(ID, message, False), None
        except Exception as exc:
            return None, exc
Esempio n. 26
0
from rivescript import RiveScript

bot = RiveScript(utf8=True)
bot.load_directory("./replies")
bot.sort_replies()
Esempio n. 27
0
from rivescript import RiveScript

bot = RiveScript()
bot.load_directory("./")
bot.sort_replies()

while True:
    msg = input('You> ')
    if msg == '/quit':
        quit()

    reply = bot.reply("localuser", msg)
    print('Bot>', reply)
Esempio n. 28
0
 def new(self, code, **kwargs):
     """Make a bot and stream in the code."""
     self.rs = RiveScript(**kwargs)
     self.extend(code)
Esempio n. 29
0
    bot.set_variable("shop", None)
    return "Shclosed 😭"


def get_shop(rs, args):

    shop = bot.get_variable("shop")

    return "Shopen!!!" if shop else "Shclosed 😭"


celery = Celery('bot', broker=BROKER_URL)

# ==== rivescript bot setup ==== #

bot = RiveScript()
bot.load_directory("./bot/brain")
bot.sort_replies()

# ==== rivescript subroutines ==== #

# These functions can be used in the rivescript documents
bot.set_subroutine("set_jd", set_jd)
bot.set_subroutine("get_jd", get_jd)
bot.set_subroutine("set_shop", set_shop)
bot.set_subroutine("get_shop", get_shop)
# bot.set_subroutine("set_hashbrowns", functions.set_hashbrowns)
# bot.set_subroutine("get_hashbrowns", functions.get_hashbrowns)

# ==== message handling ==== #
Esempio n. 30
0
from rivescript import RiveScript

bot = RiveScript(utf8=True)
bot.load_directory('brain')
bot.sort_replies()

def reply(user, message):
    return bot.reply(user, message)

def logoutUser(user):
    try:
        bot.clear_uservars(user)
    except:
        print("User not found")
Esempio n. 31
0
import re
import requests
from config import CONFIG
from fbmq import Attachment, Template, QuickReply, NotificationType
from fbpage import page
from rivescript import RiveScript
from rivescript_redis import RedisSessionManager
from util import topicos
from util import elimina_tildes

parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)

USER_SEQ = {}

bot = RiveScript(session_manager=RedisSessionManager())
bot.load_directory("./rs")
bot.sort_replies()

page.greeting("LinguaBot+, tu mejor opción para el asesoramiento del idioma inglés.")

page.show_starting_button("START_PAYLOAD")


#MÉTODOS MODIFICADOS Y/O CREADOS


@page.callback(['START_PAYLOAD'])
def start_callback(payload, event):
    print("Let's start!")
Esempio n. 32
0
from rivescript import RiveScript
from gevent import pywsgi
from flask import Flask, render_template, request, redirect
from redis_storage import RedisSessionStorage
import redis

#import logging
import gevent.monkey
gevent.monkey.patch_all()


rs = RiveScript(session_manager=RedisSessionStorage(),)
rs.load_directory("/home/luky/line3v2/rivescript_microsite/")
rs.sort_replies()

redisconn = redis.StrictRedis()

if __name__==  "__main__":
    print "Rivescript is online"

    app = Flask(__name__)

    @app.route('/reply', methods=['POST'])
    def reply():
        content = request.get_json()
        print "reply:", content
        return rs.reply(content['msisdn'], content['ask'])

    print "starting gevent wsgi..."
    pywsgi.WSGIServer(('', 3003), app).serve_forever()
Esempio n. 33
0
#!/usr/bin/env python

from __future__ import unicode_literals, print_function, absolute_import
from six.moves import input
import sys
from rivescript import RiveScript
from redis_storage import RedisSessionStorage

bot = RiveScript(session_manager=RedisSessionStorage(), )
bot.load_directory("../brain")
bot.sort_replies()

print("""RiveScript Redis Session Storage Example

This example uses a Redis server to store user variables. For the sake of the
example, choose a username to store your variables under. You can re-run this
script with the same username (or a different one!) and verify that your
variables are kept around!

Type '/quit' to quit.
""")

username = input("What is your username? ").strip()
if len(username) == 0:
    print("You need to enter one! This script will exit now.")
    sys.exit(1)

while True:
    message = input("You> ").strip()
    if len(message) == 0:
        continue
Esempio n. 34
0
class Aplicacion(wx.Frame):
    def __init__(self):
        self.Ventana()
        self.Agente()
#        self.Respuesta("begin")
        
    def Agente(self):
        self.agente = RiveScript()
        self.agente.load_directory("./recursos")
        self.agente.sort_replies()
        self.lector = Dispatch("SAPI.SpVoice")
        if time.localtime().tm_hour < 12:
            self.agente.set_variable("time", "dia")
        else:
            if time.localtime().tm_hour < 18:
                self.agente.set_variable("time", "tarde")
            else:
                self.agente.set_variable("time", "noche")        

    def Ventana(self):
        wx.Frame.__init__(self, None, style= wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)
        self.panel = wx.Panel(self)
        self.texto = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_READONLY, size= (293,350), pos = (5,5))
        self.linea = wx.TextCtrl(self.panel, style=wx.TE_NO_VSCROLL | TE_PROCESS_ENTER, size= (200,50), pos = (10,365))      
        self.boton = wx.BitmapButton(self.panel, bitmap = wx.Bitmap("recursos\_enviar.png"), pos = (220, 360))
        self.etiqueta = wx.StaticText(self.panel, label = "Proyecto Inteligencia Artificial - ULA, A2012 ", pos = (5, 425))          
        self.Bind(wx.EVT_TEXT_ENTER, self.Pregunta, self.linea)
        self.Bind(wx.EVT_BUTTON, self.Pregunta, self.boton)     
        self.linea.SetFocus()
        self.SetTitle("Representante de Atencion al Cliente")
        self.SetSize((320,480))
        self.Centre()
        self.Show()
        
    def Pregunta(self, evento):
        self.texto.AppendText("   "+ str(self.linea.GetValue()).capitalize() + "\n")
        self.Respuesta(self.linea.GetValue().__str__()) 
                
    def Respuesta(self, texto):
        bot = self.agente.reply("rac", texto)
        self.linea.Clear()
        self.texto.AppendText(str(bot) + "\n")
        self.lector.Speak(bot)
Esempio n. 35
0
#!/usr/bin/python3

# Python 3 example

from rivescript import RiveScript

rs = RiveScript()
rs.load_directory("./eg/brain")
rs.sort_replies()

print(
    """This is a bare minimal example for how to write your own RiveScript bot!

For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.

example3.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.

Type /quit when you're done to exit this example.
""")

while True:
    msg = input("You> ")
    if msg == '/quit':
        quit()
    reply = rs.reply("localuser", msg)
    print("Bot>", reply)
Esempio n. 36
0
See the accompanying README.md for instructions."""

# Manipulate sys.path to be able to import rivescript from this git repo.
# Otherwise you'd have to `pip install rivescript`
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))

from flask import Flask, request, redirect
from rivescript import RiveScript
import twilio.twiml

# Set up the RiveScript bot. This loads the replies from "../brain", or,
# the "brain" folder in the "eg" folder of this git repository.
bot = RiveScript()
bot.load_directory(
    os.path.join(os.path.dirname(__file__), "..", "brain")
)
bot.sort_replies()

app = Flask(__name__)

@app.route("/twilio", methods=["GET", "POST"])
def hello_rivescript():
    """Receive an inbound SMS and send a reply from RiveScript."""

    from_number = request.values.get("From", "unknown")
    message     = request.values.get("Body")
    reply       = "(Internal error)"
Esempio n. 37
0
class RiveScript_Py_Tests(RiveScriptTestCase):
    def setUp(self):
        super().setUp()
        self.testdir = "__testdir__"
        os.mkdir(self.testdir)
        os.mkdir(os.path.join(self.testdir, "subdir"))

        def writeit(filename, contents):
            with open(os.path.join(self.testdir, filename), 'w') as f:
                f.write(contents + '\n')

        writeit("star.rive", """
            + *
            - star
        """)
        writeit(
            "sub.rive", """
            ! sub aya = a
            ! sub bee = b
        """)
        writeit(
            os.path.join("subdir", "cont.rive"), """
            + a
            - aa

            + b
            - bb
        """)

    def tearDown(self):
        shutil.rmtree(self.testdir)

    def test_improve_code_coverage_rivescript(self):
        from rivescript import __version__
        from rivescript import RiveScript
        self.assertEqual(RiveScript.VERSION(), __version__)

        self.rs = RiveScript()
        self.rs.load_directory(self.testdir)
        self.rs.sort_replies()
        self.reply("a", "aa")
        self.reply("aya", "aa")
        self.reply("bee", "bb")
        self.reply("cee", "star")

        self.rs = RiveScript()
        self.rs.load_file(os.path.join(self.testdir, "star.rive"))
        self.rs.load_file(os.path.join(self.testdir, "subdir", "cont.rive"))
        self.rs.sort_replies()
        self.reply("a", "aa")
        self.reply("aya", "star")

        self.new("""
            ! global g = gee
            ! var    v = vee

            + g
            - <env g>

            + v
            - <bot v>
        """)
        self.reply("g", "gee")
        self.reply("v", "vee")
        self.rs.set_global("g", None)
        self.rs.set_variable("v", None)
        self.reply("g", "undefined")
        self.reply("v", "undefined")

        self.new("""
            + *
            - star<set m=me><set u=you>
        """)
        self.reply("hi", "star")
        self.assertContains(self.rs.get_uservars(),
                            {self.username: {
                                'm': "me",
                                'u': "you"
                            }})
        self.rs.set_uservar("u2", "a", "aye")
        self.rs.clear_uservars(self.username)
        uv = self.rs.get_uservars()
        self.assertNotIn(self.username, uv)
        self.assertContains(uv, {"u2": {'a': "aye"}})

        self.new("""
            + u
            - <call>user</call>

            > object user python
                return rs.current_user()
            < object
        """)
        self.reply('u', self.username)
        self.assertEqual(self.rs.current_user(), None)
Esempio n. 38
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

from rivescript import RiveScript

rs = RiveScript(utf8 = True)
rs.load_directory("./cerveau")
rs.sort_replies()

while True:
    msg = raw_input("Vous > ")
    if msg == '/quit':
        quit()
    reply = u"{0}".format(rs.reply("localuser", msg))
    print(u"Aria > {0}".format(reply))

Esempio n. 39
0
    def test_improve_code_coverage_rivescript(self):
        from rivescript import __version__
        from rivescript import RiveScript
        self.assertEqual(RiveScript.VERSION(), __version__)

        self.rs = RiveScript()
        self.rs.load_directory(self.testdir)
        self.rs.sort_replies()
        self.reply("a", "aa")
        self.reply("aya", "aa")
        self.reply("bee", "bb")
        self.reply("cee", "star")

        self.rs = RiveScript()
        self.rs.load_file(os.path.join(self.testdir, "star.rive"))
        self.rs.load_file(os.path.join(self.testdir, "subdir", "cont.rive"))
        self.rs.sort_replies()
        self.reply("a", "aa")
        self.reply("aya", "star")

        self.new("""
            ! global g = gee
            ! var    v = vee

            + g
            - <env g>

            + v
            - <bot v>
        """)
        self.reply("g", "gee")
        self.reply("v", "vee")
        self.rs.set_global("g", None)
        self.rs.set_variable("v", None)
        self.reply("g", "undefined")
        self.reply("v", "undefined")

        self.new("""
            + *
            - star<set m=me><set u=you>
        """)
        self.reply("hi", "star")
        self.assertContains(self.rs.get_uservars(),
                            {self.username: {
                                'm': "me",
                                'u': "you"
                            }})
        self.rs.set_uservar("u2", "a", "aye")
        self.rs.clear_uservars(self.username)
        uv = self.rs.get_uservars()
        self.assertNotIn(self.username, uv)
        self.assertContains(uv, {"u2": {'a': "aye"}})

        self.new("""
            + u
            - <call>user</call>

            > object user python
                return rs.current_user()
            < object
        """)
        self.reply('u', self.username)
        self.assertEqual(self.rs.current_user(), None)
Esempio n. 40
0
 def __init__(self):
     self.bot = RiveScript()
     self.bot.load_directory("dialogues")
     self.bot.sort_replies()
Esempio n. 41
0
from rivescript import RiveScript
from bot_interface.bot_interface import BotInterface
from message_processor.message_processor import MessageProcessor, ExternalApiParser
from nyt_interface.nyt_interface import NytimesApi


app = Flask(__name__)
mongo = PyMongo(app)

app.config.from_object("config.DevelopmentConfig")
app.config.from_pyfile("local.cfg")

bot = BotInterface(app.config['FB_API_VERSION'], app.config['FB_ACCESS_TOKEN'])
nyt_api = NytimesApi(app.config['NYT_KEY'])

rive = RiveScript()
rive.load_directory(
    os.path.join(os.path.dirname(__file__), "message_processor", "rivescripts")
)
rive.sort_replies()

# external_api_parser = ExternalApiParser(app.config['WIT_KEY'], app.config['API_AI_KEY'], bot, nyt_api)
external_api_parser = ExternalApiParser(app.config['WIT_KEY'], rive, bot, nyt_api, mongo)
msgproc = MessageProcessor(bot, external_api_parser, app.config)


@app.route("/")
def index():
    return render_template('messenger.html')
    # return success(status=200, message="Hello world from climatechangebot!")
Esempio n. 42
0
class ImproveTestCoverage_Tests(RiveScriptTestCase):
    def test_improve_code_coverage_brain(self):
        self.new("""
            + *
            - star{topic=empty}

            > topic empty
            < topic
        """)
        self.reply("hi", "star")
        self.reply(
            "hi",
            "[ERR: No Reply Matched]")  # Should give an "empty topic" warning
        # Doesn't work!  self.reply("hi", "star")                            # and put us back in "random"

        self.new("""
            + *
            @ recurse most deeply
        """)
        self.reply("recurse", "[ERR: Deep recursion detected]")

        self.new("""    // Trying to hit a bunch of code here! :-)
            + *
            - {random}star star{/random}<set var=var>{weight=2}

            + <input> <reply1> <get var>
            * 1 <= 2 => <get var> <reply> <input1> <add num=2><mult num=3><sub num=2><div num=2><get num>
            - Nope!

            + upper lower
            - {uppercase}lower{/uppercase} {lowercase}UPPER{/lowercase}

            + blank random
            - {random} {/random}blank

        """)
        self.reply("hi", "star")
        self.reply("hi star var", "var star hi 2")
        self.reply("upper lower", "LOWER upper")
        self.reply("blank random", "blank")

        from rivescript import RiveScript
        from rivescript.exceptions import RepliesNotSortedError
        self.rs = RiveScript()
        self.rs.stream("""
            + *
            - star
        """)
        try:
            self.reply("hi", "Nope!")
        except RepliesNotSortedError:
            pass

    def test_improve_code_coverage_parser(self):
        self.new("""
            + *         // Inline comment
            - star      // Another comment
        """)
        self.reply("hi", "star")

        self.new("""
            ! global g = gee
            ! global debug = false
            ! global depth = 100
            ! global strict = true
            ! var v = vee
            ! array a = a b c
            ! sub g = a
            ! person v = b

            // Now get rid of most of these

            ! global g = <undef>
            ! var v = <undef>
            ! array a = <undef>
            ! sub g = <undef>
            ! person v = <undef>

            + g
            - g <env g>

            + v *
            - <person> <bot v>

            + *
            - star

            + @a arr
            - a arr

        """)
        self.reply("g gee", "star")
        self.reply("g", "g undefined")
        self.reply("v v", "v undefined")
        self.reply("a arr", "star")
Esempio n. 43
0
#!/usr/bin/python

from rivescript import RiveScript

rs = RiveScript()
rs.load_file("replies.rive")
rs.sort_replies()

print """This is a bare minimal example for how to write your own RiveScript bot!

For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.

example.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.

Type /quit when you're done to exit this example.
"""

while True:
    msg = raw_input("You> ")
    if msg == '/quit':
        quit()
    reply = rs.reply("localuser", msg)
    print "Bot>", reply

# vim:expandtab
Esempio n. 44
0
from matplotlib import pyplot
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression

#Load model
pkl_filename = "model/pickle_model.pkl"
with open(pkl_filename, 'rb') as file:
    model = pickle.load(file)

#Bot initialisation
file = os.path.dirname("__file__")
convo = os.path.join(file , 'convo')
bot = RiveScript()
bot.load_directory(convo)
bot.sort_replies()

while True:
	msg = str(input("You> "))
    
	if msg.find('gre') != -1:
		gre = [int(i) for i in msg.split() if i.isdigit()]
		print(gre)
	if msg.find('cgpa') != -1:
		cgpa = re.findall("\d+\.\d+", msg)
		cgpa = [float(i) for i in cgpa]   
		print(cgpa)
	if msg.find('toefl') != -1:
		toefl = [int(i) for i in msg.split() if i.isdigit()]
Esempio n. 45
0
from __future__ import print_function
from rivescript import RiveScript

rs = RiveScript()
rs.load_directory("./brain")
rs.sort_replies()


def lambda_handler(event, context):
    """ Route the incoming request based on type (LaunchRequest, IntentRequest,
    etc.) The JSON body of the request is provided in the event parameter.
    """
    print("event.session.application.applicationId=" +
          event['session']['application']['applicationId'])
    """
    Uncomment this if statement and populate with your skill's application ID to
    prevent someone else from configuring a skill that sends requests to this
    function.
    """
    # if (event['session']['application']['applicationId'] !=
    #         "amzn1.echo-sdk-ams.app.[unique-value-here]"):
    #     raise ValueError("Invalid Application ID")

    if event['session']['new']:
        on_session_started({'requestId': event['request']['requestId']},
                           event['session'])

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'], event['session'])
    elif event['request']['type'] == "IntentRequest":
        return on_intent(event['request'], event['session'])
Esempio n. 46
0
#!/usr/bin/python3

# Python 3 example

from rivescript import RiveScript
from server_functions import get_random_user_id
import json
import re
import socket
import spell_checker_italian as spell
rs = RiveScript(utf8=True)
rs.unicode_punctuation = re.compile(r'[,!?;:]')
rs.load_directory("./brain/")
rs.sort_replies()
#rs.set_uservar(get_current_user(),'id',get_current_user())


def set_user_var(user,var,value):
    """
    Imposta una variabile all'utente selezionato

    :param user : l'utente a cui assegnare la variabile
    :param var  : il nome della variabile
    :param value: il valore da assegnare
    """
    rs.set_uservar(user,var,value)

def set_metadata(value, user_id='localuser', name='metadata'):
    """
    Imposta la variabile 'metadata' all'utente selezionato
    Usato per gestire i diversi tipi di richieste HTTP
Esempio n. 47
0
from rivescript import RiveScript

def error_check(reply):
    if "[ERR:" in reply:
        return "I'm sorry, something went wrong."
    else:
        return reply

bot = RiveScript()
bot.load_directory("./Ania")
bot.sort_replies()

user = "******"

while True:
    msg = input('You> ')
    if msg == '/quit':
        quit()
    reply = bot.reply(user, msg)
    reply = error_check(reply)
    print("{}{}{}{}".format("\033[96m", "Ania> ", reply, "\033[0m"))


Esempio n. 48
0
#!/usr/bin/python

import re
from flask import Flask, jsonify, render_template, request

from rivescript import RiveScript
from rivescript import sentences

rs = RiveScript(debug=False, utf8=True)
rs.load_directory("./brain_zh")
rs.sort_replies()
rs.train()

app = Flask(__name__)

@app.route('/reply')
def get_reply():
    user = re.sub(ur'\W', '', request.remote_addr)
    line = request.args.get('l','')

    user = user.strip()
    res = []
    req = []
    if user != '':
        for msg in sentences(line):
            if  msg.strip() == '':
                continue
            reply = rs.reply(user, msg)
            req.append(msg)
            res.append(reply)
    return jsonify(req=req, reply=res)
Esempio n. 49
0
# create by fanfan on 2019/7/5 0005
#!/usr/bin/python3

# Python 3 example

from rivescript import RiveScript

rs = RiveScript(utf8=True, debug=True)
rs.load_directory("brain")
rs.sort_replies()

print(
    """This is a bare minimal example for how to write your own RiveScript bot!
For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.
example3.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.
Type /quit when you're done to exit this example.
""")

while True:
    msg = input("You> ")
    if msg == '/quit':
        quit()
    reply = rs.reply("localuser", msg)
    print("Bot>", reply)

# vim:expandtab
Esempio n. 50
0
from rivescript import RiveScript
from bot_interface.bot_interface import BotInterface
from message_processor.message_processor import MessageProcessor, ExternalApiParser
from nyt_interface.nyt_interface import NytimesApi

app = Flask(__name__)
mongo = PyMongo(app)

app.config.from_object("config.DevelopmentConfig")
app.config.from_pyfile("local.cfg")

bot = BotInterface(app.config['FB_API_VERSION'], app.config['FB_ACCESS_TOKEN'])
nyt_api = NytimesApi(app.config['NYT_KEY'])

rive = RiveScript()
rive.load_directory(
    os.path.join(os.path.dirname(__file__), "message_processor",
                 "rivescripts"))
rive.sort_replies()

# external_api_parser = ExternalApiParser(app.config['WIT_KEY'], app.config['API_AI_KEY'], bot, nyt_api)
external_api_parser = ExternalApiParser(app.config['WIT_KEY'], rive, bot,
                                        nyt_api, mongo)
msgproc = MessageProcessor(bot, external_api_parser, app.config)


@app.route("/")
def index():
    return render_template('messenger.html')
    # return success(status=200, message="Hello world from climatechangebot!")
Esempio n. 51
0
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage, SourceUser, SourceGroup,
    SourceRoom, TemplateSendMessage, ConfirmTemplate, MessageAction,
    ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URIAction,
    PostbackAction, DatetimePickerAction, CameraAction, CameraRollAction,
    LocationAction, CarouselTemplate, CarouselColumn, PostbackEvent,
    StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
    ImageMessage, VideoMessage, AudioMessage, FileMessage, UnfollowEvent,
    FollowEvent, JoinEvent, LeaveEvent, BeaconEvent, FlexSendMessage,
    BubbleContainer, ImageComponent, BoxComponent, TextComponent,
    SpacerComponent, IconComponent, ButtonComponent, SeparatorComponent,
    QuickReply, QuickReplyButton)
from linebot.exceptions import LineBotApiError

bot = RiveScript()
bot.load_file("data.rive")
bot.sort_replies()

app = Flask(__name__)

# create stemmer
factory = StemmerFactory()
stemmer = factory.create_stemmer()

# Developer Trial Mode
line_bot_api = LineBotApi('API_KEY')
handler = WebhookHandler('Channel')


def time_to_int(t):
Esempio n. 52
0
#!/usr/bin/python3

# Python 3 example

from pprint import pprint
from rivescript import RiveScript

rs = RiveScript(True)
rs.load_directory("./brain")
rs.sort_replies()

print("""This is a bare minimal example for how to write your own RiveScript bot!

For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.

example3.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.

Type /quit when you're done to exit this example.
""")

user = "******"

while True:
    msg = input("You> ")
    if msg == '/quit':
        quit()
    elif msg == '/dump':
Esempio n. 53
0
See the accompanying README.md for instructions."""

# Manipulate sys.path to be able to import rivescript from this git repo.
# Otherwise you'd have to `pip install rivescript`
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))

from flask import Flask, request, redirect
from rivescript import RiveScript
import twilio.twiml

# Set up the RiveScript bot. This loads the replies from "../brain", or,
# the "brain" folder in the "eg" folder of this git repository.
bot = RiveScript()
bot.load_directory(os.path.join(os.path.dirname(__file__), "..", "brain"))
bot.sort_replies()

app = Flask(__name__)


@app.route("/twilio", methods=["GET", "POST"])
def hello_rivescript():
    """Receive an inbound SMS and send a reply from RiveScript."""

    from_number = request.values.get("From", "unknown")
    message = request.values.get("Body")
    reply = "(Internal error)"

    # Get a reply from RiveScript.
Esempio n. 54
0
from rivescript import RiveScript

bot = RiveScript()
bot.load_directory("../public/brain/")
bot.load_directory("../public/brain/commands")
bot.sort_replies()

while True:
    msg = input("You> ")
    if msg == "/quit":
        quit()

    reply = bot.reply("localuser", msg)
    print("Bot>", reply)
Esempio n. 55
0
def interactive_mode():
    # Get command line options.
    options, remainder = [], []
    try:
        options, remainder = getopt.getopt(sys.argv[1:], 'dju', [
            'debug', 'json', 'utf8', 'log=', 'strict', 'nostrict', 'depth=',
            'help'
        ])
    except:
        print("Unrecognized options given, try " + sys.argv[0] + " --help")
        exit()

    # Handle the options.
    debug, depth, strict = False, 50, True
    with_json, help, log = False, False, None
    utf8 = False
    for opt in options:
        if opt[0] == '--debug' or opt[0] == '-d':
            debug = True
        elif opt[0] == '--strict':
            strict = True
        elif opt[0] == '--nostrict':
            strict = False
        elif opt[0] == '--json':
            with_json = True
        elif opt[0] == '--utf8' or opt[0] == '-u':
            utf8 = True
        elif opt[0] == '--help' or opt[0] == '-h':
            help = True
        elif opt[0] == '--depth':
            depth = int(opt[1])
        elif opt[0] == '--log':
            log = opt[1]

    # Help?
    if help:
        print("""Usage: rivescript [options] <directory>

Options:

    --debug, -d
        Enable debug mode.

    --log FILE
        Log debug output to a file (instead of the console). Use this instead
        of --debug.

    --json, -j
        Communicate using JSON. Useful for third party programs.

    --strict, --nostrict
        Enable or disable strict mode (enabled by default).

    --depth=50
        Set the recursion depth limit (default is 50).

    --help
        Display this help.

JSON Mode:

    In JSON mode, input and output is done using JSON data structures. The
    format for incoming JSON data is as follows:

    {
        'username': '******',
        'message': 'Hello bot!',
        'vars': {
            'name': 'Aiden'
        }
    }

    The format that would be expected from this script is:

    {
        'status': 'ok',
        'reply': 'Hello, human!',
        'vars': {
            'name': 'Aiden'
        }
    }

    If the calling program sends an EOF signal at the end of their JSON data,
    this script will print its response and exit. To keep a session going,
    send the string '__END__' on a line by itself at the end of your message.
    The script will do the same after its response. The pipe can then be used
    again for further interactions.""")
        quit()

    # Given a directory?
    if len(remainder) == 0:
        print("Usage: rivescript [options] <directory>")
        print("Try rivescript --help")
        quit()
    root = remainder[0]

    # Make the bot.
    bot = RiveScript(debug=debug,
                     strict=strict,
                     depth=depth,
                     utf8=utf8,
                     log=log)
    bot.load_directory(root)
    bot.sort_replies()

    # Interactive mode?
    if with_json:
        # Read from standard input.
        buffer = ""
        stateful = False
        while True:
            line = ""
            try:
                line = _input()
            except EOFError:
                break

            # Look for the __END__ line.
            end = re.match(r'^__END__$', line)
            if end:
                # Process it.
                stateful = True  # This is a stateful session
                json_in(bot, buffer, stateful)
                buffer = ""
                continue
            else:
                buffer += line + "\n"

        # We got the EOF. If the session was stateful, just exit,
        # otherwise process what we just read.
        if stateful:
            quit()
        json_in(bot, buffer, stateful)
        quit()

    print("""RiveScript Interpreter (Python) -- Interactive Mode"
---------------------------------------------------"
rivescript version: %s
        Reply Root: %s

You are now chatting with the RiveScript bot. Type a message and press Return"
to send it. When finished, type '/quit' to exit the program."
Type '/help' for other options."
""" % (str(bot.VERSION()), root))

    while True:
        msg = _input("You> ")

        # Commands
        if msg == '/help':
            print("> Supported Commands:")
            print("> /help   - Displays this message.")
            print("> /quit   - Exit the program.")
        elif msg == '/quit':
            exit()
        else:
            reply = bot.reply("localuser", msg)
            print("Bot>", reply)
Esempio n. 56
0
#!/usr/bin/env python

# Manipulate sys.path to be able to import rivescript from this local git
# repository.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))

from rivescript import RiveScript
import json

bot = RiveScript()
bot.load_file("example.rive")

dep = bot.deparse()
print(json.dumps(dep, indent=2))
Esempio n. 57
0
from rivescript import RiveScript

chatbot = RiveScript(utf8=True)

chatbot.prepare_brain_transplant()
chatbot.load_directory("application/bot_brain")
chatbot.sort_replies()


def Chat(user_msg):
    if user_msg == "":
        return "Please type a message"
    else:
        response = chatbot.reply("user", user_msg)
    if response:
        return response
    else:
        return "No reply, please try again"
Esempio n. 58
0
#!/usr/bin/python

from rivescript import RiveScript
from rivescript import sentences

#rs = RiveScript(log='log.example', utf8=True)
rs = RiveScript(debug=False, utf8=True)
rs.load_directory("./brain_zh")
rs.sort_replies()

rs.train()

print """This is a bare minimal example for how to write your own RiveScript bot!

For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.

example.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.

Type /quit when you're done to exit this example.
"""

while True:
    s = raw_input("You> ")
    if s == '/quit':
        quit()
    for msg, is_ask in sentences(s):
        if msg.strip() == '':
Esempio n. 59
0
if len(sys.argv) == 1:
    print("Usage: 01-gamemode.py <list of users to whitelist>")
    sys.exit(1)

debug = False
host, port, password = None, None, None

if sys.argv[1] == "--debug":
    debug = True
    host, port, password = sys.argv[2:5]
else:
    host, port, password = sys.argv[1:4]

# Initialize the RiveScript bot.
# http://www.rivescript.com/
bot = RiveScript()
bot.stream("""
+ (hello|hi|hey|yo)
- Hello, <id>!
- Hi there, <id>!
- Hey, <id>!

+ (how are you|how you doing)
- Great, you?
- Good.

+ (good|great|awesome)
- Awesome!

+ (not good|not great)
- Aww. =(