def main(): # Create two Cleverbot connections alice = Cleverbot('cleverbot-py-example') bob = Cleverbot('cleverbot-py-example') print('>> Alice: Hi.') answer = bob.ask('Hi.') while True: print('>> Bob: {}'.format(answer)) answer = alice.ask(answer) print('>> Alice: {}'.format(answer)) answer = bob.ask(answer)
def askClever(intent, session): if 'query' in intent['slots']: querySlot = intent['slots']['query']['value'] else: speech_output = "I'm sorry, I didn't understand, you can say something like 'Hi, how are you?'" card_title = None should_end_session = True reprompt_text = "" return build_response({}, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session)) cb = Cleverbot() #Gets the response queryRun = cb.ask(querySlot) speech_output = queryRun card_title = None should_end_session = False reprompt_text = "" return build_response({}, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session, queryRun))
class CleverBotBehavior(object): def __init__(self): self.cleverbot = Cleverbot() self.name = 'Cleverbot' def execute(self, bot, msg, event): bot.send_msg(self.cleverbot.ask(msg), event['channel'])
class Chatbot: def __init__(self): self.bot = Cleverbot() logger.info('Chatbot initialized.') def ask(self, text): return self.bot.ask(text)
def main(): # instantiate a Cleverbot object client = Cleverbot('cleverbot-py-example') while True: question = input('>> You: ') answer = client.ask(question) print('>> Cleverbot: {}'.format(answer))
def generate_text_from_cleverbot(text_raw): cb = Cleverbot() try: cleverbot_reply = cb.ask(text_raw) return cleverbot_reply except: print "Cleverbot failed to reply" pass
class RobanonPlugin(Plugin): def load(self): super(RobanonPlugin, self).load() self.cb = Cleverbot() self.last_message = time.time() @Plugin.schedule(120, init=False) def keepalive(self): # TODO for over channels if time.time() - self.last_message > 75: self.send_one( self.state.channels.get(self.config.channel_ids[0]), random.choice(RESET_LINES)) def send_one(self, channel, seed): res = self.get_cb_response(seed) if not res: raise Exception('WTF') channel.send_message(res) self.last_message = time.time() def get_cb_response(self, msg): for _ in range(10): try: res = self.cb.ask(msg) if PREVIOUS_LINES.count(res) > 3: self.log.info('Resetting due to repeats: `%s`', res) self.cb = Cleverbot() msg = random.choice(RESET_LINES) continue PREVIOUS_LINES.append(res) return res except: self.log.exception('Error: ') self.cb = Cleverbot() gevent.sleep(2) @Plugin.listen('MessageCreate') def on_message_create(self, event): if event.channel.id not in self.config.channel_ids: return if event.author.id not in self.config.bot_cycle: return if self.state.me.id != self.config.bot_cycle[event.author.id]: return self.client.api.channels_typing(event.channel.id) gevent.sleep(get_delay()) self.send_one(event.channel, event.content)
class RobanonPlugin(Plugin): def load(self): super(RobanonPlugin, self).load() self.cb = Cleverbot() self.last_message = time.time() @Plugin.schedule(120, init=False) def keepalive(self): # TODO for over channels if time.time() - self.last_message > 75: self.send_one(self.state.channels.get(self.config.channel_ids[0]), random.choice(RESET_LINES)) def send_one(self, channel, seed): res = self.get_cb_response(seed) if not res: raise Exception('WTF') channel.send_message(res) self.last_message = time.time() def get_cb_response(self, msg): for _ in range(10): try: res = self.cb.ask(msg) if PREVIOUS_LINES.count(res) > 3: self.log.info('Resetting due to repeats: `%s`', res) self.cb = Cleverbot() msg = random.choice(RESET_LINES) continue PREVIOUS_LINES.append(res) return res except: self.log.exception('Error: ') self.cb = Cleverbot() gevent.sleep(2) @Plugin.listen('MessageCreate') def on_message_create(self, event): if event.channel.id not in self.config.channel_ids: return if event.author.id not in self.config.bot_cycle: return if self.state.me.id != self.config.bot_cycle[event.author.id]: return self.client.api.channels_typing(event.channel.id) gevent.sleep(get_delay()) self.send_one(event.channel, event.content)
def run(msg): input = msg['text'].replace(bot['first_name'] + ' ', '') cb = Cleverbot() unescape = HTMLParser().unescape try: message = unescape(cb.ask(input)) except: message = u'🙃' send_message(msg['chat']['id'], message, reply_to_message_id = msg['message_id'])
def reply(self, comment): if self.reddit.get_info(thing_id=comment.parent_id).author.name == self.username: # TODO: handle a threaded conversation over restarts. will need a DB. ugh pass if comment.parent_id in self.conversations: cleverbot = self.conversations[comment.parent_id] else: cleverbot = Cleverbot() response = cleverbot.ask(comment.body) post = comment.reply(response) self.done.add(comment.id) self.conversations[post.id] = copy(cleverbot)
def handle_autoreply(bot, event): """Handle autoreplies to keywords in messages""" cb = Cleverbot() # Test if message is not empty if not event.text: return # Test if autoreplies are enabled if not bot.get_config_suboption(event.conv_id, 'autoreplies_enabled'): return reply = cb.ask(event.text) yield from event.conv.send_message(text_to_segments(reply)) """
class CleverPlugin(Plugin): terms = None msg = None clever = None def __init__(self, maid): super().__init__(maid, 'cleverbot', ['mention']) self.needs_reload = False self.clever = Cleverbot() def load(self): print("Cleverbot loaded.") async def mention_callback(self, message): answer = self.clever.ask(message.content) await self.maid.say(message.channel, answer)
def handle_message(instance, command, predicate, message_entity, who, conversation): # N***a who send the message (first name) who_name = message_entity.getNotify().split(" ")[0] if command == "hi" or command == "hola": answer = "Hola *" + who_name + "*" mac.send_message(instance, answer, conversation) elif command == "help": answer = "Hola *" + who_name + "*\nNo puedo ayudarte por ahora" mac.send_message(instance, answer, conversation) elif command == "siono": yesno = YesNo(instance, conversation) yesno.send_yesno() elif command == "yt": WAYoutube(instance, who, conversation) elif command == "poll": # args = <title>, <identifier (optional)> args = [x.strip() for x in predicate.split(',')] if len(args) <= 0: mac.send_message(instance, "_Argumentos invalidos_", conversation) return if len(args) >= 1: if args[0] == "finish": poll.finish_my_poll(instance, who, conversation) return if len(args) == 1: title = args[0] basic_boll = poll.WAPoll(instance, conversation, who, title) basic_boll.send_poll() elif len(args) >= 2: title = args[0] identifier = args[1] basic_boll = poll.WAPoll(instance, conversation, who, title, identifier) basic_boll.send_poll() else: # No command for this so use IA cb = Cleverbot() answer = cb.ask(command + " " + predicate) mac.send_message(instance, answer, conversation)
async def talk(self, ctx): cleverbot_client = Cleverbot(str(self.bot.user.name)) await self.bot.say(":fire: type exit to quit") while True: question = await self.bot.wait_for_message( author=ctx.message.author, channel=ctx.message.channel, timeout=60) try: if question.content == "exit": await self.bot.say(":+1:") break await self.bot.send_typing(ctx.message.channel) answer = cleverbot_client.ask(question.content) await asyncio.sleep(2) await self.bot.say(answer) except AttributeError: await self.bot.say("Ok then, well talk later") break
class Ask(PluginBase, Observer): def __init__(self, command='ask'): super(self.__class__, self).__init__(command=command) Observer.__init__(self) self.cb = Cleverbot('cleverbot-tautbot') def events(self, *args, **kwargs): self.observe('channel_command', self.route_event) def route_event(self, command, channel, text, output): if re.match('^ask', command): text = text.replace(command, '').strip() self.ask(channel, text) def ask(self, channel, text): response = self.cb.ask(text) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def respond(): cb = Cleverbot() resp = twilio.twiml.Response() body = request.values.get('Body', None) print request.values print body demos_mentioned = [] for demo in known_demos: if demo in body.lower(): demos_mentioned.append(demo) get_feedback = False if demos_mentioned: response = get_response_for_demos(demos_mentioned) #want to find out if what we gave was effective get_feedback = True else: #no demos were detected so no feedback should be gathered get_feedback = False #they might be giving us feedback from the previous convo feedback = handle_feedback(body, resp) if feedback: response = feedback else: #nope they're not, let's just use cleverbot to reply response = cb.ask(body) if get_feedback: store_cookies(demos_mentioned) response += "*****\nWas this information helpful? (Y/N)" resp.sms(response) #TODO: store user info (maybe?) return str(resp)
def askClever(intent, session): if 'query' in intent['slots']: querySlot = intent['slots']['query']['value'] else: speech_output = "I'm sorry, I didn't understand, you can say something like 'Hi, how are you?'" card_title = None should_end_session = True reprompt_text = "" return build_response({}, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session)) cb = Cleverbot() #Gets the response queryRun = cb.ask(querySlot) speech_output = queryRun card_title = None should_end_session = False reprompt_text = "" return build_response({}, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session, queryRun))
def _prophet(self, word): """ AI autoreply. """ """ url = 'http://192.168.0.10:5000/chatbot/' headers = {'Content-Type': 'application/json'} payload = {'text': str(word)} try: r = requests.post(url, data=json.dumps(payload), headers=headers) if r and r.status_code == 200: return r.content else: replies = ["Awesome!", "Really?", "And then?", "Good to hear.", "Okay, enough!"] return replies[random.randint(0,4)] except: return "Sorry, I can't understand." """ prophet = Cleverbot() return prophet.ask(word)
class SkypeBot(object): def __init__(self): self.skype = Skype4Py.Skype(Events=self) self.skype.Attach() self.me = self.skype.CurrentUser self.stupidBot = Cleverbot() self.awayMessage = "\ Hi, seems like Denis isn't in front of \ me right now. I am Gentoo penguin, his pet. \ Would you like to talk for a while ?" self.chatsSoFar = [] def UserStatus(self, Status): print 'The status of the user changed' def MessageStatus(self, msg, Status): time.sleep(1.0) chat = msg.Chat sender = msg.Sender if sender == self.me: return if chat in self.chatsSoFar: activityTime = chat.ActivityDatetime now = datetime.now() timeDiff = now - activityTime minDiff = timeDiff.seconds / 60 if minDiff > 20: self.chatsSoFar.remove(chat) # Prevent intruding to public chats, rethink it later if self.me.Handle in chat.Name \ and self.me.OnlineStatus == 'AWAY': if chat not in self.chatsSoFar: chat.SendMessage(self.awayMessage) self.chatsSoFar.append(chat) else: answer = self.stupidBot.ask(msg.Body) chat.SendMessage(answer) else: print 'Prolly this is not the right chat'
class ChatBot(Plugin): def load(self): self.chat_bot = Cleverbot() self.dm_bots = defaultdict(Cleverbot) @command( p.bind(p.mention, 'user') + p.bind((p.many(p.any_type >> p.to_s)), 'words'), master_only ) async def answer(self, message, user, words): if str(user) != self.bot.user.id: return await self.bot.send_typing(message.channel) response = self.chat_bot.ask(' '.join(words)) if response: await self.send_message( message.channel, response ) @command(p.bind((p.many(p.any_type >> p.to_s)), 'words')) async def answer_dm(self, message, words): if message.server: return await self.bot.send_typing(message.channel) bot = self.dm_bots[message.author.id] response = bot.ask(' '.join(words)) if response: await self.send_message( message.channel, response )
def main(data): if data['config']['settings']['botNick'] in data['recv']\ or data['config']['settings']['botNick'].lower() in data['recv']: from cleverbot import Cleverbot global cleverbot if not 'cleverbot' in globals(): # check for instance cleverbot = Cleverbot() # print "making new bot" args = argv('', data['recv']) query = args['message'] query = query.replace('\n','') query = query.replace('\r','') query = query.replace(data['config']['settings']['botNick'] + ':','') query = query.replace(data['config']['settings']['botNick'],'CleverBot') answer = html_decode(cleverbot.ask(query)) answer = answer.replace('CleverBot',data['config']['settings']['botNick']) answer = answer.replace('Cleverbot',data['config']['settings']['botNick']) answer = answer.replace('God','Taiiwo') answer = answer.replace('god','Taiiwo') debug = 'Query: ' + query + ' -- Answer: "' + answer + '"' print debug data['api'].say(args['channel'], args['nick'] + ': ' + answer)
class CleverBot(AbstractScript): name = "CleverBot" trigger = "gote" p = 0.01 helpstring = """ [b]CleverBot[/b] \tChat with Cleverbot. [b]Examples:[/b] \tgote [i]<message>[/i] \tgote [i]good morning[/i] \t[i]good morning[/i] gote """ def __init__(self): """ Initialise Cleverbot connection. """ self.cb = Cleverbot() def react(self, event, conn, settings): """ Act. False if there is no message to send, string message otherwise. """ if "msg" in event: if event["invokername"] == settings["name"]: return False m = event["msg"] # don't forget to check for trigger http://pastebin.com/zD2mAHH6 if (self.trigger.lower() in m.lower()) or random.random() < self.p: rem_trigger = re.compile(r"\b(" + self.trigger + r")\b", flags=re.IGNORECASE) result = self.cb.ask(rem_trigger.sub("", m)) conn.sendtextmessage(targetmode=2, target=1, msg=result) return True return False
async def on_message(message): if message_logging == True: connection = pymysql.connect(host='', user='', password='', db='', charset='', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = "INSERT INTO `messages` (`server`, `time`, `channel`, `author`, `content`) VALUES (%s, %s, %s, %s, %s)" if message.channel.is_private: cursor.execute(sql, ("Private Message", message.timestamp, "N/A", "{0} <{1}>".format(message.author.name, message.author.id) ,"{0}".format(message.content))) else: cursor.execute(sql, (message.server.name, message.timestamp, message.channel.name, "{0} <{1}>".format(message.author.name, message.author.id) ,"{0}".format(message.content))) connection.commit() finally: connection.close() try: # print("({0}, #{1}) {2} <{3}>: {4}".format(message.server.name, message.channel.name, message.author.name, message.author.id, message.content)) cb = Cleverbot() if message.author == bot.user: return cb_channels = ['150813303822614528', '173799905662337025', '161146445129318405', '175676162784100352'] #1. gmod, 4. flex kek = ['kek'] amirite = ['amirite', 'am i right', 'right', 'right?', 'amiright'] cb_ads = ['iOS', 'cleverbot', 'download', '.com', '.net', 'Android', 'angry', 'app', 'apps', 'Phone', 'pocket', 'SMS', 'Suprise'] if replies_disabled == False: if any(x in message.content.lower() for x in kek) and '.kek' not in message.content.lower(): msg = 'kek {0} *text* \nhttps://example.org\nhttps://example.org'.format(message.author.mention) await bot.send_message(message.channel, msg) if any(x in message.content.lower() for x in amirite): msg = 'ye you are right' await bot.send_message(message.channel, msg) await bot.send_message(message.channel, msg) if message.content.lower() == "change" and message.channel.id == "152162730244177920": await bot.send_message(message.channel, "**text**\nhttps://example.org") elif message.content.lower() == "cancer": await bot.send_message(message.channel, "**text**") await bot.send_file(message.channel, "/root/discord/cancer.gif") if cleverbot_b == True and any(x in message.channel.id for x in cb_channels): channel = discord.Object(id='{0}'.format(message.channel.id)) msg = cb.ask(str(message)) if any(x in msg for x in cb_ads): print("cleverbot ad, trying again") await bot.send_message(channel, msg) else: await bot.send_message(channel, msg) if random.randint(0, 1500) < 500: bot.send_typing(message.channel) if "<@" + message.author.id + ">" in open('/root/discord/utils/blacklist.txt').read() and message.channel.is_private == False: if blacklist_logging == True and message.channel.is_private == False: connection = pymysql.connect(host='', user='', password='', db='', charset='', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = "INSERT INTO `blacklist_log` (`server`, `user`, `time`) VALUES (%s, %s, %s)" if message.channel.is_private: cursor.execute(sql, ("Private Message", "{0} <{1}>".format(message.author.name, message.author.id), message.timestamp)) else: cursor.execute(sql, ("{0} #{1}".format(message.server.name, message.channel.name),"{0} <{1}>".format(message.author.name, message.author.id), message.timestamp)) connection.commit() finally: connection.close() return else: await bot.process_commands(message) except Exception as e: print(e) if say_errors_on_message == True: if message.channel.is_private: await bot.send_message(message.author, code.format(type(e).__name__ + ': ' + str(e))) else: await bot.send_message(message.channel, code.format(type(e).__name__ + ': ' + str(e)))
class SocialBot(): def __init__(self): logger.debug('Instantiating SocialBot') self.token = settings.SECRET_KEY self.slack = Slacker(self.token) self.facebook = Facebook() self.twitter = Twitter() self.cleverbot = Cleverbot() self.history = {} def channels(self): logger.debug('Getting all channels') channels = [] for channel in self.slack.channels.list().body['channels']: channels.append(channel) return channels def discover_userid(self, username): logger.debug('Getting user id') users = self.slack.users.list().body['members'] for user in users: if user['name'] == username: return user['id'] def discover_username(self, userid): logger.debug('Getting username') users = self.slack.users.list().body['members'] for user in users: if user['id'] == userid: return user['name'] def listen(self, channel): logger.debug('Listening...') self.messages = self.slack.channels.history(channel, count=3).body['messages'] bot_id = self.discover_userid(settings.BOT_NAME) bot_mention = "<@" + bot_id + ">" if str(channel) in self.history: if self.history[str(channel)] != self.messages: for message in self.messages: logger.debug('Getting new messages') if dict(message) not in self.history[str(channel)]: text = '' try: text = message['text'] logger.debug('New message: %s' % text) except: logger.error('Invalid message: %s' % str(message['text'])) if bot_mention in text: logger.debug('Oh! Someone is talking to me :D') self.talk(channel, message) if settings.SHARE_TRIGGER in text: logger.debug('Someone is calling me to share!') self.share(channel, text) self.history[str(channel)] = self.messages else: self.history[str(channel)] = [] self.listen(channel) def talk(self, channel, question): try: logger.debug('Talking to the moooon... ops, to the bot =P') answer = '@' + self.discover_username(question['user']) + ': ' + self.cleverbot.ask(question['text']) self.slack.chat.post_message(channel=channel, text=answer, as_user=settings.BOT_NAME) except Exception as ex: logger.error('Something wrong. Error: %s' % str(ex)) def share(self, channel, message): try: logger.debug('Sharing...') message = message.replace(settings.SHARE_TRIGGER, '').strip().replace('<', '').replace('>', '') self.facebook.post(message) self.twitter.post(message) except Exception as ex: logger.error('Something wrong. Error: %s' % str(ex))
def cleverbot_answer(message): cb = Cleverbot() answer = cb.ask(message) return answer
logger.logMessage(fileLog, ' Oops! Unable to read file.') for Subreddit in colSubreddits: logger.logMessage(fileLog, 'Entering %s...' % Subreddit) thisSub = r.get_subreddit(Subreddit) hot = thisSub.get_hot(limit=numPosts) for thing in hot: if not(thing.id in arrTouched): logger.logMessage(fileLog, 'Post: %s' % thing.title) try: for redComment in thing.comments: try: strComment = redComment.body strComment = strComment.strip() logger.logMessage(fileLog, ' Question: %s' % strComment) if (ValidComment(strComment)): strAnswer = cb.ask(strComment) logger.logMessage(fileLog, ' Answer: %s' % strAnswer) if (ValidReply(strAnswer)): logger.logMessage(fileLog, ' Valid answer. Waiting %s seconds before posting.' % timeDelay) time.sleep(timeDelay) try: redComment.reply(strAnswer) arrTouched.append(thing.id) logger.logMessage(fileLog, ' Success! Happy trolling!') except: logger.logMessage(fileLog, ' Oops! There was a problem posting the reply.') break break else: logger.logMessage(fileLog, ' Not a valid answer.') else:
import json # Probably not needed. Don't want to break anything right now though. from flask import Flask, request from cleverbot import Cleverbot cb = Cleverbot() app = Flask(__name__) print cb.ask("what's good") @app.route("/cleverbot", methods=["POST"]) def cb_query(): print "Received query" query = request.form["query"] response = cb.ask(query) print query print response print "---------------" return response if __name__ == "__main__": app.run(debug=True)
# -*- coding: utf-8 -*- # encoding=utf8 from cleverbot import Cleverbot import time import pyttsx import sys reload(sys) sys.setdefaultencoding('utf-8') en = pyttsx.init() cb1 = Cleverbot() cb2 = Cleverbot() s = cb1.ask('Привет') while True: print('bot1> ' + s) en.say(s) en.runAndWait() s = cb2.ask(s) print('bot2> ' + s) en.say(s) en.runAndWait() time.sleep(1) s = cb1.ask(s) time.sleep(1)
# variables and stuff Jack = Cleverbot () Jill = Cleverbot () JackQ = raw_input ('Enter start text: ') # LoopVar = to control loop LoopVar = True Speech2Txt = "kek" # main loop stuff # JackQ = the question Jack is going to ask Jill # JillQ = the question Jill is going to ask Jack while LoopVar: try: JillQ = Jack.ask (JackQ) Speech2Txt = 'echo "' + JackQ + '" | espeak -v +m1 ' print 'Jack: ' + JackQ os.system (Speech2Txt) JackQ = Jill.ask (JillQ) Speech2Txt = 'echo "' + JillQ + '" | espeak -v +f1' print 'Jill: ' + JillQ os.system (Speech2Txt) except KeyboardInterrupt: LoopVar = False except KeyboardInterrupt: print 'BYE!'
class SocialBot: def __init__(self): logger.debug("Instantiating SocialBot") self.token = settings.SECRET_KEY self.slack = Slacker(self.token) self.facebook = Facebook() self.twitter = Twitter() self.cleverbot = Cleverbot() self.history = {} def channels(self): logger.debug("Getting all channels") channels = [] for channel in self.slack.channels.list().body["channels"]: channels.append(channel) return channels def discover_userid(self, username): logger.debug("Getting user id") users = self.slack.users.list().body["members"] for user in users: if user["name"] == username: return user["id"] def discover_username(self, userid): logger.debug("Getting username") users = self.slack.users.list().body["members"] for user in users: if user["id"] == userid: return user["name"] def listen(self, channel): logger.debug("Listening...") self.messages = self.slack.channels.history(channel, count=3).body["messages"] bot_id = self.discover_userid(settings.BOT_NAME) bot_mention = "<@" + bot_id + ">" if str(channel) in self.history: if self.history[str(channel)] != self.messages: for message in self.messages: logger.debug("Getting new messages") if dict(message) not in self.history[str(channel)]: text = "" try: text = message["text"] logger.debug("New message: %s" % text) except: logger.error("Invalid message: %s" % str(message["text"])) if bot_mention in text: logger.debug("Oh! Someone is talking to me :D") self.talk(channel, message) if settings.SHARE_TRIGGER in text: logger.debug("Someone is calling me to share!") self.share(channel, text) self.history[str(channel)] = self.messages else: self.history[str(channel)] = [] self.listen(channel) def talk(self, channel, question): try: logger.debug("Talking to the moooon... ops, to the bot =P") answer = "@" + self.discover_username(question["user"]) + ": " + self.cleverbot.ask(question["text"]) self.slack.chat.post_message(channel=channel, text=answer, as_user=settings.BOT_NAME) except Exception as ex: logger.error("Something wrong. Error: %s" % str(ex)) def share(self, channel, message): try: logger.debug("Sharing...") message = message.replace(settings.SHARE_TRIGGER, "").strip().replace("<", "").replace(">", "") self.facebook.post(message) self.twitter.post(message) except Exception as ex: logger.error("Something wrong. Error: %s" % str(ex))
class Robotson(): def __init__(self, token): self.token = token self.slack = SlackClient(token=self.token) self.cleverbot = Cleverbot() self.botname = settings.BOT_NAME self.facebook = Facebook() self.twitter = Twitter() self.network = SocialNetwork() def run(self, interval): if self.slack.rtm_connect(): while True: full_message = self.slack.rtm_read() if full_message: content = full_message[0] if content.get("type") == 'message': sender = self.username_as_str(content.get("user")) channel = content.get("channel") message = content.get("text") try: match = re.search(r'<@[A-Z0-9]+>', message) bot_mention = match.group() if match else "" if bot_mention: # TODO: Remove hardcoding if settings.BOT_UID in bot_mention: self.talk(channel, sender, message) elif settings.SHARE_TRIGGER in message.lower(): self.share(message) except: pass time.sleep(interval) else: raise SlackNotConnected def share(self, message): try: match_share_trigger = re.search(r'%s[\:]?' % settings.SHARE_TRIGGER, message) message = message.replace(match_share_trigger.group(), "") match_lt_mt = re.search(r'[<]+(.*)[>]+', message) message = message.replace(match_lt_mt.group(0), match_lt_mt.group(1)) message = message.strip() url = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message) if len(url) > 0: if not self.network.already_posted(url[0]): self.facebook.post(message) # self.twitter.post(message) self.network.save_message(message) except Exception: pass def talk(self, channel, user, message): try: answer = '@%s: %s' % (user, self.cleverbot.ask(message)) self.slack.rtm_send_message(channel=channel, message=answer) except Exception: pass def username_as_str(self, userid): try: response = json.loads(self.slack.api_call('users.info', user=userid)) return response.get("user").get("name") except: return ""
from cleverbot import Cleverbot from time import sleep cb = Cleverbot('cleverloop') iask = (cb.ask("hi")) while True: print(iask) iask = (cb.ask(iask)) sleep(1)
async def on_message(message): if message_logging == True: connection = pymysql.connect(host='', user='', password='', db='', charset='', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = "INSERT INTO `messages` (`server`, `time`, `channel`, `author`, `content`) VALUES (%s, %s, %s, %s, %s)" if message.channel.is_private: cursor.execute( sql, ("Private Message", message.timestamp, "N/A", "{0} <{1}>".format(message.author.name, message.author.id), "{0}".format( message.content))) else: cursor.execute( sql, (message.server.name, message.timestamp, message.channel.name, "{0} <{1}>".format( message.author.name, message.author.id), "{0}".format(message.content))) connection.commit() finally: connection.close() try: # print("({0}, #{1}) {2} <{3}>: {4}".format(message.server.name, message.channel.name, message.author.name, message.author.id, message.content)) cb = Cleverbot() if message.author == bot.user: return cb_channels = [ '150813303822614528', '173799905662337025', '161146445129318405', '175676162784100352' ] #1. gmod, 4. flex kek = ['kek'] amirite = ['amirite', 'am i right', 'right', 'right?', 'amiright'] cb_ads = [ 'iOS', 'cleverbot', 'download', '.com', '.net', 'Android', 'angry', 'app', 'apps', 'Phone', 'pocket', 'SMS', 'Suprise' ] if replies_disabled == False: if any(x in message.content.lower() for x in kek) and '.kek' not in message.content.lower(): msg = 'kek {0} *text* \nhttps://example.org\nhttps://example.org'.format( message.author.mention) await bot.send_message(message.channel, msg) if any(x in message.content.lower() for x in amirite): msg = 'ye you are right' await bot.send_message(message.channel, msg) await bot.send_message(message.channel, msg) if message.content.lower( ) == "change" and message.channel.id == "152162730244177920": await bot.send_message(message.channel, "**text**\nhttps://example.org") elif message.content.lower() == "cancer": await bot.send_message(message.channel, "**text**") await bot.send_file(message.channel, "/root/discord/cancer.gif") if cleverbot_b == True and any(x in message.channel.id for x in cb_channels): channel = discord.Object(id='{0}'.format(message.channel.id)) msg = cb.ask(str(message)) if any(x in msg for x in cb_ads): print("cleverbot ad, trying again") await bot.send_message(channel, msg) else: await bot.send_message(channel, msg) if random.randint(0, 1500) < 500: bot.send_typing(message.channel) if "<@" + message.author.id + ">" in open( '/root/discord/utils/blacklist.txt').read( ) and message.channel.is_private == False: if blacklist_logging == True and message.channel.is_private == False: connection = pymysql.connect( host='', user='', password='', db='', charset='', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = "INSERT INTO `blacklist_log` (`server`, `user`, `time`) VALUES (%s, %s, %s)" if message.channel.is_private: cursor.execute( sql, ("Private Message", "{0} <{1}>".format( message.author.name, message.author.id), message.timestamp)) else: cursor.execute(sql, ("{0} #{1}".format( message.server.name, message.channel.name), "{0} <{1}>".format( message.author.name, message.author.id), message.timestamp)) connection.commit() finally: connection.close() return else: await bot.process_commands(message) except Exception as e: print(e) if say_errors_on_message == True: if message.channel.is_private: await bot.send_message( message.author, code.format(type(e).__name__ + ': ' + str(e))) else: await bot.send_message( message.channel, code.format(type(e).__name__ + ': ' + str(e)))
def response(self): cb = Cleverbot() resp = cb.ask(self.tweet) return resp
class Robotson(): def __init__(self, token): self.token = token self.slack = SlackClient(token=self.token) self.cleverbot = Cleverbot() self.botname = settings.BOT_NAME self.facebook = Facebook() self.twitter = Twitter() self.network = SocialNetwork() def run(self, interval): if self.slack.rtm_connect(): while True: full_message = self.slack.rtm_read() if full_message: content = full_message[0] if content.get("type") == 'message': sender = self.username_as_str(content.get("user")) channel = content.get("channel") message = content.get("text") try: match = re.search(r'<@[A-Z0-9]+>', message) bot_mention = match.group() if match else "" if bot_mention: # TODO: Remove hardcoding if settings.BOT_UID in bot_mention: self.talk(channel, sender, message) elif settings.SHARE_TRIGGER in message.lower(): self.share(message) except: pass time.sleep(interval) else: raise SlackNotConnected def share(self, message): try: match_share_trigger = re.search( r'%s[\:]?' % settings.SHARE_TRIGGER, message) message = message.replace(match_share_trigger.group(), "") match_lt_mt = re.search(r'[<]+(.*)[>]+', message) message = message.replace(match_lt_mt.group(0), match_lt_mt.group(1)) message = message.strip() url = re.findall( r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message) if len(url) > 0: if not self.network.already_posted(url[0]): self.facebook.post(message) # self.twitter.post(message) self.network.save_message(message) except Exception: pass def talk(self, channel, user, message): try: answer = '@%s: %s' % (user, self.cleverbot.ask(message)) self.slack.rtm_send_message(channel=channel, message=answer) except Exception: pass def username_as_str(self, userid): try: response = json.loads( self.slack.api_call('users.info', user=userid)) return response.get("user").get("name") except: return ""
# Setup Variables Running = True # Main loop while Running == True: # Get voice input - GOOGLE MAGIC subprocess.call("./StT.sh") # Import Google Speech question question = open("question.txt").read() print "Q: %s" % question # Check if user wants to quit if "goodbye" in question: Running = False # Send to Cleverbot, and get response in ASCII response = ChatBot.ask(question) response = response.encode("utf-8") print "A: %s" % response # Save response to text file with open("response.txt", "w") as text_file: text_file.write("%s" % response) # Speak response aloud subprocess.call(["festival", "--tts", "response.txt"]) print "Thanks for chatting to CleverVoice"
class Chatbot(object): port = '/dev/ttyACM1' ########################################################################## def __init__(self): self.cb = Cleverbot() self.r = sr.Recognizer() self.ard = serial.Serial(self.port, 9600, timeout=5) self.pyttsx_engine = pyttsx.init() ########################################################################## @property def get_input(self): #Get audio input from user with sr.Microphone() as source: print("Say something!") audio = self.r.listen(source) # Speech recognition using Google Speech Recognition try: question = "" #for testing purposes, we're just using the default API key #to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` #instead of `r.recognize_google(audio)` question = self.r.recognize_google(audio) print("You said: " + question) except (sr.UnknownValueError, sr.RequestError) as e: question = "Hello" print("Google Speech Recognition encountered an error: {0}".format( e)) return question ########################################################################## def query_cleverbot(self, question): #Query Cleverbot with user input print("Calling Cleverbot!") try: answer = self.cb.ask(question) print("Cleverbot said: {}".format(answer)) #For *nix systems. #subprocess.call(["espeak", answer]) self.pyttsx_engine.say(answer) self.pyttsx_engine.runAndWait() except: print("Error!") answer = "Can you repeat that?" ########################################################################## def query_watson(self, conn, question): # Call watson to analysis the mood of input print("Calling Watson!") data = str(question) url = 'https://watson-api-explorer.mybluemix.net/tone-analyzer/api/v3/tone?version=2016-05-19' response = "" try: req = urllib2.Request(url, data, {'Content-Type': 'text/plain'}) f = urllib2.urlopen(req) for line in f: response = response + line f.close() response = json.loads(response) except IOError: print("Failed to open {0}.".format(url)) except ValueError: print("Could not decode JSON!") watson_mood_values = {} moods = ("Anger", "Disgust", "Fear", "Joy", "Sadness") #if response from watson, choose the mood with the highest score #else pick a random mood to return if response: for elem in response['document_tone']['tone_categories'][0][ 'tones']: #print elem['tone_name'] watson_mood_values[elem['tone_name']] = elem['score'] #print elem['score'] maximum = max(watson_mood_values, key=watson_mood_values.get) #print(maximum, mood_values[maximum]) #return maximum else: maximum = random.choice(moods) #return result to parent conn.send(maximum) conn.close() ########################################################################## def send_to_arduino(self, input_mood): try: self.ard.flush #convert from unicode input_mood = str(input_mood) print("Python value sent: {0}".format(input_mood)) #currently writes a string to Serial on Arduino #this can be changed self.ard.write(input_mood) self.ard.flush except: print("Failed to write to Arduino!") time.sleep(1)
new_message = omegle.retrieve_new_message() if new_message == []: count += 1 if omegle.still_here() or count >= 20: count = 0 cb = Cleverbot() omegle.talk.close() omegle.start_again() else: count = 0 for x in new_message: try: omegle.goodbye(x.text[10:].lower()) anw = cb.ask(x.text[10:]) omegle.talk.write(x.text+"\r\n") omegle.talk.write("CleverBot: "+anw+"\r\n") print(x.text) print(anw) omegle.send_message(anw) except: try: print("") count = 0 cb = Cleverbot() omegle.talk.close() omegle.start_new_chat() except: alert = omegle.driver.switch_to_alert() alert.accept()