def add_projects(self, arguments, messageInfo): message = arguments.split(" ") try: name = message[0] language = message[1] link = message[2] message.pop(0) message.pop(0) message.pop(0) description = " ".join(message) except IndexError: ircHelpers.pmInChannel( messageInfo["user"], "Correct usage is: !!addproject [name] [language] [link] [description]" ) return False proj_id = binascii.b2a_hex(os.urandom(3)).decode() proj_dict = { "name": name, "language": language, "link": link, "description": description.strip("\r"), "id": proj_id, } if DB().db_add_data("projects", proj_dict): ircHelpers.pmInChannel(messageInfo["user"], "Added project %s. Thank's for taking part!" % name) ircHelpers.sayInChannel("Added new project: %s" % name) else: ircHelpers.pmInChannel("Error trying to add project %s" % name)
def db_add_data(self, table_name, data): try: if self.db_check_table(table_name): conn = self.db_connect() cur = conn.cursor() table_columns = '' column_data = '' for key in data.keys(): table_columns = table_columns + key + ", " column_data = column_data + "'" + data[key] + "', " table_columns = table_columns[:-2] column_data = column_data[:-2] SQL = "INSERT INTO %s (%s) VALUES(%s);" % ( table_name, table_columns, column_data) cur.execute(SQL) conn.commit() return True else: ircHelpers.sayInChannel("There is no table: %s" % table_name) return False except psycopg2.Error as e: print("!! Error adding data to table: %s" % table_name) print(e) return False finally: try: conn.close() except Exception: pass
def db_update_data( self, table_name, column_name, changed_value, condition_column_name, condition_value, ): try: if self.db_check_table(table_name): conn = self.db_connect() cur = conn.cursor() SQL = "UPDATE " + table_name + " SET " + column_name + " = %s WHERE " + condition_column_name + " = " + condition_value cur.execute(SQL, (changed_value)) conn.commit() return True else: ircHelpers.sayInChannel("There is no table: %s" % table_name) return False except psycopg2.Error as e: print("!! Error updating data in table: %s" % table_name) print(e) return False finally: try: conn.close() except Exception: pass
def add_projects(self, arguments, messageInfo): message = arguments.split(" ") try: name = message[0] language = message[1] link = message[2] message.pop(0) message.pop(0) message.pop(0) description = ' '.join(message) except IndexError: ircHelpers.pmInChannel( messageInfo['user'], "Correct usage is: !!addproject [name] [language] [link] [description]" ) return False proj_id = binascii.b2a_hex(os.urandom(3)).decode() proj_dict = { "name": name, "language": language, "link": link, "description": description.strip("\r"), "id": proj_id } if DB().db_add_data("projects", proj_dict): ircHelpers.pmInChannel( messageInfo['user'], "Added project %s. Thank's for taking part!" % name) ircHelpers.sayInChannel("Added new project: %s" % name) else: ircHelpers.pmInChannel("Error trying to add project %s" % name)
def db_add_data(self,table_name,data): try: if self.db_check_table(table_name): conn = self.db_connect() cur = conn.cursor() table_columns = '' column_data ='' for key in data.keys(): table_columns = table_columns + key + ", " column_data = column_data + "'" + data[key] + "', " table_columns = table_columns[:-2] column_data = column_data[:-2] SQL = "INSERT INTO %s (%s) VALUES(%s);" % (table_name,table_columns,column_data) cur.execute(SQL) conn.commit() return True else: ircHelpers.sayInChannel("There is no table: %s" % table_name) return False except psycopg2.Error as e: print("!! Error adding data to table: %s" % table_name) print(e) return False finally: try: conn.close() except Exception: pass
def delete_projects(self, arguments, messageInfo): if not arguments.strip("\r").strip(): ircHelpers.pmInChannel(messageInfo["user"], "Correct usage is: !!delproject [project_id]") return False if DB().db_delete_data("projects", "id", arguments.strip("\r")): ircHelpers.sayInChannel("Deleted project (if available)") return True else: ircHelpers.sayInChannel("Error trying to delete project") return False
def delete_projects(self, arguments, messageInfo): if not arguments.strip('\r').strip(): ircHelpers.pmInChannel( messageInfo['user'], "Correct usage is: !!delproject [project_id]") return False if DB().db_delete_data("projects", "id", arguments.strip('\r')): ircHelpers.sayInChannel("Deleted project (if available)") return True else: ircHelpers.sayInChannel("Error trying to delete project") return False
def respond_with_subreddit(self, message): potential_reddits = re.compile("(/r/\S+)").findall(message) reddits=[] for reddit in potential_reddits: reddit = reddit.rstrip(string.punctuation) resp = requests.get("http://www.reddit.com"+reddit+"/about.json", headers={ 'User-Agent' : '/r/progether bot' }) try: data = resp.json() if not 'error' in data: reddits.append("http://www.reddit.com"+reddit) else: reddits.append("The subreddit "+reddit+" doesn't exist") except: reddits.append("The subreddit "+reddit+" doesn't exist") ircHelpers.sayInChannel(', '.join(reddits))
def respond_with_subreddit(self, message): potential_reddits = re.compile("(/r/\S+)").findall(message) reddits = [] for reddit in potential_reddits: reddit = reddit.rstrip(string.punctuation) resp = requests.get("http://www.reddit.com" + reddit + "/about.json", headers={'User-Agent': '/r/progether bot'}) try: data = resp.json() if not 'error' in data: reddits.append("http://www.reddit.com" + reddit) else: reddits.append("The subreddit " + reddit + " doesn't exist") except: reddits.append("The subreddit " + reddit + " doesn't exist") ircHelpers.sayInChannel(', '.join(reddits))
def db_drop_table(self,table_name): try: if self.db_check_table(table_name): conn = self.db_connect() cur = conn.cursor() SQL = "DROP TABLE IF EXISTS %s" % table_name cur.execute(SQL) conn.commit() return True else: ircHelpers.sayInChannel("There is no table: %s" % table_name) return False except psycopg2.Error as e: print("!! Error dropping table: %s" % table_name) print(e) return False finally: try: conn.close() except Exception: pass
def db_delete_data(self,table_name,condition_column_name,condition_value): try: if self.db_check_table(table_name): conn = self.db_connect() cur = conn.cursor() SQL = "DELETE FROM %s WHERE %s = '%s'" % (table_name,condition_column_name,condition_value) cur.execute(SQL) conn.commit() return True else: ircHelpers.sayInChannel("There is no table: %s" % table_name) return False except psycopg2.Error as e: print("!! Error deleting data from table: %s" % table_name) print(e) return False finally: try: conn.close() except Exception: pass
def db_drop_table(self, table_name): try: if self.db_check_table(table_name): conn = self.db_connect() cur = conn.cursor() SQL = "DROP TABLE IF EXISTS %s" % table_name cur.execute(SQL) conn.commit() return True else: ircHelpers.sayInChannel("There is no table: %s" % table_name) return False except psycopg2.Error as e: print("!! Error dropping table: %s" % table_name) print(e) return False finally: try: conn.close() except Exception: pass
def db_update_data(self,table_name,column_name,changed_value,condition_column_name,condition_value,): try: if self.db_check_table(table_name): conn = self.db_connect() cur = conn.cursor() SQL = "UPDATE "+table_name+" SET "+column_name+" = %s WHERE "+condition_column_name+" = "+condition_value cur.execute(SQL, (changed_value)) conn.commit() return True else: ircHelpers.sayInChannel("There is no table: %s" % table_name) return False except psycopg2.Error as e: print("!! Error updating data in table: %s" % table_name) print(e) return False finally: try: conn.close() except Exception: pass
def list_projects(self, arguments, messageInfo): user = messageInfo["user"] if not DB().db_check_table("projects"): DB().db_add_table("projects", "name text, language text, link text, description text, id text") if arguments: data = DB().db_get_data("projects", "language", arguments.replace("\r", "")) else: data = DB().db_get_all_data("projects") if data == None: ircHelpers.pmInChannel(user, "Error while trying to retrieve Projects") if len(data) == 0: ircHelpers.pmInChannel(user, "There are no listed projects") else: max_name = len("name") max_lang = len("language") max_desc = len("description") max_link = 0 for proj_tuple in data: if len(proj_tuple[1]) > max_lang: max_lang = len(proj_tuple[1]) if len(proj_tuple[0]) > max_name: max_name = len(proj_tuple[0]) if len(proj_tuple[3]) > max_desc: max_desc = len(proj_tuple[3]) if len(proj_tuple[2]) > max_link: max_link = len(proj_tuple[2]) title_row = "(%s) %s [[ %s ]] %s (( %s ))" % ( " id ", "language".ljust(max_lang), "name".ljust(max_name), "description".ljust(max_desc), " link".ljust(max_link), ) ircHelpers.sayInChannel(title_row) ircHelpers.sayInChannel("-" * len(title_row)) for proj_tuple in data: ircHelpers.sayInChannel( # (id) lang [[ name ]] desc << link >> "(%s) %s [[ %s ]] %s (( %s ))" % ( proj_tuple[4], # id proj_tuple[1].ljust(max_lang), # lang proj_tuple[0].ljust(max_name), # name proj_tuple[3].ljust(max_desc), # desc proj_tuple[2].ljust(max_link), ) ) # link
def list_projects(self, arguments, messageInfo): user = messageInfo['user'] if not DB().db_check_table("projects"): DB().db_add_table( "projects", "name text, language text, link text, description text, id text" ) if (arguments): data = DB().db_get_data("projects", "language", arguments.replace('\r', '')) else: data = DB().db_get_all_data("projects") if data == None: ircHelpers.pmInChannel(user, "Error while trying to retrieve Projects") if len(data) == 0: ircHelpers.pmInChannel(user, "There are no listed projects") else: max_name = len("name") max_lang = len("language") max_desc = len("description") max_link = 0 for proj_tuple in data: if len(proj_tuple[1]) > max_lang: max_lang = len(proj_tuple[1]) if len(proj_tuple[0]) > max_name: max_name = len(proj_tuple[0]) if len(proj_tuple[3]) > max_desc: max_desc = len(proj_tuple[3]) if len(proj_tuple[2]) > max_link: max_link = len(proj_tuple[2]) title_row = "(%s) %s [[ %s ]] %s (( %s ))" % ( " id ", "language".ljust(max_lang), "name".ljust(max_name), "description".ljust(max_desc), " link".ljust(max_link)) ircHelpers.sayInChannel(title_row) ircHelpers.sayInChannel('-' * len(title_row)) for proj_tuple in data: ircHelpers.sayInChannel( #(id) lang [[ name ]] desc << link >> "(%s) %s [[ %s ]] %s (( %s ))" % ( proj_tuple[4], # id proj_tuple[1].ljust(max_lang), # lang proj_tuple[0].ljust(max_name), # name proj_tuple[3].ljust(max_desc), # desc proj_tuple[2].ljust(max_link))) # link
def delete_data(self, arguments, messageInfo): # table_name, name of column to determine deletion, column value, type of condition to match (= or LIKE) # makes DELETE FROM test where name = 'test1' DB().db_delete_data("test","name","test1") ircHelpers.sayInChannel("Deleted data")
def perform(self, data): match = self.regex.match(data) if match: if match.group('user') != ircHelpers.getNick(): ircHelpers.sayInChannel('Hello %s!' % match.group('user'))
def delete_data(self, arguments, messageInfo): # table_name, name of column to determine deletion, column value, type of condition to match (= or LIKE) # makes DELETE FROM test where name = 'test1' DB().db_delete_data("test", "name", "test1") ircHelpers.sayInChannel("Deleted data")
def drop_table(self, arguments, messageInfo): # table_name DB().db_drop_table("test") ircHelpers.sayInChannel("Dropped table")
def speak(self, arguments, messageInfo): ircHelpers.sayInChannel(arguments)
def irc(self, arguments, messageInfo): ircHelpers.sayInChannel("server: irc.freenode.net, channel: #reddit-progether")
def wiki(self, arguments, messageInfo): ircHelpers.sayInChannel("http://www.reddit.com/r/progether/wiki/index")
def add_data_to_table(self, arguments, messageInfo): dict = {"name": "test1", "details": "sample_details"} # table_name, dict of column name and column value DB().db_add_data("test", dict) ircHelpers.sayInChannel("Wrote data to table")
def sayHello(self, data): match = self.regex.match(data) if match: if match.group('user') != ircHelpers.getNick(): ircHelpers.sayInChannel('Hello %s!' % match.group('user'))
def lastMessage(self, arguments, messageInfo): ircHelpers.sayInChannel( '%s said %s' % (self.chatLog[-1]['user'], self.chatLog[-1]['message']))
def sayHello(self, user): if user != ircHelpers.getNick(): ircHelpers.sayInChannel("Hello %s! If you're new, try !!help" % user)
def update_data(self, arguments, messageInfo): # table_name, name of column to change, column value, name of column to determine change, column value, = or LIKE # makes UPDATE test SET name = 'test2' WHERE name = 'test1' DB().db_update_data("test","name","test2","name","test1") ircHelpers.sayInChannel("Updated data")
def mainLoop(self): import ircHelpers # dirty hack - should be moved somewhere more applicable (ie at !!nick) ircHelpers.start_queue_thread() while True: receivedData = self.socket.recv(self.tempCacheSize).decode("UTF-8") messageInfo = dict() if (self.logAllToConsole): print("-- %s" % receivedData.encode('utf-8')) isError = self.regexIsError.match(receivedData) if isError: self.logError("CAUGHT ERROR ::> " +receivedData) self.logError("Quitting") return 1 isNickInUse = self.regexIsNickInUse.match(receivedData) if isNickInUse: ircHelpers.sayInChannel("Nick is already in use") isChat = self.regexIsChat.match(receivedData) if isChat: # parse message messageInfo['user'] = isChat.group('user') messageInfo['isp'] = isChat.group('isp') messageInfo['channel'] = isChat.group('channel') messageInfo['message'] = isChat.group('message') # if it is a command, find addon and execute command isCommand = self.regexIsCommand.match(messageInfo['message']) if isCommand: split = self.regexCommandSplitCommand.match(messageInfo['message']) commandName = split.group('command') commandArguments = split.group('arguments') isAddon = False for addon in self.addonList: if commandName in addon.commandList: addon.commandList[commandName](commandArguments, messageInfo) isAddon = True if not isAddon and self.respondToNotFound: string = "NOTICE %s :I don't know that command\r\n" % (messageInfo['user']) self.socket.send(string.encode('UTF-8')) elif messageInfo['channel'] == self.channel: for addon in self.addonList: for messageMethod in addon.messageList: messageMethod(messageInfo) # if new join, greet isJoin = self.regexIsJoin.match(receivedData) if isJoin: for addon in self.addonList: for joinMethod in addon.joinList: joinMethod(isJoin.group('user')) # if user leaves channel, update their database info isQuit = self.regexIsQuit.match(receivedData) if isQuit: for addon in self.addonList: for quitMethod in addon.quitList: quitMethod(isQuit.group('user')) #make sure we don't time out of server if receivedData.find('PING') != -1: string = 'PONG %s \r\n' % receivedData.split()[1] self.socket.send(string.encode("UTF-8")) else: # moved log here to filter out ping/pong chatter self.logIncomming(receivedData.encode('utf-8'))
def create_test_table(self, arguments, messageInfo): # table name, column name and column type DB().db_add_table("test", "name text, details text") ircHelpers.sayInChannel("Created table")
def lastMessage(self, arguments, messageInfo): ircHelpers.sayInChannel('%s said %s' % (self.chatLog[-1]['user'], self.chatLog[-1]['message']))
def help(self, arguments, messageInfo): ircHelpers.sayInChannel("Welcome to progether! There may not always be a lot of activity here, just stick around. Someone will pop up. To experiment with the bot, try these commands: !!irc, !!reddit, !!wiki. Some future commands deal with chatlogs and in-channel mail.")
def irc(self, arguments, messageInfo): ircHelpers.sayInChannel( "server: irc.freenode.net, channel: #reddit-progether")
def reddit(self, arguments, messageInfo): ircHelpers.sayInChannel("http://reddit.com/r/progether/")
def mainLoop(self): while True: receivedData = self.socket.recv(self.tempCacheSize).decode("UTF-8") messageInfo = dict() if (self.logAllToConsole): print("-- %s" % receivedData.encode('utf-8')) isError = self.regexIsError.match(receivedData) if isError: self.logError("CAUGHT ERROR ::> " + receivedData) self.logError("Quitting") return 1 isNickInUse = self.regexIsNickInUse.match(receivedData) if isNickInUse: import ircHelpers # dirty hack - should be moved somewhere more applicable (ie at !!nick) ircHelpers.sayInChannel("Nick is already in use") isChat = self.regexIsChat.match(receivedData) if isChat: # parse message messageInfo['user'] = isChat.group('user') messageInfo['isp'] = isChat.group('isp') messageInfo['channel'] = isChat.group('channel') messageInfo['message'] = isChat.group('message') # if it is a command, find addon and execute command isCommand = self.regexIsCommand.match(messageInfo['message']) if isCommand: split = self.regexCommandSplitCommand.match( messageInfo['message']) commandName = split.group('command') commandArguments = split.group('arguments') isAddon = False for addon in self.addonList: if commandName in addon.commandList: addon.commandList[commandName](commandArguments, messageInfo) isAddon = True if not isAddon and self.respondToNotFound: string = "NOTICE %s :I don't know that command\r\n" % ( messageInfo['user']) self.socket.send(string.encode('UTF-8')) elif messageInfo['channel'] == self.channel: for addon in self.addonList: for messageMethod in addon.messageList: messageMethod(messageInfo) # if new join, greet isJoin = self.regexIsJoin.match(receivedData) if isJoin: for addon in self.addonList: for joinMethod in addon.joinList: joinMethod(isJoin.group('user')) # if user leaves channel, update their database info isQuit = self.regexIsQuit.match(receivedData) if isQuit: for addon in self.addonList: for quitMethod in addon.quitList: quitMethod(isQuit.group('user')) #make sure we don't time out of server if receivedData.find('PING') != -1: string = 'PONG %s \r\n' % receivedData.split()[1] self.socket.send(string.encode("UTF-8")) else: # moved log here to filter out ping/pong chatter self.logIncomming(receivedData.encode('utf-8'))
def update_data(self, arguments, messageInfo): # table_name, name of column to change, column value, name of column to determine change, column value, = or LIKE # makes UPDATE test SET name = 'test2' WHERE name = 'test1' DB().db_update_data("test", "name", "test2", "name", "test1") ircHelpers.sayInChannel("Updated data")
def add_data_to_table(self, arguments, messageInfo): dict = { "name" : "test1", "details" : "sample_details" } # table_name, dict of column name and column value DB().db_add_data("test", dict) ircHelpers.sayInChannel("Wrote data to table")