예제 #1
0
class TkinterGUIExample(tk.Tk):

    def __init__(self, *args, **kwargs):
        '''
        Create & set window variables.
        '''
        tk.Tk.__init__(self, *args, **kwargs)

        self.chatbot = ChatBot("No Output",
            storage_adapter="chatterbot.adapters.storage.JsonFileStorageAdapter",
            logic_adapters=[
                "chatterbot.adapters.logic.ClosestMatchAdapter"
            ],
            input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter",
            output_adapter="chatterbot.adapters.output.OutputFormatAdapter",
            database="../database.db"
        )

        self.title("Chatterbot")

        self.initialize()

    def initialize(self):
        '''
        Set window layout.
        '''
        self.grid()

        self.respond = ttk.Button(self, text='Get Response', command=self.get_response)
        self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3)

        self.usr_input = ttk.Entry(self, state='normal')
        self.usr_input.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)

        self.conversation_lbl = ttk.Label(self, anchor=tk.E, text='Conversation:')
        self.conversation_lbl.grid(column=0, row=1, sticky='nesw', padx=3, pady=3)

        self.conversation = ScrolledText.ScrolledText(self, state='disabled')
        self.conversation.grid(column=0, row=2, columnspan=2, sticky='nesw', padx=3, pady=3)

    def get_response(self):
        '''
        Get a response from the chatbot &
        display it.
        '''
        user_input = self.usr_input.get()
        self.usr_input.delete(0, tk.END)

        response = self.chatbot.get_response(user_input)

        self.conversation['state'] = 'normal'
        self.conversation.insert(
            tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(response.text) + "\n"
        )
        self.conversation['state'] = 'disabled'

        time.sleep(0.5)
예제 #2
0
# Bot cũ version 1 = Bot
# Bot version 2 = Kimi1.0
bot1 = ChatBot('KimiVN',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    logic_adapters=[
        'chatterbot.logic.MathematicalEvaluation',
        'chatterbot.logic.BestMatch',
        'chatterbot.logic.TimeLogicAdapterVN'
    ],
   database_uri='sqlite:///database.sqlite3')
trainer = ChatterBotCorpusTrainer(bot1)

training_vietnames = 'vietnamese/'

for file in os.listdir(training_vietnames):
    trainer.train(training_vietnames + file)
count = 0
while True:
    count += 1
    message = input('You: ')
    if message.strip() == 'Bye':
        print('Kimi : Bye')
        break
    else:
        reply = bot1.get_response(message)
        print('Kimi: ', reply)
        tts = gTTS(text=str(reply), lang='vi')
        tts.save("good"+str(count)+".mp3")
        playsound("good"+str(count)+".mp3")
        os.remove("good"+str(count)+".mp3")
예제 #3
0
import sys
sys.path.append("..")
from chatterbot.chatterbot import ChatBot

# Create a new chat bot named Charlie
chatbot = ChatBot("Charlie")

# Get a response to the input "How are you?"
response = chatbot.get_response("How are you?")

print(response)
예제 #4
0
import sys
sys.path.append("..")
from chatterbot.chatterbot import ChatBot
from settings import HIPCHAT
'''
See the HipChat api documentation for how to get a user access token.
https://developer.atlassian.com/hipchat/guide/hipchat-rest-api/api-access-tokens
'''

chatbot = ChatBot('HipChatBot',
                  hipchat_host=HIPCHAT['HOST'],
                  hipchat_room=HIPCHAT['ROOM'],
                  hipchat_access_token=HIPCHAT['ACCESS_TOKEN'],
                  input_adapter='chatterbot.adapters.input.HipChat',
                  output_adapter='chatterbot.adapters.output.HipChat',
                  trainer='chatterbot.trainers.ChatterBotCorpusTrainer')

chatbot.train('chatterbot.corpus.english')

# The following loop will execute each time the user enters input
while True:
    try:
        response = chatbot.get_response(None)

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break
예제 #5
0
from chatterbot.chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import UbuntuCorpusTrainer

chatbot = ChatBot('PseudoBot',
                  trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
                  storage_adapter="chatterbot.storage.MongoDatabaseAdapter",
                  logic_adapters=[{
                      'import_path':
                      'chatterbot.logic.BestMatch',
                      "response_selection_method":
                      "chatterbot.response_selection.get_first_response"
                  }, {
                      'import_path':
                      'chatterbot.logic.MathematicalEvaluation'
                  }])

print "Trained"
while (True):
    message = str(raw_input())
    print chatbot.get_response(message)
예제 #6
0
class PreciseChatter(object):
    """
    this class using ChatterBot to precise response on chat,
    this will train on statements corpus

    Huge Plan!!!!
    in precise chatter, I got an very interesting idea that Jarvis will
    write down every ask question from users, and at night, Jarvis will using Chatter Mind
    chat with Turing to improve himself!!
    """
    def __init__(self, lan='cn'):
        self.lan = lan
        self.base_dir = os.path.dirname(os.path.abspath(__file__))
        self._init_chatter()
        self._set_trainer()
        print('precise chatter init')

    def _init_chatter(self):
        self.chatbot = ChatBot(
            'Victoria',
            trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
            storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
            # logic_adapters=[
            #     "chatterbot.logic.MathematicalEvaluation",
            #     "chatterbot.logic.TimeLogicAdapter"
            # ],
            database='victoria',
        )

    def _load_train_corpus(self):
        train_corpus_path = os.path.join(self.base_dir, 'statements')
        train_list = []
        if os.path.exists(train_corpus_path):
            with open(train_corpus_path, 'r') as f:
                for l in f.readlines():
                    train_list.append(l.strip())
        if self.lan == 'cn':
            for i in dynamic_list_train_cn:
                train_list.append(i)
        else:
            for i in dynamic_list_train_cn:
                train_list.append(i)
        return train_list

    def _set_trainer(self):
        trainer = ChatterBotCorpusTrainer(self.chatbot)
        if self.lan == 'cn':
            trainer.train("chatterbot.corpus.chinese")
        else:
            trainer.train("chatterbot.corpus.english")
        list_trainer = ListTrainer(self.chatbot)
        list_trainer.train(self._load_train_corpus())
        # self.chatter.train(self._load_train_corpus())

    def _collect_talk(self, q, a):
        """
        this method will automatically collect PreciseChatter talk,
        and save into local, so that this will be an good corpus to train Jarvis
        :return: 
        """
        collected_file = os.path.join(self.base_dir, 'collected_talk')

        with open(collected_file, 'a+') as f:
            f.writelines(q + '&&&&&' + a + '\n')

    def get_response(self, from_talk):
        response = self.chatbot.get_response(from_talk)
        response = str(response)
        self._collect_talk(from_talk, response)
        # print('response from precise chat: ', response)
        return response

    def rival_turing(self):
        """
        this method will only work under LEARNING mode.

        in this method, Jarvis will using all collected questions chat with Turing, and collect
        the result in another talk file named Jarvis_vs_Turing.
        :return:
        """
        pass
예제 #7
0
    output_adapter="chatterbot.output.terminal.TerminalAdapter",
    database="../database.db"
)
popat.set_trainer(ListTrainer)
popat.train([
    "hi",
    "hello",
    "how are you",
    "why are you interested",
    "that is good to hear",
    "thank you",
    "you are welcome",
    "sorry",
    "its okay",
    "what is your name",
    "my name is popat",
])
print("Type something to begin...")

# The following loop will execute each time the user enters input
while True:
    try:
        # We pass None to this method because the parameter
        # is not used by the TerminalAdapter
        popat_input = popat.get_response(None)

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break

TWITTER = {
    "CONSUMER_KEY": "my-twitter-consumer-key",
    "CONSUMER_SECRET": "my-twitter-consumer-secret",
    "ACCESS_TOKEN": "my-access-token",
    "ACCESS_TOKEN_SECRET": "my-access-token-secret"
}
'''

chatbot = ChatBot("ChatterBot",
    storage_adapter="chatterbot.adapters.storage.TwitterAdapter",
    logic_adapters=[
        "chatterbot.adapters.logic.ClosestMatchAdapter"
    ],
    input_adapter="chatterbot.adapters.input.TerminalAdapter",
    output_adapter="chatterbot.adapters.output.TerminalAdapter",
    database="../database.db",
    twitter_consumer_key=TWITTER["CONSUMER_KEY"],
    twitter_consumer_secret=TWITTER["CONSUMER_SECRET"],
    twitter_access_token_key=TWITTER["ACCESS_TOKEN"],
    twitter_access_token_secret=TWITTER["ACCESS_TOKEN_SECRET"]
)

print("Type something to begin...")

while True:
    try:
        bot_input = chatbot.get_response(None)

    except (KeyboardInterrupt, EOFError, SystemExit):
        break
예제 #9
0
from settings import MAILGUN

'''
To use this example, create a new file called settings.py.
In settings.py define the following:

MAILGUN = {
    "CONSUMER_KEY": "my-mailgun-api-key",
    "API_ENDPOINT": "https://api.mailgun.net/v3/my-domain.com/messages"
}
'''

# Change these to match your own email configuration
FROM_EMAIL = "*****@*****.**"
RECIPIENTS = ["*****@*****.**"]

bot = ChatBot(
    "Mailgun Example Bot",
    mailgun_from_address=FROM_EMAIL,
    mailgun_api_key=MAILGUN["CONSUMER_KEY"],
    mailgun_api_endpoint=MAILGUN["API_ENDPOINT"],
    mailgun_recipients=RECIPIENTS,
    output_adapter="chatterbot.adapters.io.Mailgun",
    storage_adapter="chatterbot.adapters.storage.JsonFileStorageAdapter",
    database="../database.db"
)

# Send an example email to the address provided
response = bot.get_response("How are you?")
print("Check your inbox at ", RECIPIENTS)
import sys
sys.path.append("..")
from chatterbot.chatterbot import ChatBot
from chatterbot.adapters.logic.closest_meaning import ClosestMeaningAdapter
import logging
'''
This is an example showing how to train a chat bot using the
Ubuntu Corpus of conversation dialog.
'''

# Enable info level logging
logging.basicConfig(level=logging.INFO)

chatbot = ChatBot(
    'Example Bot',
    trainer='chatterbot.trainers.UbuntuCorpusTrainer',
    logic_adapters=[
        'chatterbot.adapters.logic.ClosestMeaningAdapter',
        'chatterbot.adapters.logic.SentimentAdapter'
    ],
)

# Start by training our bot with the Ubuntu corpus data
chatbot.train()

# Now let's get a response to a greeting
response = chatbot.get_response('What\'s the matter with you?')
print(response)
예제 #11
0
sys.path.append("..")
from chatterbot.chatterbot import ChatBot
from settings import MAILGUN
'''
To use this example, create a new file called settings.py.
In settings.py define the following:

MAILGUN = {
    "CONSUMER_KEY": "my-mailgun-api-key",
    "API_ENDPOINT": "https://api.mailgun.net/v3/my-domain.com/messages"
}
'''

# Change these to match your own email configuration
FROM_EMAIL = "*****@*****.**"
RECIPIENTS = ["*****@*****.**"]

bot = ChatBot(
    "Mailgun Example Bot",
    mailgun_from_address=FROM_EMAIL,
    mailgun_api_key=MAILGUN["CONSUMER_KEY"],
    mailgun_api_endpoint=MAILGUN["API_ENDPOINT"],
    mailgun_recipients=RECIPIENTS,
    output_adapter="chatterbot.adapters.io.Mailgun",
    storage_adapter="chatterbot.adapters.storage.JsonFileStorageAdapter",
    database="../database.db")

# Send an example email to the address provided
response = bot.get_response("How are you?")
print("Check your inbox at ", RECIPIENTS)
예제 #12
0
import sys
sys.path.append("..")
from chatterbot.chatterbot import ChatBot

chatbot = ChatBot('Ron Obvious',
                  trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
                  silence_performance_warning=True)

chatbot.train("chatterbot.corpus.english")
print(chatbot.get_response("Hello, how are you today?"))
예제 #13
0
In settings.py define the following:

TWITTER = {
    "CONSUMER_KEY": "my-twitter-consumer-key",
    "CONSUMER_SECRET": "my-twitter-consumer-secret",
    "ACCESS_TOKEN": "my-access-token",
    "ACCESS_TOKEN_SECRET": "my-access-token-secret"
}
'''

chatbot = ChatBot(
    "ChatterBot",
    storage_adapter="chatterbot.adapters.storage.TwitterAdapter",
    logic_adapters=["chatterbot.adapters.logic.ClosestMatchAdapter"],
    input_adapter="chatterbot.adapters.input.TerminalAdapter",
    output_adapter="chatterbot.adapters.output.TerminalAdapter",
    database="../database.db",
    twitter_consumer_key=TWITTER["CONSUMER_KEY"],
    twitter_consumer_secret=TWITTER["CONSUMER_SECRET"],
    twitter_access_token_key=TWITTER["ACCESS_TOKEN"],
    twitter_access_token_secret=TWITTER["ACCESS_TOKEN_SECRET"])

print("Type something to begin...")

while True:
    try:
        bot_input = chatbot.get_response(None)

    except (KeyboardInterrupt, EOFError, SystemExit):
        break
예제 #14
0
from chatterbot.trainers import ListTrainer

trainer = ListTrainer(bot)

trainer.train([
'(hi|hello|hey|holla|hola)',
'Hello',
'I need help| assistance',
'yes, how may i help?',
'have a question|another question',
'Yes, go ahead',
'what does profcess do ?',
'We help people ditch the script on the old ways of thinking and make the people-work connections that enable the growth which job seekers and employers are striving for. We are all about placing the right people in the right positions, not just filling a quota. We listen to both the client and candidates needs and ensure the entire process is a conversation, not just a transaction. We establish an ease in alliance between the company demand and skilled workforce through our well-defined research and tech based platform which mainly monitors the real time market trend and various diversified needs. The alliance is established by assisting the company with a skilled workforce and providing the opportunity to the talented candidates to update their employment status. It is not a success until both our client and candidate are happy. Let us help you find success, no matter which side of the process you are on.',
'What all services does prof-cess have?',
'to view the services that we provide, you can visit this link https://profcess.com/services',
'(who are prof-cess?| what makes profcess special?| why profcess?)',
'We at Prof-cess are the story of work with a team of supercharged, talented, and experienced people along with fresher who are highly ardent and can go to any extent to achieve the customary goal',
'Okay Thanks',
'No Problem!'
])

name=input("Enter Your Name: ")
print("Welcome to Prof-cess! I am a support bot, let me know how can I help you?")
while True:
    request=input(name+':')
    if request=='Bye' or request =='bye' or request =='be back later' or request == 'see you soon':
        print('Bot: Bye! Have a nice day.')
        break
    else:
        response=bot.get_response(request)
        print('Bot:',response)
예제 #15
0
class TkinterGUIExample(tk.Tk):
    def __init__(self, *args, **kwargs):
        '''
        Create & set window variables.
        '''
        tk.Tk.__init__(self, *args, **kwargs)

        self.chatbot = ChatBot(
            "No Output",
            storage_adapter=
            "chatterbot.adapters.storage.JsonFileStorageAdapter",
            logic_adapters=["chatterbot.adapters.logic.ClosestMatchAdapter"],
            input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter",
            output_adapter="chatterbot.adapters.output.OutputFormatAdapter",
            database="../database.db")

        self.title("Chatterbot")

        self.initialize()

    def initialize(self):
        '''
        Set window layout.
        '''
        self.grid()

        self.respond = ttk.Button(self,
                                  text='Get Response',
                                  command=self.get_response)
        self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3)

        self.usr_input = ttk.Entry(self, state='normal')
        self.usr_input.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)

        self.conversation_lbl = ttk.Label(self,
                                          anchor=tk.E,
                                          text='Conversation:')
        self.conversation_lbl.grid(column=0,
                                   row=1,
                                   sticky='nesw',
                                   padx=3,
                                   pady=3)

        self.conversation = ScrolledText.ScrolledText(self, state='disabled')
        self.conversation.grid(column=0,
                               row=2,
                               columnspan=2,
                               sticky='nesw',
                               padx=3,
                               pady=3)

    def get_response(self):
        '''
        Get a response from the chatbot &
        display it.
        '''
        user_input = self.usr_input.get()
        self.usr_input.delete(0, tk.END)

        response = self.chatbot.get_response(user_input)

        self.conversation['state'] = 'normal'
        self.conversation.insert(
            tk.END, "Human: " + user_input + "\n" + "ChatBot: " +
            str(response.text) + "\n")
        self.conversation['state'] = 'disabled'

        time.sleep(0.5)
예제 #16
0
class ChatterBot:

    # Init with the bot reference, and a reference to the settings var
    def __init__(self,
                 bot,
                 chatChannels=config.chatChannels,
                 prefix=config.prefix):
        self.bot = bot
        self.chatChannels = chatChannels
        self.prefix = prefix
        self.waitTime = 4  # Wait time in seconds
        self.botDir = 'botdata'
        self.botBrain = 'data.db'
        self.botList = []
        self.ownerName = discord.utils.find(lambda m: m.id == config.owner,
                                            self.bot.get_all_members())
        self.ownerGender = "Female"
        self.timeout = 3
        self.chatBot = ChatBot(
            "Catbot",
            storage_adapter="chatterbot.storage.SQLStorageAdapter",
            logic_adapters=[
                # "chatterbot.logic.MathematicalEvaluation",
                # "chatterbot.logic.TimeLogicAdapter",
                "chatterbot.logic.BestMatch"
            ],
            database="data.db",
            trainer='chatterbot.trainers.ChatterBotCorpusTrainer')

    async def onmessage(self, message):
        if message.channel.id not in self.chatChannels:
            return
        channel = message.channel

        if message.author.id != self.bot.user.id and not message.content.startswith(
                self.prefix):
            await self._chat(message.channel, message.channel.server,
                             message.content, message.author)

    @commands.command()
    async def export(self, ctx):
        if ctx.message.author.id != config.owner:
            return
        data = {'conversations': self.chatBot.trainer._generate_export_data()}
        ymlfile = 'this_data.yml'
        jsonfile = 'this_data.json'
        with open(jsonfile, 'w+', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False)
        with Json2yaml.safeopen(jsonfile, 'r') as json_file:
            with Json2yaml.safeopen(ymlfile, 'w+') as yaml_file:
                Json2yaml.convert(json_file, yaml_file)

    @commands.command(hidden=True, pass_context=True)
    async def train(self, ctx, data_file_or_path: str):
        if ctx.message.author.id != config.owner:
            return
        self.chatBot.train(data_file_or_path)

    @commands.command(name='channel')
    async def add_chat_channel(self, ctx, channelID: int = None):
        if ctx.message.author.id != config.owner:
            return

        def chkedit(m):
            return (m.author.id != self.bot.user.id and m.content.isdigit())

        if channelID is None:
            chanq = await self.bot.say('Enter a channel ID for Chatterbot...')
            channelID = await self.bot.wait_for_message(60, check=chkedit)
        if not channelID:
            return
        chans = self.chatChannels
        chans.append('%d' % channelID)
        configfile = helpers.load_file('cogs/utils/config.py')
        configfile.remove(configfile[5])
        configfile.append('chatChannels = {}'.format(chans))
        helpers.write_file('cogs/utils/config.py', configfile)
        dataIO = DataIO()
        file = 'data/settings.json'

        data = {
            "token": config.token,
            "cogs": config.cogs,
            "prefix": config.prefix,
            "owner": config.owner,
            "volume": config.volume,
            "chatChannels": config.chatChannels,
            "servers": {}
        }
        dataIO.save_json(filename=file, data=data)

    async def onready(
        self
    ):  #that won't happen. Train it with cogs/utils/blob.py in terminal.
        if not os.path.isfile(self.botBrain):
            self.chatBot.train('botdata.data')

    @commands.command(pass_context=True)
    async def chat(self, ctx, *, message=None):
        """Chats with the bot."""
        await self._chat(ctx.message.channel, ctx.message.channel.server,
                         message, ctx.message.author)

    async def _chat(self, channel, server, message, author):
        if message == None:
            return
        blob = TextBlob(message)
        if author.nick is None:
            author = author.name
        else:
            author = author.nick
        for word in blob.words:
            if word.lower() in GREETING_KWDS:
                mess = choice(GREETING_KWDS) + ', {}!'.format(author)
                msg = self.chatBot.input.process_input_statement(mess)
            else:
                msg = self.chatBot.get_response(message)
        if not msg:
            return
        await self.bot.send_message(channel, msg)
예제 #17
0
import sys
sys.path.append("..")
from chatterbot.chatterbot import ChatBot

chatbot = ChatBot(
        'Ron Obvious',
        trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
        silence_performance_warning=True
        )

chatbot.train("chatterbot.corpus.english")
print(chatbot.get_response("Hello, how are you today?"))
예제 #18
0
        'import_path': 'chatterbot.logic.BestMatch',
        'maximum_similarity_threshold': 0.7
    }],
    database_uri='mongodb://localhost:27017/chatterbot-database7',
    preprocessors=['chatterbot.preprocessors.clean_whitespace'],
    filters=['filters.get_recent_repeated_responses'],
    read_only=True)

trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')

while True:
    message = input('You :')

    if message.strip() != 'Bye':
        reply = chatbot.get_response(message)
        text = message.strip()
        print('confidence = ', reply.confidence)

        if reply.confidence >= 0.6:
            print('ChatBot :', reply)
        elif reply.confidence < 0.6:
            #d = 'https://www.google.com/search?client=safari&rls=en&q={0}&ie=UTF-8&oe=UTF-8'.format(message)
            #webbrowser.open_new_tab(d)
            print('Sorry!  no response')
    elif message.strip() == 'Bye':
        print('ChatBot : Bye')
        break
''' 
while True:
    try:
예제 #19
0
import sys
sys.path.append("..")
from chatterbot.chatterbot import ChatBot

bot = ChatBot(
    "Math & Time Bot",
    logic_adapters=[
        "chatterbot.adapters.logic.MathematicalEvaluation",
        "chatterbot.adapters.logic.TimeLogicAdapter"
    ],
    input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter",
    output_adapter="chatterbot.adapters.output.OutputFormatAdapter")

# Print an example of getting one math based response
response = bot.get_response("What is 4 + 9?")
print(response)

# Print an example of getting one time based response
response = bot.get_response("What time is it?")
print(response)