import irc.bot from rake_nltk import Rake import random from nltk.tokenize import sent_tokenize, word_tokenize import json #from thread import start_new_thread import os r = Rake() def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] class HelloBot(irc.bot.SingleServerIRCBot): def __init__(self, channel, nickname, server, port=6667, index=None): print("connecting to chatroom...") irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname) self.channel = channel self.index = index def on_welcome(self, c, e): c.join(self.channel) print("joined chatroom") def on_privmsg(self, c, e): pass def on_pubmsg(self, c, e): print(e.arguments, e.source) msg=e.arguments[0] print(e.source.split("!")[0][:1]) incoming_msg = e.arguments[0] r.extract_keywords_from_text(msg) listOfKeys = r.get_ranked_phrases() msg_where = "" if e.source.split("!")[0][-3:] != "bot" or e.source.split("!")[0][:1] != "A": print("true") for keyWord in listOfKeys: if keyWord in self.index: msg = (index.get(keyWord)[0].get('sentence')) msg_where = "I found this in {}".format(index.get(keyWord)[0].get('filename')) else: msg = "I don't know anything about that" msg_where = "" for chunk in chunks(msg, 400): print(chunk) c.privmsg(self.channel, chunk) else: print("bot") if __name__ == "__main__": import argparse import sys ap = argparse.ArgumentParser("IRC Bot") ap.add_argument("--server", default="irc.freenode.net") ap.add_argument("--port", type=int, default=6667) ap.add_argument("--channel", default="#pzi") ap.add_argument("--nickname", default="scanbot") ap.add_argument("--text", nargs="+", help="database to use", default="index.json") args=ap.parse_args() # build the index of sentences organized by keywords with open("src/index.json") as f: try: index = json.load(f) except: print("I can't work with no knowledge") sys.exit() myhost = os.uname()[1] bot = HelloBot(args.channel, "A-2{}-bot".format(len(index)), args.server, args.port, index) bot.start()