def setUp(self):
        super().setUp()

        self.trainer = ChatterBotCorpusTrainer(
            self.chatbot,
            show_training_progress=False
        )
class ChatterBotCorpusTrainingTestCase(ChatterBotTestCase):
    """
    Test case for training with data from the ChatterBot Corpus.

    Note: This class has a mirror tests/training_tests/
    """

    def setUp(self):
        super().setUp()

        self.trainer = ChatterBotCorpusTrainer(
            self.chatbot,
            show_training_progress=False
        )

    def tearDown(self):
        super().tearDown()
        self.chatbot.storage.drop()

    def test_train_with_english_greeting_corpus(self):
        self.trainer.train('chatterbot.corpus.english.greetings')

        results = list(self.chatbot.storage.filter(text='Hello'))

        self.assertGreater(len(results), 1)

    def test_train_with_english_greeting_corpus_tags(self):
        self.trainer.train('chatterbot.corpus.english.greetings')

        results = list(self.chatbot.storage.filter(text='Hello'))

        self.assertGreater(len(results), 1)
        statement = results[0]
        self.assertEqual(['greetings'], statement.get_tags())

    def test_train_with_multiple_corpora(self):
        self.trainer.train(
            'chatterbot.corpus.english.greetings',
            'chatterbot.corpus.english.conversations',
        )
        results = list(self.chatbot.storage.filter(text='Hello'))

        self.assertGreater(len(results), 1)

    def test_train_with_english_corpus(self):
        self.trainer.train('chatterbot.corpus.english')
        results = list(self.chatbot.storage.filter(text='Hello'))

        self.assertGreater(len(results), 1)
Beispiel #3
0
# ChatterBot Initialization
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

bot = ChatBot('ttd', database_uri=f'sqlite:///data/db/chatbot.sqlite3')

trainer = ChatterBotCorpusTrainer(bot)

trainer.train(f'./data/training/default')
Beispiel #4
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
'''
This is an example showing how to train a chat bot using the
ChatterBot Corpus of conversation dialog.
'''

chatbot = ChatBot('Mahmoud',
                  logic_adapters=[
                      'chatterbot.logic.BestMatch',
                      'chatterbot.logic.MathematicalEvaluation'
                  ],
                  database_uri='sqlite:///database.sqlite3')

# Start by training our bot with the ChatterBot corpus data
trainer = ChatterBotCorpusTrainer(chatbot)

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

# Now let's get a response to a greeting
while True:
    humen = input("You: ")
    response = chatbot.get_response(humen)
    print("Bot: ", response)
Beispiel #5
0
import speech_recognition as sr  # import the library
import pyaudio
import pyttsx3
import inflect
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
import serial

chatterbot = ChatBot("Training Example")
trainer = ChatterBotCorpusTrainer(chatterbot)
trainer.train("chatterbot.corpus.english.my_chatpot")

serialPort = serial.Serial(port="COM3",
                           baudrate=9600,
                           bytesize=8,
                           timeout=2,
                           stopbits=serial.STOPBITS_ONE)

neg_list = ["EXIT", "NOT", "DON'T"]

d = {
    "BED UP": 1,
    "BED DOWN": 2,
    "LIGHT ON": 3,
    "LIGHT OFF": 4,
    "FAN ON": 5,
    "FAN OFF": 6,
    "MOOD RED": 7,
    "MOOD GREEN": 8,
    "BLINDS OPEN": 9,
    "BLINDS CLOSE": 10,
from chatterbot import ChatBot #import the chatbot
from chatterbot.trainers import ChatterBotCorpusTrainer
import os
import subprocess
import pyttsx3
import pyaudio
import webbrowser
import datetime
import speech_recognition as sr
from PIL import ImageTk, Image, ImageOps

engine = pyttsx3.init()
engine.setProperty('rate' ,150)

bot= ChatBot('Bot')
trainer = ChatterBotCorpusTrainer(bot)

corpus_path = 'C:/chatterbot-corpus-master/chatterbot_corpus/data/english/'

for file in os.listdir(corpus_path):
        trainer.train(corpus_path + file)
engine.say("Hi I am your personal assistant")
engine.runAndWait()
def convert():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source, duration = 0.5)
        #print('Speak Anything:')
        audio = r.listen(source)
        reply = "Got Nothing"
        try:
Beispiel #7
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from videoTotext import *

app = Flask(__name__)

app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/EasyDoubt'

english_bot = ChatBot(
    'Chatterbot',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    database_uri='postgresql://*****:*****@localhost/EasyDoubt')

db = SQLAlchemy(app)
trainer = ChatterBotCorpusTrainer(english_bot)

trainer.train('./Knowledge/c.yml', './Knowledge/os.yml',
              './Knowledge/english.yml', './Knowledge/sort.yml')

# config for video content


class Thumbnail(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    href = db.Column(db.String(80), unique=True, nullable=False)
    image = db.Column(db.String(80), unique=True, nullable=False)
    head = db.Column(db.String(50), unique=True, nullable=False)
    desc = db.Column(db.String(200), unique=True, nullable=False)

    def __init__(self, head, image, desc):
Beispiel #8
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer

chatbot = ChatBot("deepThought",
                  storage_adapter="chatterbot.storage.SQLStorageAdapter",
                  database="/data/database.db")

trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train("chatterbot.corpus.english", "chatterbot.corpus.chinese")


def talk(msg):
    return chatbot.get_response(msg)


def train(input, res):
    trainer = ListTrainer(chatbot)
    trainer.train([input, res])
    return "ok"
Beispiel #9
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

trained_bot = ChatBot(name='Jenga Score Bot',
                      read_only=True,
                      logic_adapters=[
                          'chatterbot.logic.BestMatch',
                          'chatterbot.logic.MathematicalEvaluation'
                      ])
trainer = ChatterBotCorpusTrainer(trained_bot)

#Training the bot English and the additional credit score corpus
#'chatterbot.corpus.english.creditscore

training_data = ['chatterbot.corpus.english']

#This section is commented out because the bot has already been trained
#for item in(training_data):
#   trainer.train(item)
#train bot on credit scores
trainer = ListTrainer(trained_bot)
trainer.train([
    'What is Credit Reference Bureau ?',
    ' A credit reference bureau (CRB) is a firm that collects information from financial institutions and provides consumer credit information on individual consumers for a variety of uses. CRB’s hold credit data shared by financial institutions and facilitates credit lending to financial institutions.',
    'What can you do to improve your credit history?',
    'Check Your Credit Report and Fix errors ,Pay your bills on time and Setup Payment Reminders',
    'Other tips?',
    '1. Don’t close old credit accounts. 2. Avoid negative listings. 3. Maintain an active credit account. 4. Build a credit history. 5. Create a budget. 6. Click the PataScore Button and get the other tips'
])
Beispiel #10
0
#!/usr/bin/env python

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('Terminal',
                  storage_adapter='chatterbot.storage.SQLStorageAdapter',
                  trainer='chatterbot.trainers.ListTrainer',
                  database_uri='sqlite:///database.db')

trainer = ChatterBotCorpusTrainer(chatbot)

trainer.export_for_training('./export.yml')
Beispiel #11
0
def answer(message):
    bot = ChatBot('Bot')
    trainer = ChatterBotCorpusTrainer(bot)
    trainer.train('greetings.yml')
    reply = bot.get_response(message)
    return reply
Beispiel #12
0
    'What would you like to have sir?'
]

# Each item in the list becomes
# a possible response to it’s predecessor in the list.

training_lists = [greetings, maths, random_talks, online_business]

# Allows a chat bot to be trained using
# a list of strings where the list represents a conversation.
list_trainer = ListTrainer(bot)
for x in training_lists:
    list_trainer.train(x)

# Train using chatterbot corpus
bot_trainer = ChatterBotCorpusTrainer(bot)
bot_trainer.train("chatterbot.corpus.english.greetings",
                  "chatterbot.corpus.english")

# Search algorithms
# naive Bayesian classification algorithms
# to determine if an input statement meets a particular set of criteria

#----------------------------------------------------------------------------------------------------


@app.route("/get_response_from_bot", methods=['POST', 'GET'])
def get_response_from_bot():
    user_msg = ""
    if request.method == 'POST':
        user_msg = request.form['input']
Beispiel #13
0
def train_bot_corpus():

    trainer = ChatterBotCorpusTrainer(bot)
    trainer.train('chatterbot.corpus.english')
Beispiel #14
0
		{
			'import_path':'chatterbot.logic.BestMatch',
			'default_response':'I am sorry, but I do not understand.',
			'maximum_similarity_threshold':0.90
		},
		{
			'import_path':'chatterbot.logic.SpecificResponseAdapter',
			'input_text':'Como te llamas?',
			'output_text':'Mi nombre es ChatBot!'
		}
	],
	database_uri='sqlite:///database.sqlite3'
	) #create the bot


trainer = ChatterBotCorpusTrainer(bot)
trainer.train(
	"chatterbot.corpus.spanish.greetings",
	"chatterbot.corpus.spanish.conversations"
)



@app.route('/chat')
def chat():
	return render_template('chat.html',bot_response="Hola, My nombre es ChatBot, ¿Como puedo ayudarte?")

@app.route('/process',methods=['POST'])
def process():
	user_input=request.form['user_input']
Beispiel #15
0
    input=tf.constant(responses_en),
    context=tf.constant(response_contexts_en))['outputs']

# Variables containing answers and context
responses_ar = answer_ar
response_contexts_ar = context_ar

# Create response embeddings
response_encodings_ar = module.signatures['response_encoder'](
    input=tf.constant(responses_ar),
    context=tf.constant(response_contexts_ar))['outputs']

chatbot = ChatBot('Amal')

# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(chatbot)

# Train the chatbot based on the english corpus
#trainer.train("chatterbot.corpus.english")
trainer.train("chatterbot.corpus.english.covid19")

app = Flask(__name__)
#CORS(app)
#Cross Origin
#cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
CORS(app,
     headers=(
         'x-requested-with',
         'content-type',
         'accept',
         'origin',
Beispiel #16
0
        "statement_comparison_function":
        'chatterbot.comparisons.SynsetDistance',
        'default_response': 'Ainda não sei responder essa frase.',
        'maximum_similarity_threshold': 0.95
    }],
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    database_uri='postgresql://*****:*****@localhost/sarah_chatbot',
)

# local - dev config
# database_uri='postgresql://*****:*****@localhost/sarah_chatbot',)

# --------------------------------------

# Corpus Trainer
corpus_trainer = ChatterBotCorpusTrainer(bot)

# use this line and comment out the complete pack if
# you feel like doing some quick testing

corpus_trainer.train('data/greetings.yml')
"""
corpus_trainer.train('data/botprofile.yml', 'data/compliment.yml', 'data/context_free_br.yml', 'data/conversations.yml',
                     'data/emotion.yml', 'data/food.yml', 'data/games.yml', 'data/health.yml',
                     'data/literature.yml', 'data/money.yml', 'data/movies.yml', 'data/psychology.yml',
                     'data/sports.yml', 'data/suggestions.yml')
"""

# --------------------------------------
# Conversation Loop - terminal only
Beispiel #17
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

'''
This is an example showing how to create an export file from
an existing chat bot that can then be used to train other bots.
'''

chatbot = ChatBot('Export Example Bot')

# First, lets train our bot with some data
trainer = ChatterBotCorpusTrainer(chatbot)

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

# Now we can export the data to a file
trainer.export_for_training('./my_export.json')
Beispiel #18
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

#instance of the class “ChatBot.”
my_bot = ChatBot(name='PyBot',
                 read_only=True,
                 logic_adapters=[
                     'chatterbot.logic.MathematicalEvaluation',
                     'chatterbot.logic.BestMatch',
                     'chatterbot.logic.TimeLogicAdapter'
                 ])
corpus_trainer = ChatterBotCorpusTrainer(my_bot)
corpus_trainer.train('chatterbot.corpus.english')

#specifying the lists of strings that can be later used to train your Python chatbot
small_talk = [
    'Hi', 'Hello', 'I need your assistance regarding my order',
    'Please, Provide me with your order id', 'I have a complaint.',
    'Please elaborate, your concern',
    'How long it will take to receive an order ?',
    'An order takes 3-5 Business days to get delivered.', 'Okay Thanks',
    'No Problem! Have a Good Day!'
]
math_talk_1 = [
    'pythagorean theorem', 'A squared plus b squared equals c squared.'
]
math_talk_2 = ['Law of cosines', 'c**2 = a**2 + b**2 -2 * a * b * cos(gamma)']

#train the bot by writing an instance of “ListTrainer” and supplying it with a list of strings
list_trainer = ListTrainer(my_bot)
Beispiel #19
0
from django.shortcuts import render
from django.http import HttpResponse
import json
from django.views.generic.base import TemplateView
from django.views.generic import View
from django.http import JsonResponse
from chatterbot import ChatBot
from gpi import settings
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot(**settings.CHATTERBOT)

trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train(*settings.CHATTERBOT['training_data'])


# Create your views here.
class ChatterBotApiView(View):
    """
    Provide an API endpoint to interact with ChatterBot.
    """

    chatterbot = ChatBot(**settings.CHATTERBOT)

    def post(self, request, *args, **kwargs):
        """
        Return a response to the statement in the posted data.

        * The JSON data should contain a 'text' attribute.
        """
        input_data = json.loads(request.body.decode('UTF-8'))
Beispiel #20
0
#         #     'import_path': 'chatterbot.logic.SpecificResponseAdapter',
#         #     'input_text': 'Who Created you?',
#         #     'output_text': 'God is my creator'
#         # }
#     ]
# )

# for _file in os.listdir('files'):
#     convs = open('files/'+ _file, "r").readlines()

#*******List trainer************
#bot_trainer = ListTrainer(bot)
#bot_trainer.train(convs)

#********Corpus TRainer******************
bot_trainer_con = ChatterBotCorpusTrainer(bot)
bot_trainer_con.train(
    'chatterbot.corpus.english'
    #"chatterbot.corpus.english.greetings",
    #"chatterbot.corpus.english.conversations"exit
)

name = (input('Eva : Tell me your name?\n'))
print(
    "Hi", name,
    "This is EVA, your personal digital assistant for anything and everything related to Prodapt. Ask me anything"
)

#sp.speech.say('Hi. This is trisha, your personal digital assistant for anything and everything related to Prodapt. Ask me anything')
#sp.speech.runAndWait()
Beispiel #21
0
def setup():
    chatbot = ChatBot('Bot')
    trainer = ChatterBotCorpusTrainer(chatbot)

    for file in os.listdir('./data/'):
        trainer.train('./data/' + file)
Beispiel #22
0
#Chatboy Main
#Currently deprecated and not being worked on, I'm experimenting elsewhere

#Import Discord.py for Discord things
import discord
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
#Import os for handling misc stuff
import os

#Create ChatBoy
chatbot = ChatBot('ChatBoy')

#Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(chatbot)
#Train the chatbot based on the english corpus
try:
    trainer.train("chatterbot.corpus.english")
except:
    print("Error training with English corpus, skipping")
#Train the chatbot based on past experience
try:
    trainer.train(os.path.dirname(os.path.abspath(__file__))+"/ChatBoy_training_export.json")
except FileNotFoundError:
    print("ChatBoy Training Export not found, skipping")

#Initialise Discord client
print("ChatBoy loading...")
client = discord.Client()

#Discord bot stuff
Beispiel #23
0
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
import nltk
import os
port = int(os.environ.get("PORT", 5000))
app = Flask(__name__)

englishBot = ChatBot("Chatterbot",
                     storage_adapter="chatterbot.storage.SQLStorageAdapter")
trainer = ChatterBotCorpusTrainer(englishBot)
trainer.train("chatterbot.corpus.english")  #train the chatter bot for english


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    return str(englishBot.get_response(userText))


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=port)
Beispiel #24
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

bot = ChatBot("BotBoy")

corpus_trainer = ChatterBotCorpusTrainer(bot)
corpus_trainer.train("chatterbot.corpus.english")

convo = [
    'hello', 'hi!!', 'how are you?!', 'i am fine', 'what is your name?',
    "my name is BotBoy", 'who created you', 'I was created by akshay'
    'lets dance!', 'ok!!'
]

trainer = ListTrainer(bot)
trainer.train(convo)

while True:
    question = input()

    if question == 'x':
        break
    answer = bot.get_response(question)
    print(answer)
Beispiel #25
0
    'BestMatch',
    'LogicAdapter',
    'UnitConversion',
    'TimeLogicAdapter',
    'MathematicalEvaluation',
    'SpecificResponseAdapter',
]

_adapters = []
for adapter in adapters:
    _adapters.append({'import_path', f'chatterbot.logic.{adapter}'})

cb = ChatBot(
    'Bot',
    logic_adapers=_adapters,   
    # storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
    # database_uri=DB_URL or config.get('database', 'mongo_url'),
)

trainer = ChatterBotCorpusTrainer(cb)

trainer.train(
    # Uncomment each line to train from chatterbot's corpus
    # 'chatterbot.corpus.french',
    'chatterbot.corpus.english',
    # 'chatterbot.corpus.portuguese',
    # 'chatterbot.corpus.german',
    # 'chatterbot.corpus.spanish',
    # 'chatterbot.corpus.italian'
)
Beispiel #26
0
class Kenzer(object):

    #initializations
    def __init__(self):
        print(BLUE + "KENZER[3.07] by ARPSyndicate" + CLEAR)
        print(YELLOW + "automated web assets enumeration & scanning" + CLEAR)
        self.client = zulip.Client(email=_BotMail, site=_Site, api_key=_APIKey)
        self.upload = False
        if _subscribe == "True":
            self.subscribe()
            print(YELLOW + "[*] subscribed all streams" + CLEAR)
        if _uploads == "True":
            self.upload = True
            print(YELLOW + "[*] enabled uploads" + CLEAR)
        print(YELLOW + "[*] training chatterbot" + CLEAR)
        self.chatbot = ChatBot("Kenzer")
        self.trainer = ChatterBotCorpusTrainer(self.chatbot)
        time.sleep(3)
        self.trainer.train("chatterbot.corpus.english")
        time.sleep(3)
        self.modules = [
            "monitor", "subenum", "webenum", "headenum", "socscan", "conenum",
            "dnsenum", "portenum", "asnenum", "urlenum", "favscan", "cscan",
            "idscan", "subscan", "cvescan", "vulnscan", "portscan", "parascan",
            "endscan", "buckscan", "vizscan", "enum", "scan", "recon", "hunt",
            "remlog", "sync"
        ]
        print(YELLOW + "[*] KENZER is online" + CLEAR)
        print(YELLOW +
              "[*] {0} modules up & running".format(len(self.modules)) + CLEAR)

    #subscribes to all streams
    def subscribe(self):
        try:
            json = self.client.get_streams()["streams"]
            streams = [{"name": stream["name"]} for stream in json]
            self.client.add_subscriptions(streams)
        except:
            print(RED + "[!] an exception occurred.... retrying...." + CLEAR)
            self.subscribe()

    #manual
    def man(self):
        message = "**KENZER[3.07]**\n"
        message += "**KENZER modules**\n"
        message += "  `subenum` - enumerates subdomains\n"
        message += "  `portenum` - enumerates open ports\n"
        message += "  `webenum` - enumerates webservers\n"
        message += "  `headenum` - enumerates additional info from webservers\n"
        message += "  `conenum` - enumerates hidden files & directories\n"
        message += "  `dnsenum` - enumerates dns records\n"
        message += "  `asnenum` - enumerates asn\n"
        message += "  `urlenum` - enumerates urls\n"
        message += "  `subscan` - hunts for subdomain takeovers\n"
        message += "  `socscan` - scans search engines & webpages for social media accounts\n"
        message += "  `cscan` - scan with customized templates\n"
        message += "  `cvescan` - hunts for CVEs\n"
        message += "  `vulnscan` - hunts for other common vulnerabilites\n"
        message += "  `portscan` - scans open ports\n"
        message += "  `parascan` - hunts for vulnerable parameters\n"
        message += "  `endscan` - hunts for vulnerable endpoints\n"
        message += "  `buckscan` - hunts for unreferenced aws s3 buckets\n"
        message += "  `favscan` - fingerprints webservers using favicon\n"
        message += "  `idscan` - identifies applications running on webservers\n"
        message += "  `vizscan` - screenshots applications running on webservers\n"
        message += "  `enum` - runs all enumerator modules\n"
        message += "  `scan` - runs all scanner modules\n"
        message += "  `recon` - runs all modules\n"
        message += "  `hunt` - runs your custom workflow\n"
        message += "  `remlog` - removes log files\n"
        message += "  `upload` - switches upload functionality\n"
        message += "  `sync` - synchronizes the local kenzerdb with github\n"
        message += "  `upgrade` - upgrades kenzer to latest version\n"
        message += "  `monitor` - monitors ct logs for new subdomains\n"
        message += "  `monitor normalize` - normalizes the enumerations from ct logs\n"
        message += "  `monitor db` - monitors ct logs for kenzerdb's domains.txt\n"
        message += "`kenzer <module>` - runs a specific modules\n"
        message += "`kenzer man` - shows this manual\n"
        message += "or you can just interact with chatterbot\n"
        self.sendMessage(message)
        return

    #sends messages
    def sendMessage(self, message):
        time.sleep(2)
        if self.type == "private":
            self.client.send_message({
                "type": self.type,
                "to": self.sender_email,
                "content": message
            })
        else:
            self.client.send_message({
                "type": self.type,
                "subject": self.subject,
                "to": self.display_recipient,
                "content": message
            })
        time.sleep(3)
        return

    #uploads output
    def uploader(self, domain, raw):
        global _kenzerdb
        global _Site
        org = domain
        data = _kenzerdb + org + "/" + raw
        print(data)
        if (os.path.exists(data) == False):
            return
        with open(data, 'rb') as fp:
            uploaded = self.client.call_endpoint(
                'user_uploads',
                method='POST',
                files=[fp],
            )
        self.sendMessage("{0}/{1} : {3}{2}".format(org, raw, uploaded['uri'],
                                                   _Site))
        print(uploaded)

    #monitors ct logs
    def monitor(self):
        self.sendMessage("[monitoring - #({0})]".format(len(self.content) - 2))
        self.monitor = monitor.Monitor(_kenzerdb, " ".join(self.content[2:]))
        self.monitor.certex()
        return

    #monitors ct logs for kenzerdb's domains.txt
    def monitor_kenzerdb(self):
        domfile = _kenzerdb + "../domains.txt"
        with open(domfile) as f:
            line = len(f.readlines())
        self.sendMessage("[monitoring - #({0})]".format(line))
        self.monitor = monitor.Monitor(_kenzerdb)
        self.monitor.certex()
        return

    #normalizes enumerations from ct logs
    def normalize(self):
        self.monitor = monitor.Monitor(_kenzerdb, " ".join(self.content[2:]))
        self.monitor.normalize()
        self.sendMessage("[normalized - #({0})]".format(len(self.content) - 2))
        return

    #enumerates subdomains
    def subenum(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[subenum - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer, _github)
            message = self.enum.subenum()
            self.sendMessage("[subenum - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "subenum.kenz"
                self.uploader(self.content[i], file)
        return

    #probes web servers from enumerated subdomains
    def webenum(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[webenum - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer)
            message = self.enum.webenum()
            self.sendMessage("[webenum - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "webenum.kenz"
                self.uploader(self.content[i], file)
        return

    #enumerates additional info from webservers
    def headenum(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[headenum - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer)
            message = self.enum.headenum()
            self.sendMessage("[headenum - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "headenum.kenz"
                self.uploader(self.content[i], file)
        return

    #enumerates dns records
    def dnsenum(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[dnsenum - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer)
            message = self.enum.dnsenum()
            self.sendMessage("[dnsenum - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "dnsenum.kenz"
                self.uploader(self.content[i], file)
        return

    #enumerates hidden files & directories
    def conenum(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[conenum - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer)
            message = self.enum.conenum()
            self.sendMessage("[conenum - #({0}/{1}) ~] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            if self.upload:
                file = "conenum.kenz"
                self.uploader(self.content[i], file)
        return

    #enumerates asn for enumerated subdomains
    def asnenum(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[asnenum - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer)
            message = self.enum.asnenum()
            self.sendMessage("[asnenum - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "asnenum.kenz"
                self.uploader(self.content[i], file)
        return

    #enumerates open ports
    def portenum(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[portenum - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer)
            message = self.enum.portenum()
            self.sendMessage("[portenum - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "portenum.kenz"
                self.uploader(self.content[i], file)
        return

    #enumerates urls
    def urlenum(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[urlenum - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer, _github)
            message = self.enum.urlenum()
            self.sendMessage("[urlenum - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "urlenum.kenz"
                self.uploader(self.content[i], file)
        return

    #hunts for subdomain takeovers
    def subscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[subscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.subscan()
            self.sendMessage("[subscan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "subscan.kenz"
                self.uploader(self.content[i], file)

        return

    #scans search engines & webpages for social media accounts
    def socscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[socscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.socscan()
            self.sendMessage("[socscan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "socscan.kenz"
                self.uploader(self.content[i], file)

        return

    #scans with customized templates
    def cscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[cscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.cscan()
            self.sendMessage("[cscan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "cscan.kenz"
                self.uploader(self.content[i], file)

        return

    #hunts for CVEs
    def cvescan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[cvescan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.cvescan()
            self.sendMessage("[cvescan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "cvescan.kenz"
                self.uploader(self.content[i], file)

        return

    #hunts for other common vulnerabilities
    def vulnscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[vulnscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.vulnscan()
            self.sendMessage("[vulnscan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "vulnscan.kenz"
                self.uploader(self.content[i], file)

        return

    #scans open ports
    def portscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[portscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.portscan()
            self.sendMessage("[portscan - #({0}/{1}) ~] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            if self.upload:
                file = "portscan.kenz"
                self.uploader(self.content[i], file)
        return

    #hunts for vulnerable parameters
    def parascan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[parascan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.parascan()
            self.sendMessage("[parascan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "parascan.kenz"
                self.uploader(self.content[i], file)

        return

    #hunts for vulnerable endpoints
    def endscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[endscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.endscan()
            self.sendMessage("[endscan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "endscan.kenz"
                self.uploader(self.content[i], file)

        return

    #hunts for subdomain takeovers
    def buckscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[buckscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.buckscan()
            self.sendMessage("[buckscan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "buckscan.kenz"
                self.uploader(self.content[i], file)

        return

    #fingerprints servers using favicons
    def favscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[favscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.favscan()
            self.sendMessage("[favscan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "favscan.kenz"
                self.uploader(self.content[i], file)
        return

    #identifies applications running on webservers
    def idscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[idscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.idscan()
            self.sendMessage("[idscan - #({0}/{1}) - {2}] {3}".format(
                i - 1,
                len(self.content) - 2, message, self.content[i].lower()))
            if self.upload:
                file = "idscan.kenz"
                self.uploader(self.content[i], file)
        return

    #screenshots applications running on webservers
    def vizscan(self):
        for i in range(2, len(self.content)):
            if (validators.domain(self.content[i].lower()) != True
                    and self.content[i].lower() != "monitor"):
                self.sendMessage("[invalid] {0}".format(
                    self.content[i].lower()))
                continue
            self.sendMessage("[vizscan - #({0}/{1})] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            self.scan = scanner.Scanner(self.content[i].lower(), _kenzerdb,
                                        _kenzer)
            message = self.scan.vizscan()
            self.sendMessage("[vizscan - #({0}/{1}) ~] {2}".format(
                i - 1,
                len(self.content) - 2, self.content[i].lower()))
            if self.upload:
                for file in os.listdir(_kenzerdb + self.content[i].lower() +
                                       "/aquatone/screenshots/"):

                    self.uploader(self.content[i],
                                  "aquatone/screenshots/" + file)
        return

    #runs all enumeration modules
    def enum(self):
        self.subenum()
        self.portenum()
        self.webenum()
        self.headenum()
        self.dnsenum()
        self.conenum()
        self.asnenum()
        #experimental ones
        #self.urlenum()
        return

    #runs all scanning modules
    def scan(self):
        self.favscan()
        self.socscan()
        self.idscan()
        self.subscan()
        self.portscan()
        self.buckscan()
        self.cvescan()
        self.vulnscan()
        self.vizscan()
        #experimental ones
        #self.parascan()
        #self.endscan()
        return

    #define your custom workflow
    def hunt(self):
        self.subenum()
        self.portenum()
        self.webenum()
        self.headenum()
        self.dnsenum()
        self.conenum()
        self.socscan()
        self.subscan()
        self.idscan()
        self.favscan()
        self.buckscan()
        self.portscan()
        self.cvescan()
        self.vulnscan()
        self.asnenum()
        self.vizscan()
        #experimental ones
        #self.urlenum()
        #self.parascan()
        #self.endscan()
        #self.remlog()
        return

    #runs all modules
    def recon(self):
        self.enum()
        self.scan()
        return

    #synchronizes the local kenzerdb with github
    def sync(self):
        os.system(
            "cd {0} && git remote set-url origin https://{1}@github.com/{2}/{3}.git && git pull && git add . && git commit -m updated && git push"
            .format(_kenzerdb, _github, _user, _repo))
        self.sendMessage("[synced]")
        return

    #upgrades kenzer to latest version
    def upgrade(self):
        os.system("bash update.sh")
        self.sendMessage("[upgraded]")
        return

    #removes old log files
    def remlog(self):
        for i in range(2, len(self.content)):
            self.enum = enumerator.Enumerator(self.content[i].lower(),
                                              _kenzerdb, _kenzer)
            message = self.enum.remlog()
            self.sendMessage(message)
        return

    #controls
    def process(self, text):
        self.content = text["content"].split()
        self.sender_email = text["sender_email"]
        self.type = text["type"]
        self.display_recipient = text['display_recipient']
        self.subject = text['subject']
        content = self.content
        print(content)
        if self.sender_email == _BotMail:
            return
        try:
            if len(content) > 1 and content[0].lower() == "@**{0}**".format(
                    _BotMail.split('@')[0].replace("-bot", "")):
                if content[1].lower() == "man":
                    if len(content) == 2:
                        self.man()
                    else:
                        message = "excuse me???"
                        self.sendMessage(message)
                elif content[1].lower() == "monitor":
                    if content[2].lower() == "normalize":
                        self.normalize()
                    elif content[2].lower() == "db":
                        self.monitor_kenzerdb()
                    else:
                        self.monitor()
                elif content[1].lower() == "subenum":
                    self.subenum()
                elif content[1].lower() == "webenum":
                    self.webenum()
                elif content[1].lower() == "socscan":
                    self.socscan()
                elif content[1].lower() == "headenum":
                    self.headenum()
                elif content[1].lower() == "asnenum":
                    self.asnenum()
                elif content[1].lower() == "dnsenum":
                    self.dnsenum()
                elif content[1].lower() == "conenum":
                    self.conenum()
                elif content[1].lower() == "favscan":
                    self.favscan()
                elif content[1].lower() == "portenum":
                    self.portenum()
                elif content[1].lower() == "urlenum":
                    self.urlenum()
                elif content[1].lower() == "subscan":
                    self.subscan()
                elif content[1].lower() == "cscan":
                    self.cscan()
                elif content[1].lower() == "cvescan":
                    self.cvescan()
                elif content[1].lower() == "vulnscan":
                    self.vulnscan()
                elif content[1].lower() == "portscan":
                    self.portscan()
                elif content[1].lower() == "parascan":
                    self.parascan()
                elif content[1].lower() == "endscan":
                    self.endscan()
                elif content[1].lower() == "idscan":
                    self.idscan()
                elif content[1].lower() == "vizscan":
                    self.vizscan()
                elif content[1].lower() == "buckscan":
                    self.buckscan()
                elif content[1].lower() == "enum":
                    self.enum()
                elif content[1].lower() == "scan":
                    self.scan()
                elif content[1].lower() == "hunt":
                    self.hunt()
                elif content[1].lower() == "recon":
                    self.recon()
                elif content[1].lower() == "remlog":
                    self.remlog()
                elif content[1].lower() == "sync":
                    self.sync()
                elif content[1].lower() == "upgrade":
                    self.upgrade()
                elif content[1].lower() == "upload":
                    self.upload = not self.upload
                    self.sendMessage("upload: " + str(self.upload))
                else:
                    message = self.chatbot.get_response(' '.join(self.content))
                    message = message.serialize()['text']
                    self.sendMessage(message)
        except Exception as exception:
            self.sendMessage("[exception] {0}:{1}".format(
                type(exception).__name__, str(exception)))
            print(exception.__class__.__name__ + ": " + str(exception))
        return
Beispiel #27
0
              filters=["chatterbot.filters.RepetitiveResponseFilter"],
              preprocessors=['chatterbot.preprocessors.clean_whitespace'],
              logic_adapter=[{
                  'import_path':
                  "chatterbot.logic.BestMatch",
                  'statement_comparison_function':
                  "chatterbot.comparison.levenshtein_distance",
                  'response_selection_method':
                  "chatterbot.response_selection.get_first_response"
              }, {
                  'import_path': "chatterbot.logic.LowConfidenceAdapter",
                  'threshold': 0.65,
                  'default_response': 'Sorry I do not know that'
              }])

trainer = ChatterBotCorpusTrainer(bot)
trainer.train("data/data.yml")


@app.route("/")
def index():
    return render_template("index.html")  #send context to html


@app.route("/get")
def get_bot_response():
    userText = request.args.get(
        "msg")  #get data from input,we write js  to index.html
    return str(bot.get_response(userText))

Beispiel #28
0
                'import_path': 'chatterbot.logic.BestMatch',
                'default_response':
                'sorry, Iam donot understand what you are saying',
                'maximum_similarity_threshold': 0.90
            }
        ])
except:
    print("compiled sucessfully")

    training_data_for_mybot = open(
        'training_data_for_mychatbot/Ques and Anes.txt').read().splitlines()

    trainer = ListTrainer(my_chatbot)
    trainer.train(training_data_for_mybot)

    trainer = ChatterBotCorpusTrainer(my_chatbot)
    trainer.train("chatterbot.corpus.english")


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/get")
def get_bot_response():
    user_request = request.args.get('msg')
    return str(my_chatbot.get_response(user_request))


if __name__ == "__main__":
travel_listtrainer = ListTrainer(chatbot)

for convo in convos:
    travel_listtrainer.train(convo)

for ty in thanks:
    travel_listtrainer.train(ty)

for hi in hellos:
    travel_listtrainer.train(hi)

for bye in byes:
    travel_listtrainer.train(bye)

# Next we will need to train in with the corpus.
travel_corpustrainer = ChatterBotCorpusTrainer(chatbot)

travel_corpustrainer.train("chatterbot.corpus.english")


def depart_date_matcher(tokenized):
    matcher = Matcher(nlp.vocab)
    matcher.add("DateFromFinder", None, [{
        'LOWER': 'leave'
    }, {
        'LOWER': 'on'
    }, {
        "ENT_TYPE": "DATE"
    }], [{
        'LOWER': 'leaving'
    }, {
# -*- coding: utf-8 -*-

#----- importing libraries -----#
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

#----- Instantiating Chatbot named Lire -----#
bot = ChatBot('Lire')

#----- Instantiating training to the bot -----#
trainer = ChatterBotCorpusTrainer(bot)

#----- setting conversation to the bot -----#
trainer.train("chatterbot.corpus.portuguese",
              "chatterbot.corpus.portuguese.games")
# "chatterbot.corpus.Portuguese.greetings")

#----- progress looping -----#
while True:
    response = bot.get_response(input("Você: "))
    print("Lire: ", response)

# while True:
#     #----- Defining condition based on degree of confidence -----#
#     try:
#         response = bot.get_response(input("Você: "))
#         if float(response.confidence) > 0.1:
#             print("Lire: ", response)
#         else:
#             print("Eu não entendi :(")
#     except(KeyboardInterrupt, EOFError, SystemExit):
Beispiel #31
0
from flask import request
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

bot = ChatBot("Kona")
#
trainer = ChatterBotCorpusTrainer(bot)
trainer = ListTrainer(bot)

trainer.train(["Hi", "Hello"])
trainer.train(["How are you?", "Good."])

#
trainer.train("chatterbot.corpus.english")


def getChat(request):
    chatMessage = str(request.args.get('chat'))
    botResponse = str(bot.get_response(chatMessage))
    if botResponse:
        response, code = {"message": botResponse}, 200
    else:
        response, code = {"message": "No Response"}, 400
    return response, code
Beispiel #32
0
# chatbot = ChatBot(
#     'Buddy',
#     storage_adapter='chatterbot.storage.SQLStorageAdapter',
#     database_uri='sqlite:///database.sqlite3'
# )

# Create object of ChatBot class with Logic Adapter
bot = ChatBot(
    'Buddy',
    # logic_adapters=[
    #     'chatterbot.logic.BestMatch',
    #     'chatterbot.logic.TimeLogicAdapter'],
)

# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(bot)

# Train the chatbot based on the english corpus
# trainer.train("chatterbot.corpus.english")

# trainer.train(
#     "chatterbot.corpus.english.greetings",
#     "chatterbot.corpus.english.conversations",
#     "chatterbot.corpus.english.emotion",
# )

# You can also specify file paths to corpus files or directories of corpus files when calling the train method.
trainer.train("./corpus/")

# from chatterbot.trainers import ListTrainer
# trainer = ListTrainer(bot)
Beispiel #33
0
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

app = Flask(__name__)

english_bot = ChatBot("Chatterbot",
                      storage_adapter="chatterbot.storage.SQLStorageAdapter")
trainer = ChatterBotCorpusTrainer(english_bot)
trainer.train("chatterbot.corpus.english")


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    return str(english_bot.get_response(userText))


if __name__ == "__main__":
    app.run()
Beispiel #34
0
						  'import_path': 'chatterbot.logic.SpecificResponseAdapter',
						  'input_text': 'Can you show my the highest rated book list please !',
						  'output_text': 'Ok, here is a link: localhost:8000/high'
					  },
					  {
						  "import_path": "chatterbot.logic.BestMatch",
						  "statement_comparison_function": levenshtein_distance,
						  "response_selection_method": get_first_response,
					  },
				  ]
				  )
#Statement.objects.all().delete()

book = open('bot/dataset/book.txt','r').readlines()
trainer1 = ListTrainer(chatbot)
trainer2 = ChatterBotCorpusTrainer(chatbot)
#
#Train based on the english corpus
trainer1.train(book)
trainer2.train("chatterbot.corpus.english.greetings",
 			   "chatterbot.corpus.english.conversations")

@csrf_exempt
def get_response(request):
	response = {'status': None}

	if request.method == 'POST':
		data = json.loads(request.body)
		message = data['message']

		chat_response = chatbot.get_response(message).text
Beispiel #35
0
from chatterbot.trainers import ChatterBotCorpusTrainer
from settings import GITTER


# Uncomment the following lines to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)


chatbot = ChatBot(
    'GitterBot',
    gitter_room=GITTER['ROOM'],
    gitter_api_token=GITTER['API_TOKEN'],
    gitter_only_respond_to_mentions=False,
    input_adapter='chatterbot.input.Gitter',
    output_adapter='chatterbot.output.Gitter'
)

trainer = ChatterBotCorpusTrainer(chatbot)

trainer.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
# Uncomment the following line to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)

CONVERSATION = 'example_learning_conversation'

# Create a new instance of a ChatBot
bot = ChatBot(
    "Terminal",
    storage_adapter="chatterbot.storage.SQLStorageAdapter",
    input_adapter="chatterbot.input.TerminalAdapter",
    output_adapter="chatterbot.output.TerminalAdapter"
)

trainer = ChatterBotCorpusTrainer(bot)

trainer.train("chatterbot.corpus.english")


def get_feedback():

    text = input()

    if 'yes' in text.lower():
        return False
    elif 'no' in text.lower():
        return True
    else:
        print('Please type either "Yes" or "No"')
        return get_feedback()