예제 #1
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
예제 #2
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)
예제 #3
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?"))
예제 #4
0
        "chatterbot.logic.mathematical_evaluation.MathematicalEvaluation",
        "chatterbot.logic.time_adapter.TimeLogicAdapter",
        "chatterbot.logic.best_match.BestMatch"
    ],
    input_adapter="chatterbot.input.terminal.TerminalAdapter",
    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)
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)
from chatterbot.chatterbot import ChatBot  # import the chatbot
from pep8 import readlines
from chatterbot.trainers import ListTrainer  # method to train the chatbot

bot = ChatBot('Test')  # create the chatbot

conv = open('chat.txt', 'r').readlines()

bot.set_trainer(ListTrainer)  # set the trainers
bot.train(conv)  # train the bot

while True:
    request = input('You: ')
    response = bot.get_response(request)
    print('Bot: ', response)
예제 #7
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?"))