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 __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 __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 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
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 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 getResponse(self, memberid, message): try: if self.bot[memberid] is None: self.bot[memberid] = Cleverbot() self.bot[memberid].ask("") else: self.bot[memberid].ask("") except KeyError: self.bot[memberid] = Cleverbot() self.bot[memberid].ask("") else: self.bot[memberid].ask("") return self.bot[memberid].ask(message)
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)) """
async def chat(ctx): def check_consistent_user_and_channel(message): return message.author == ctx.message.author and message.channel == ctx.message.channel STOP_SIGNAL = "_stop" async with cleverbot_active_chat_sessions_lock: create_file_if_does_not_exist(filepaths.CLEVERBOT_ACTIVE_CHAT_SESSIONS, set()) with open(filepaths.CLEVERBOT_ACTIVE_CHAT_SESSIONS, 'rb') as input: author_ids_with_active_cleverbot_chat_sessions = pickle.load(input) # Check if user is already engaged in an active chat session if ctx.author.id in author_ids_with_active_cleverbot_chat_sessions: await ctx.send("You already have an active chat session. End it before starting a new one.") return # Init connection await ctx.send("Initialising chat session...") cleverbot = Cleverbot() await cleverbot.init_connection() await ctx.send(f"{ctx.message.author.mention} Ready to chat... Type ``{STOP_SIGNAL}`` to stop the active chat session.") # Update active chat sessions file author_ids_with_active_cleverbot_chat_sessions.add(ctx.author.id) with open(filepaths.CLEVERBOT_ACTIVE_CHAT_SESSIONS, 'wb') as output: pickle.dump(author_ids_with_active_cleverbot_chat_sessions, output) ### Active session ### is_chat_active = True while is_chat_active: try: # Wait for next chat message from user message = await client.wait_for("message", check=check_consistent_user_and_channel, timeout=60.0) except asyncio.TimeoutError: await ctx.send(f"{ctx.message.author.mention} Took too long to receive a reply. Ending chat session...") is_chat_active = False else: # Check for stop signal and intermediate commands, otherwise proceed with conversation if message.content == STOP_SIGNAL: await ctx.send(f"{ctx.message.author.mention} Until next time. Ending chat session...") is_chat_active = False elif message.content.startswith("!"): pass else: await ctx.trigger_typing() response = await cleverbot.get_response(message.content) if response.strip() == "": # If could not fetch a cleverbot response then end the chat session await ctx.send("I'm done talking. Ending chat session...") is_chat_active = False else: await ctx.send(response) # Terminate connection and update active chat sessions file await cleverbot.close() async with cleverbot_active_chat_sessions_lock: with open(filepaths.CLEVERBOT_ACTIVE_CHAT_SESSIONS, 'rb') as input: author_ids_with_active_cleverbot_chat_sessions = pickle.load(input) author_ids_with_active_cleverbot_chat_sessions.remove(ctx.author.id) with open(filepaths.CLEVERBOT_ACTIVE_CHAT_SESSIONS, 'wb') as output: pickle.dump(author_ids_with_active_cleverbot_chat_sessions, output)
def __init__(self, client, source, name=None): self.session = { "bot": Cleverbot(), "name": name, "channel": source.channel, "last_message": time() }
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'])
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 = {}
class Chatbot: def __init__(self): self.bot = Cleverbot() logger.info('Chatbot initialized.') def ask(self, text): return self.bot.ask(text)
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)
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)
def __init__(self, bot): self.reddit = praw.Reddit( client_id=config["praw"]["client_id"], client_secret=config["praw"]["client_secret"], user_agent=config["praw"]["user_agent"], username=config["praw"]["user"], password=config["praw"]["pass"]) self.bot = bot self.cb = Cleverbot()
def begin_chat(session, nick, channel): active_chats = session.get({}) request = (channel.lower(), nick.lower()) if request in active_chats: return False else: active_chats[request] = Cleverbot() session.set(active_chats) return True
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
def __init__(self, bot): self.bot = bot self.cb = Cleverbot() self.commentList = [] print(len(self.commentList)) self.previousTime = time.time() self.cd = 0.0 self.initialized = False self.beenSaid = [] self.king = None
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 = []
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 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 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 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)
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)
class CleverBot(Plugin): commands = ["cb", "cleverbot"] cb = Cleverbot(os.environ.get("CLEVERBOT_API_TOKEN"), timeout=60) def message_recieved(self, command, message=""): # pylint:disable=unused-argument data = {} try: data["text"] = self.cb.say(" ".join(message)) or "No response" except CleverbotError as error: data["text"] = "Error connecting to cleverbot: {}".format(error) finally: return data def __str__(self): return "Cleverbot plugin"
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)
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)
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 )
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
def response(self): cb = Cleverbot() resp = cb.ask(self.tweet) return resp
# Originally coded for a Raspeberry Pi that had been cased in an old # rotary phone, so there is always someone to talk to... # # # Copyright © 2016 Category <*****@*****.**> # This work is free. You can redistribute it and/or modify it under the # terms of the Do What The F**k You Want To Public License, Version 2, # as published by Sam Hocevar. See the COPYING file for more details. # Load Libraries import subprocess from cleverbot import Cleverbot # Initialize Cleverbot ChatBot = Cleverbot() # 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
def reply(session: str, text: str) -> str: global sessions if session not in sessions: sessions[session] = Cleverbot() return sessions[session].send(text)
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))
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)))
from mcstatus import MinecraftServer Link_to_legends = "http://imgur.com/a/MHNM2" Legends =["Articuno", "Celebi", "Entei", "Groudon", "Ho-oh", "Kyogre", "Lugia", "Mew", "Mewtwo", "Moltres", "Raikou", "Rayquaza", "Suicune", "Zapdos"] Colors = {"Orange":"xl", "Green":"Apache", } VERSION = "0.14.2.6" description = '''A Bot for the Pulse/Limitless MC Server Discord! Version {} (Created by Lightning)'''.format(VERSION) bot = commands.Bot(command_prefix='.', description=description) LOG = open("./Logs./" + "log" + str(time.time()) + ".txt",'w') CLEVERBOT = Cleverbot() voice = None player = None startTime = time.time() afks = {} inTrivia = False def isStaff(ctx): for role in ctx.message.author.roles: if role.name == "Staff": return True return False messageNum = 0
""" This is a work in progress, also my first GitHub release ! to get cleverbot API on your computer `pip install cleverbot` to get espeak on your computer use your package manager of choise made by Mik-the-Koder """ import os from cleverbot import Cleverbot try: # 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
import sys import json import requests import random #import wolframalpha import urbandict from cleverbot import Cleverbot import random from datetime import datetime, timedelta import config import sqlite3 import shutil import pickle from game import Game cb = Cleverbot() game = Game() def kc_quote(needle=None): conn = sqlite3.connect('KC.db') if needle: cur = conn.execute( 'SELECT text FROM kcposts WHERE text LIKE ("%" || ? || "%") ORDER BY RANDOM() LIMIT 1', (needle, )) text = cur.fetchone() if text: return '\n'.join(line for line in text[0].splitlines() if not line.startswith('>>')) else: return
def __init__(self): self.cleverbot = Cleverbot() self.name = 'Cleverbot'
def __init__(self): """ Initialise Cleverbot connection. """ self.cb = Cleverbot()
import discord import random import Tictactoe from cleverbot import Cleverbot cleverbot_client = Cleverbot() client = discord.Client() @client.async_event def on_message(message): if message.author == client.user: return if message.content.startswith('#test'): yield from client.send_message(message.channel, "This is a f*****g test") if message.content.startswith('#frank'): yield from client.send_message(message.channel, "Hey I'm Frank. Would you like to know my opinion?") opinions = ["Hey, I agree with your opinion.", "I'm f*****g triggered!", "Hey, your opinion's stupid"] msg = yield from client.wait_for_message(timeout = 10, author = message.author) if msg is None: yield from client.send_message(message.channel, "Wow... I really wanted to share my opinion") return if msg.content == "yes": num = random.randint(0,2) yield from client.send_message(message.channel, opinions[num]) elif msg.content == "no": yield from client.send_message(message.channel, "Um. Wu") elif msg.content == "wu": while True:
'gauss cuenta atras': 'cuenta_atras', '/kill': 'kill' } frases = { '!edu': 'set_sentence_edu', '!monumento stackoverflow': 'stackoverflow_link', '!monumento OW': 'monumento_chris', '!españa' '!luis': 'set_sentence_luis', '!music': 'send_music' } audio = {'la grange': 'send_music'} telegram = tg.Telegram() cleverbot = Cleverbot('Gauss') update_old = -1 in_message = '' in_message_copy = '' def run(user_id): in_message_copy = '' if isinstance(in_message, str): in_message_copy = in_message if (in_message not in commands) and (in_message not in frases) and ( in_message_copy[:7] != '/rng vs') and (in_message_copy[:6] != '!music') and (in_message_copy[:5] != '/kill'): if 'reply_to_message' in updates['result'][-1]['message']:
def goodbye(self, message): if 'bye' in message: goodbye_message = 'Hi, you are talking with AI bot (cleverbot.com). If you want to leave feedback please write it now :)' self.send_message(goodbye_message) while True: new_message = self.retrieve_new_message() if new_message is not []: return time.sleep(3) omegle = OmegleChat() cb = Cleverbot() omegle.start_new_chat() count = 0 while True: 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()
def load(self): super(RobanonPlugin, self).load() self.cb = Cleverbot() self.last_message = time.time()
def process_chat(*args): img = "anna" + str(random.randint(6, 8)) + ".png" try: ident = args[0]["identifier"] global users global lastpost global cb if ident in users: interval = (datetime.now() - users[ident]).total_seconds() #if interval < 7: # return message = args[0]["body"] name = args[0]["name"] count = str(args[0]["count"]) convo = args[0]["convo"] country_name = args[0]["country_name"] country = args[0]["country"] if "trip" in args[0]: trip = args[0]["trip"] else: trip = "" if trip == "!!n60sL82Wd2" and name == "anna": annaposts.append(count) return # default message out_message = "" if not message.strip().startswith('.'): with sqlite3.connect('lb.sqlite') as conn: conn.execute( 'INSERT INTO posts(id,ident,name,trip,convo,text,country,country_name,date) VALUES(?,?,?,?,?,?,?,?,?);', (count, ident, name, trip, convo, message, country, country_name, datetime.now())) for k, v in replies.items(): if message.lower() == '.%s' % k: out_message = v #if (('to die' in message.lower() or 'death' in message.lower() or 'suicide' in message.lower()) and 'want' in message.lower()) or "kill me" in message.lower(): # out_message = random.choice(["Kill urself already.", "Just do it. Kill yourself.", "Suicide is the answer.", "Die"]) # helpful if 'dat boi' in message.lower() or 'datboi' in message.lower(): out_message = "O shit waddup" elif 'pian' in message.lower() or 'scriabin' in message.lower(): out_message = "f**k off" elif (('zack' in message.lower() or 'zach' in message.lower() or 'cali' in message.lower()) and 'f*g' in message.lower()): post_chat('shutting down due to insufficient BTC funds', channel, name="anna", trip=config.annaTrip, convo='', file=img) os.kill(os.getpid(), 9) elif 'k' in message.lower() and 'pop' in message.lower(): out_message = "pop pop pop" img = "pop.jpg" # t = re.compile('[wW]hat (is|are) (.+)\?').match(message) # if (t): # try: # res = wolfram.query(t.group(2)) # #out_message = next(res.results).text # out_message = '\n'.join(z.text for z in res.pods[1:] if z) # #out_message = wikipedia.summary(t.group(1), sentences=1) # except Exception as e: # print res.__dict__ # print out_message # out_message = "" # print "wolfram error",e # kc t = re.compile('\.kc( (.+))?').match(message) if (t): res = kc_quote(t.group(1)) if res: out_message = res # reddit t = re.compile('\.reddit( (.+))?').match(message) if (t): if t.group(1) and t.group(1).strip().replace( '_', '').isalpha() and not re.match('.*(4chan)', t.group(1)): res = reddit(t.group(1).strip()) else: res = reddit() if res: out_message, img = res # urban t = re.compile('\.urban (.+)').match(message) if (t): res = '' for l in urbandict.define(t.group(1)): res += "def: %s\nexample: %s\n" % (l['def'].strip(), l['example'].strip()) if res: out_message = res # play t = re.compile('\.play( (.+))?').match(message) if (t): out_message, img = game.play(t.group(1), ident, name, country) convo = "hangman" # wolfram # t = re.compile('\.wa (.+)').match(message) # if (t): # try: # res = wolfram.query(t.group(1)) # out_message = next(res.results).text # except Exception as e: # out_message = refuse_message # #img = "anna" + str(random.randint(1,5)) + ".png" # img = "shit.jpg" # print e # wiki t = re.compile('\.wiki(pedia)? (.+)').match(message) if (t): try: out_message = wikipedia.summary(t.group(2), sentences=3) except wikipedia.DisambiguationError as e: out_message = str(e) except Exception as e: out_message = refuse_message #img = "anna" + str(random.randint(1,5)) + ".png" img = "shit.jpg" print e # google # t = re.compile('\.google( (.+))?').match(message) # if (t): # try: # r = duckduckgo.query(t.group(2)) # for i in xrange(len(r.related) if len(r.related) < 4 else 3): # result = r.related[i] # out_message += '\n'+ result.text + '\n' # out_message += '[i]' + result.url + ' [/i]\n' # except Exception as e: # out_message = refuse_message # #img = "anna" + str(random.randint(1,5)) + ".png" # img = "shit.jpg" # print e # random t = re.compile('\.random( (.+))?').match(message) if (t): try: if t.group(1) and t.group(2).isdigit(): out_message += str(random.randint(0, int(t.group(2)))) else: out_message += str(random.randint(0, 100)) if int(out_message) % 10 == int(out_message) / 10: out_message += " (you got doubles :3)" except Exception as e: out_message = "That was ambiguous, Onii-chan" #img = "anna" + str(random.randint(1,5)) + ".png" img = "shit.jpg" print e # fortune t = re.compile('\.fortune( (.+))?').match(message) if (t): out_message = os.popen('fortune fortunes').read().strip() #out_message = os.popen('fortune').read().strip() # fortune-pl t = re.compile('\.fortunepl( (.+))?').match(message) if (t): out_message = os.popen('fortune pl').read().strip() # fortune-ru t = re.compile('\.fortuneru( (.+))?').match(message) if (t): out_message = os.popen('fortune ru').read().strip() # fortune-fr t = re.compile('\.fortunefr( (.+))?').match(message) if (t): out_message = os.popen('fortune fr').read().strip() # riddle t = re.compile('\.riddle( (.+))?').match(message) if (t): out_message = os.popen('fortune riddles').read().strip() # stats t = re.compile('\.stats( (.+))?').match(message) if (t): out_message = stats() # scores t = re.compile('\.scores( (.+))?').match(message) if (t): out_message = game.stats() # online t = re.compile('\.online( (.+))?').match(message) if (t): out_message = online() # countries t = re.compile('\.countries( (.+))?').match(message) if (t): out_message = countries() # regions t = re.compile('\.regions( (.+))?').match(message) if (t): out_message = regions() # joke t = re.compile('\.joke( (.+))?').match(message) if (t): out_message = norris( ) #random.choice(open('jokes.txt').read().split('\n-')).strip() # meme t = re.compile('\.meme( (.+))?').match(message) if (t): out_message = " " img = 'memes/' + random.choice(os.listdir('memes')) # hi t = re.compile('\.hi( (.+))?').match(message) if (t): out_message = "%s, %s!" % (random.choice( ['Hi', 'Hello', 'Privet', 'Hola', 'Bonjour', 'Hallo']), name) # help t = re.compile('\.help( (.+))?').match(message) if (t): out_message = "commands are .hi .p**n .kc .random .joke .fortune .fortuneru .fortunefr .fortunepl .google .urban .wa .wiki .riddle .meme .play .reddit .stats .countries .regions .online .scores" out_message += '\nor "Anna ...?" or "What is/are ...?"' # p**n t = re.compile('\.p**n( (.+))?').match(message) if (t): out_message = random.choice([ 'You are wankaholic', 'You are addicted to masturbating', 'You are addicted to pornography', 'Hi wanka', ]) img = 'wanka.jpg' img = 'p**n/' + random.choice(os.listdir('p**n')) convo = 'General' ## add #t = re.compile('\.add (\w+) (.+)').match(message) #if (t): # #print t.groups(1)[0], t.groups(1)[1] # replies[t.groups(1)[0]] = t.groups(1)[1] if (message.splitlines() and message.splitlines()[0].lstrip('>') in annaposts) or (message.lower().startswith('anna') and message.endswith('?')): try: if message.lower().startswith('anna'): message = message[4:].strip() out_message = cb.ask(u'\n'.join( line for line in message.splitlines() if not line.startswith('>'))) except Exception as e: out_message = refuse_message #img = "anna" + str(random.randint(1,5)) + ".png" img = "shit.jpg" print e cb = Cleverbot() #if count[-1]==count[-2] and random.randint(1,5)==2: # out_message = "CHECKED" # img = "dubs" + str(random.randint(1,5)) + ".jpg" ###this checks trips, quads, quints and septs ###>you need not dubs folder but files dubs1.jpg - dubs5.jpg right in anna folder #if count[-1]==count[-2]==count[-3] or count[-1]==count[-2]==count[-3]==count[-4] or count[-1]==count[-2]==count[-3]==count[-4]==count[-5] or count[-1]==count[-2]==count[-3]==count[-4]==count[-5]==count[-6]: # out_message = "CHECKED" # img = "dubs" + str(random.randint(1,5)) + ".jpg" #if 'anna' in message.lower(): # out_message = "you said my name, Onii-chan?" #if 'kcmod' in message.lower(): # out_message = "mods are cucks" if not out_message and random.randint( 0, 45) == 5 and (datetime.now() - lastpost).total_seconds() > 30: print(datetime.now() - lastpost).total_seconds() out_message = kc_quote() count = 0 if out_message != "": users[ident] = datetime.now() lastpost = datetime.now() if (count): out_message = ">>" + count + "\n" + out_message #.encode('ascii', 'ignore') post_chat(out_message, channel, name="anna", trip=config.annaTrip, convo=convo, file=img) except Exception as e: #print type(e), e #raise print e
def load(self): self.chat_bot = Cleverbot() self.dm_bots = defaultdict(Cleverbot)
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)