def main(): # instantiate two Cleverbot objects cleverbot_client_one = cleverbot.Cleverbot() cleverbot_client_two = cleverbot.Cleverbot() print '>> Cleverbot #1: Hi.' answer = cleverbot_client_two.ask('Hi.') while True: print '>> Cleverbot #2: {}'.format(answer) answer = cleverbot_client_one.ask(answer) print '>> Cleverbot #1: {}'.format(answer) answer = cleverbot_client_two.ask(answer)
def pollEvents(id, events): cb = cleverbot.Cleverbot() lastMessage = time.time() while 1: # Read from Omegle to see if anything is happening try: omegle = urllib2.urlopen(events) data = omegle.read() omegle.close() eventsJson = simplejson.loads(data) except: log('Hmm... Something went wrong...', Fore.RED) break # print data # uncomment if you want the to see the raw response if eventsJson == None: break for json in eventsJson: if json[0] == 'connected': log("Connected!") if len(sys.argv) < 2: seed = cb.think() # make this a random selection else: seed = sys.argv[1] sendMessage(id, seed) #cb.Ask(seed) elif json[0] == 'typing': log("Omegle User is typing...") lastMessage = time.time() elif json[0] == 'gotMessage': incomingMsg = json[1] log(incomingMsg, 'Omegle User', Fore.RED) # respond try: typing(id) outgoingMsg = cb.ask(incomingMsg) sendMessage(id, outgoingMsg) except Exception as e: log(str(e)) sendMessage( id, "Huh?!" ) # something went wrong with cleverbot (timeout, whatever) lastMessage = time.time() elif json[0] == 'strangerDisconnected': log('Omegle User has disconnected.', color=Fore.YELLOW) break if time.time() - lastMessage > 60: log("Idle timeout, disconnecting", color=Fore.YELLOW) break
def clever_responder(bot, event): """Handle clever replies to messages""" # Test if message is not empty if not event.text: return # Test if clever replies are enabled enabled = bot.get_config_suboption(event.conv_id, 'clever_enabled') if not enabled: return # Don't process anything that begins with the command character commands_character = bot.get_config_suboption(event.conv_id, 'commands_character') if event.text.startswith(commands_character): return # Determine odds of replying chance = bot.get_config_suboption(event.conv_id, 'clever_chance') if chance: # If we only reply to every 1/ X messages, # see if a random float is greater than those odds if random.random() > chance: return # Grab or create a cleverbot client for this chat client = cleverbot.clients.get(event.conv_id, cleverbot.Cleverbot()) # Get a response from cleverbot response = client.ask(event.text) yield from event.conv.send_message(text_to_segments(response)) # Stop other handlers from processing event raise StopEventHandling
def chatstuffThreaded(talker, channel, text): global convos global last_response global talkon key = (talker, channel) if (player.name in text) or (channel == 'says') or (channel.startswith('tell')): if (talker, channel) not in convos: sage.echo("Starting a new convo") val = { 'time': time.time(), 'response': '', 'bot': cleverbot.Cleverbot() } convos[key] = val val = convos[key] response = '' if channel == 'says': response = 'say ' elif channel.startswith('clt'): response = 'clan switch %s;clt ' % (re.sub('clt', '', channel)) elif channel.startswith('tell'): response = channel + ' ' else: sage.echo("SOMEONE SAID MY NAME OVER %s!!!" % channel) return sage.echo(re.sub('"', '', re.sub('.*, "', '', text))) sage.echo(talker) sage.echo(channel) response = response + ' ' + val['bot'].ask(text) last_response = max(time.time(), last_response) time_to_type = len(response) / 5.0 last_response = last_response + time_to_type sage.delay(last_response - time.time(), sage.send, response)
async def on_message(self, message, pfx): if message.content.startswith(self.client.user.mention): await self.client.send_typing(message.channel) cmd_name = 'Kiss Me' try: self.log.info( 'User %s [%s] on server %s [%s], used the ' + cmd_name + ' command on #%s channel', message.author, message.author.id, message.server.name, message.server.id, message.channel) except: self.log.info( 'User %s [%s], used the ' + cmd_name + ' command.', message.author, message.author.id) try: clv_input = message.content[len(self.client.user.mention):] cb = cleverbot.Cleverbot() response = cb.ask(clv_input) await asyncio.sleep(len(response) * 0.0145) await self.client.send_message( message.channel, '<@' + message.author.id + '> ' + response) except: await self.client.send_message( message.channel, 'Sorry <@' + message.author.id + '>, my brain isn\'t working at the moment give me some time to catch my breath...' )
def test_cleverbot_load_data(self, cb): with io.BytesIO() as f: cb.save(f) with io.BytesIO(f.getvalue()) as f: cb2 = cleverbot.Cleverbot(None) cb2.load(f) assert cb2.data == cb.data
def chat(): print "Talk to me" while True: string = raw_input() bot = cleverbot.Cleverbot() if string: if string[0] == '#': if string[1:5] == 'dict': dictionary(string[6:]) elif string[1:6] == 'movie': movie(string[7:]) elif string[1:5] == 'wiki': wiki(string[6:]) elif string[1:8] == 'yomomma': yomomma() elif string[1:6] == 'chuck': chuck() else: try: print bot.ask(string) except: print "Can't talk now. Try again later." else: continue
def handle(self, text, mic, profile): """ Responds to user-input, typically speech text, starting a conversation with cleverbot Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ mic.say('Starting clever bot') exit = False bot = cleverbot.Cleverbot() errors = 0 while not exit: try: question = mic.activeListen() if is_exit(question): break answer = bot.ask(question) mic.say(answer) except Exception as e: mic.say('Oops') print traceback.format_exc() errors += 1 if errors > 5: break mic.say('Stopping clever bot')
def cb(request, monkeypatch): cb = cleverbot.Cleverbot('API_KEY', cs='76nxdxIJ02AAA', timeout=60, tweak1=25, tweak2=50, tweak3=75) if hasattr(request, 'param'): def mock_get(url, params, timeout): class MockResponse(object): def __init__(self): if request.param.get('timeout'): raise requests.Timeout if request.param.get('params'): assert params == request.param['params'] self.status_code = request.param.get('status', 200) def json(self): return request.param.get('json', { 'output': 'test', 'cs': 'cs', 'test': 'test' }) return MockResponse() monkeypatch.setattr(cb.session, 'get', mock_get) return cb
async def cmd_cleverbot(message, question): if not question: await client.send_message(message.channel, "You must specify a question!") cb1 = cleverbot.Cleverbot() answer = cb1.ask(question) await client.send_message(message.channel, answer)
def say(parser, args): cb = cleverbot.Cleverbot(vars(args).pop('key')) try: print(cb.say(**vars(args))) except cleverbot.CleverbotError as error: parser.error(error) finally: cb.close()
def clever_ask(message, raw): if raw: return if message["nickname"] not in chats: chats[message["nickname"]] = cleverbot.Cleverbot("") return message["nickname"] + ": " + chats[message["nickname"]].ask(" ".join(message["arguments"][1:]))
def main(): # instantiate a Cleverbot object cleverbot_client = cleverbot.Cleverbot() while True: question = raw_input('>> You: ') answer = cleverbot_client.ask(question) print '>> Cleverbot: {}'.format(answer)
def cb_named(): cb = cleverbot.Cleverbot('API_KEY', cs='76nxdxIJ02AAA', timeout=60, tweak1=25, tweak2=50, tweak3=75) for i, s in enumerate(map(str, range(200))): cb.conversation(s, key=s, cs=s, timeout=i) return cb
def __init__(self, client): super(LeagueBot, self).__init__(client, 'leaguebot') self.storage_manager = CouchbaseManager( os.environ.get('MATCH_HISTORY_BUCKET')) self.riot = RiotWatcher(os.environ.get('RIOT_API_KEY'), default_region=EUROPE_WEST) self.players = self.load_player_list() self.champions = self.load_champions() self.memes = self.load_memes() self.cleverbot = cleverbot.Cleverbot()
def test_replay(self): cbc = cleverbot.Cleverbot() try: response = cbc.ask("Hi. How are you?") except cleverbot.CleverbotAPIError: # Technically, cleverbot errored. But we connected, which is all # that matters self.assertTrue(True) else: self.assertNotEquals(response, str())
def get_clever_response(user_id, text): # Remember conversations per user cache_key = "clever_response:%s" % user_id cb = cache.get(cache_key) if not cb: cb = cleverbot.Cleverbot() text = re.sub('changetip', '', text, 1, re.I).strip('@: ') response = cb.ask(text) cache.set(cache_key, cb, 3600) return response
def main(): # instantiate two Cleverbot objects cleverbot_client_one = cleverbot.Cleverbot() cleverbot_client_two = cleverbot.Cleverbot() #print('>> Mary: I like you') answer = cleverbot_client_two.ask(sys.argv[1]) print('>> Mike: ' + sys.argv[1]) for key in dictionary: num = random.uniform(0, 1) index = math.floor(num * len(dictionary[key])) prefix = dictionary[key][int(index)] if (key % 2 == 0): print('>> Mike: {} , {}'.format(prefix, answer)) answer = cleverbot_client_one.ask(prefix + answer) else: print('>> Mary: {} , {}'.format(prefix, answer)) answer = cleverbot_client_two.ask(prefix + answer)
def main(): bot = cleverbot.Cleverbot() while True: audio = r.listen(source) question = r.recognize(audio) if question == 'exit' or question == 'Exit': print('Goodbye') sys.exit() print('Me:' + question) answer = bot.ask(question) print('Cleverbot: {}'.format(answer))
def test_init(self): cb = cleverbot.Cleverbot('API_KEY', cs='76nxdxIJ02AAA', timeout=60, tweak1=25, tweak2=50, tweak3=75) assert cb.key == 'API_KEY' assert cb.cs == '76nxdxIJ02AAA' assert cb.timeout == 60 assert cb.tweak1 == 25 assert cb.tweak2 == 50 assert cb.tweak3 == 75
def core(parser, args): if not args.key: args.key = prompt("Your Cleverbot API key: ", required=True, hidden=True) cb = cleverbot.Cleverbot(**vars(args)) try: while True: text = prompt(">>> ") try: print(cb.say(text)) except cleverbot.CleverbotError as error: parser.error(error) finally: cb.close()
def __init__(self): # get the configuration if needed try: self.config = SnipsConfigParser.read_configuration_file(CONFIG_INI) except : self.config = None self.apiKey = self.config["secret"]["api_key"] self.bot = cleverbot.Cleverbot(self.apiKey, timeout=60) # start listening to MQTT self.tmpClient = paho.Client("snips-skill-cleverbot-" + str(int(round(time.time() * 1000)))) self.tmpClient.on_message = self.on_message self.tmpClient.on_log = self.on_log self.tmpClient.connect(MQTT_IP_ADDR, MQTT_PORT) self.tmpClient.subscribe("hermes/intent/#") self.tmpClient.subscribe("hermes/nlu/intentNotRecognized") self.tmpClient.loop_forever()
def __init__(self): super(YowCleverBotLayer, self).__init__() self.cb = cleverbot.Cleverbot()
def test_replay(self): cbc = cleverbot.Cleverbot() response = cbc.ask("Hi. How are you?") self.assertNotEquals(response, str())
except cleverbot.APIError as e: print(e.error, e.status) #main gatta be on the bottom. Code runs top to bottom. Functions need to be init'd first. For future notice (because Joey forgets things). #------------------------------------------------------# #Function: main #Use: main processing of script #Arguments: none #Return: none #------------------------------------------------------# if __name__ == '__main__': slack_client = SlackClient(SLACK_TOKEN) cb = cleverbot.Cleverbot(CLEVERBOT_TOKEN, cs='76nxdxIJ02AAA', timeout=60, tweak1=0, tweak2=100, tweak3=75) convo = cb.conversation() if (slack_client.rtm_connect()): print("Marvin has connected sir. As if it matters.") marvin_id = slack_client.api_call("auth.test")["user_id"] while True: command, channel = parse_command(slack_client.rtm_read()) if command: handle_command(command, channel, convo) time.sleep(READ_WEB_DELAY) else: print("RTM connection failure. Check Token dingleberry. DO IT AGAIN!")
def __init__(self, bot): self.bot = bot self.clv = clv.Cleverbot() self.settings = dataIO.load_json("data/cleverbot/settings.json")
import cleverbot cb = cleverbot.Cleverbot('CC526HD-cCoAmjfGia8reYjzKPg', timeout=60) x = 1 while x > 0: text = input("Say to Cleverbot: ") try: reply = cb.say(text) except cleverbot.CleverbotError as error: print(error) else: print(reply) finally: cb.close()
# Chat Bot :AAG import cleverbot with open('key.tar') as fp: #File name with key in it. key = fp.read() cb = cleverbot.Cleverbot(key, timeout=60) print('Talk To CleverBot') try: while (True): text = input() reply = cb.say(text) print(reply) except cleverbot.CleverbotError as error: print(error) finally: cb.close() print('GoodBye Have a nice day')
def do(msg): cb = cleverbot.Cleverbot() return cb.ask(msg)
async def kys(ctx, message, *text): cleverbot_client = cleverbot.Cleverbot() answer = cleverbot_client.ask(str(text)) await bot.say(answer)