def twitter(text, consumer_key, consumer_secret): from chatterbot.conversation import Statement from chatterbot.apis.twitter import Twitter from chatterbot.apis import clean import random api = TwitterAPI(consumer_key, consumer_secret) results = api.get_related_messages(text) output = [] for result in results: # Clean the text result = clean(result) # Remove leeding usernames result = remove_leeding_usernames(text) # Remove trailing usernames result = remove_trailing_usernames(text) # Ignore single usernames if len(result.split()) > 0 and result[0] != "@": output.append(result) # Pick a random statement as the default closest_statement = random.choice(output) closest_value = 0 # The sentence with the most words is typically a good response longest_statement = random.choice(output) longest_value = len(longest_statement.split()) for statement in output: value = 0 if len(statement.split()) > longest_value: longest_value = value longest_statement = statement # Find the statement that has the closest matching number of words words = text.lower().split() for statement in output: value = 0 for word in statement.lower().split(): if word in words: value += 1 if value > closest_value: closest_value = value closest_statement = statement # If results were found if len(output) > 0: return [Statement("Twitter", closest_statement)] else: return [ Statement("Error", "Twitter is a poor source of knowledge at the moment.") ]
def begin(self, bot_input="Hi. How are you?"): import time from random import randint from chatterbot.apis import clean print(self.chatbot.name, bot_input) while self.running: cb_input = self.cleverbot.ask(bot_input) print("cleverbot:", cb_input) cb_input = clean(cb_input) bot_input = self.chatbot.get_response(cb_input, "cleverbot") print(self.chatbot.name, bot_input) bot_input = clean(bot_input) # Delay a random number of seconds. time.sleep(1.05 + randint(0, 9))
def test_clean_function(self): """ Ensure that non-ascii characters are correctly removed """ from chatterbot.apis import clean text = u"Klüft skräms inför på fédéral électoral große" clean_text = clean(text) normal_text = "Kluft skrams infor pa federal electoral groe" self.assertEqual(clean_text, normal_text)
from chatterbot import ChatBot from chatterbot.cleverbot.cleverbot import Cleverbot from chatterbot.apis import clean from random import randint import time bot = ChatBot("Chatterbot", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapter="chatterbot.adapters.logic.EngramAdapter", io_adapter="chatterbot.adapters.io.TerminalAdapter", database="../clever-database.db", logging=True) cleverbot = Cleverbot() bot_input = "Hi. How are you?" print(bot.name, bot_input) while True: cb_input = cleverbot.ask(bot_input) print("cleverbot:", cb_input) cb_input = clean(cb_input) bot_input = bot.get_response(cb_input, "cleverbot") print(bot.name, bot_input) bot_input = clean(bot_input) # Delay a random number of seconds. time.sleep(1.05 + randint(0, 9))