Example #1
0
def notice(s, sender, ident, host, channel, text):

    displayNotice(sender, text)

    authd = meta.isAuthor(sender, ident, host)
    text = text.lower()

    if text == "+logmsg" and authd:
        if meta.conf["logmsg"]:
            meta.sendNotice(s, sender, "Confirm - Logging is already On.")
        else:
            meta.sendNotice(s, sender, "Confirm - Logging is now On.")
        meta.conf["logmsg"] = True

    elif text == "-logmsg" and authd:
        if meta.conf["logmsg"]:
            meta.sendNotice(s, sender, "Confirm - Logging is now Off.")
        else:
            meta.sendNotice(s, sender, "Confirm - Logging is already Off.")
        meta.conf["logmsg"] = False

    elif text == "mode?":
        if meta.conf["logmsg"]:
            meta.sendNotice(s, sender, "Mode: Logging is On.")
        else:
            meta.sendNotice(s, sender, "Mode: Logging is Off.")
Example #2
0
def notice(s, nick, ident, host, sender, text):
	
	
	authd = meta.isAuthor(nick, ident, host)
	
	textLower = text.lower()
	
		
	if textLower[:11] == '+greetchan ' and authd:
		chan = text[11:]
		if chan.lower() in meta.conf['greetchan']:
			meta.sendNotice(s, nick, "Confirm - %s already being greeted."%chan)
		else:
			meta.conf['greetchan'][chan.lower()] = chan
			meta.sendNotice(s, nick, "Confirm - Now greeting %s."%chan)
		return False
	
		
	elif textLower[:11] == '-greetchan ' and authd:
		chan = text[11:]
		if chan.lower() in meta.conf['greetchan']:
			del meta.conf['greetchan'][chan.lower()]
			meta.sendNotice(s, nick, "Confirm - No longer greeting %s."%chan)
		else:
			meta.sendNotice(s, nick, "Confirm - %s was never being greeted."%chan)
		return False
		
	elif textLower[:6] == '+greet' and authd:
		meta.sendNotice(s, nick, "Confirm - Greet is On.")
		meta.conf['greet'] = True
		return False
		
	elif textLower[:6] == '-greet' and authd:
		meta.sendNotice(s, nick, "Confirm - Greet is Off.")
		meta.conf['greet'] = False
		return False
		
	elif textLower == 'mode?':
		if meta.conf['greet']:
			meta.sendNotice(s, nick, "Mode: Greeting is On.")
		else:
			meta.sendNotice(s, nick, "Mode: Greeting is Off.")
		meta.sendNotice(s, nick, "Greeting channels: %s"%repr(meta.conf['greetchan']))
Example #3
0
def notice(s, nick, ident, host, sender, text):
	
	
	authd = meta.isAuthor(nick, ident, host)
	
	textLower = text.lower()
	
		
	if textLower[:7] == 'say to ' and authd:
		meta.conf['talkto'] = textLower[7:]
		return False
		
	elif textLower[:4] == 'say ' and authd:
		meta.sendMsg(s, meta.conf['talkto'], text[4:])
		return False
		
	elif textLower[:4] == 'act ' and authd:
		meta.sendMsg(s, meta.conf['talkto'], "\001ACTION %s\001" % text[4:])
		return False
		
	elif textLower == '+talk' and authd:
		if meta.conf['talk']:
			meta.sendNotice(s, nick, "Confirm - Talking is already On.")
		else:
			meta.sendNotice(s, nick, "Confirm - Talking is now On.")
			meta.conf['talk'] = True
		return False
		
	elif textLower == '-talk' and authd:
		if meta.conf['talk']:
			meta.sendNotice(s, nick, "Confirm - Talking is already Off.")
		else:
			meta.sendNotice(s, nick, "Confirm - Talking is now Off.")
			meta.conf['talk'] = False
		return False
		
	elif textLower == 'mode?':
		if meta.conf['talk']:
			meta.sendNotice(s, nick, "Mode: Talking is On.")
		else:
			meta.sendNotice(s, nick, "Mode: Talking is Off.")
Example #4
0
def msg(s, nick, ident, host, channel, text):
	global conn, cur, channels
	
	if not meta.conf['bucket']:
		return True
	
	## Dont talk to yourself
	if nick == meta.conf['nick']:
		return True
	
	
	## dont talk to strange people 
	if nick in meta.conf['ignore'] or host in meta.conf['ignorehost']:
		return False
	
	
	inchannel = True
	
	if channel == meta.conf['nick']:
		channel = nick
		inchannel = False
	
	
	
	if channel not in channels:
		channels[channel] = {"lastFactoidId": 0,
							 "lastCreatedId": 0, 
							 "shutup": 0}
		
	elif channels[channel]["shutup"] > time.time():
		return True
	
	
	
	
	#/me did stuff - "\001ACTION did stuff\001"
	text = text.rstrip("\001")
	textLower = text.lower()
	factoidList = []
	
	
	
	
	if re.match(r"wally[,:] ", textLower) or \
		(channel in meta.LOUD and re.match(r"bio?t?ch[,:] ", text, re.I)):
		textLower = textLower[7 :].strip()
		unknownCommand = True
		
		
		
		###
		### chattiness
		###  - Set Chattiness level
		###
		if re.match(r"chatt?[iy]ness \d+[?!.]*$", textLower):
			
			clevel = int(re.match(r"chatt?[iy]ness (\d+)[?!.]*$", textLower).group(1))
			meta.conf['chattiness'] = (clevel>20) and 20 or clevel
			
			print("Setting chattiness level to", meta.conf['chattiness'])
			
			meta.sendMsg(s, channel, "%s, chattiness set to %s" % (nick, meta.conf['chattiness']))
			return True
		
		
		###
		### chattiness
		###  - Return chattiness level
		###
		elif re.match(r"chatt?[iy]ness[?!.]*$", textLower):
			meta.sendMsg(s, channel, "%s, chattiness is %s" % (nick, meta.conf['chattiness']))
			return True
		
		###
		### forget that
		###  - forget the last said factoid
		###
		elif re.match(r"(f[eiou]r?g[ei]t|undo) ((th|d)at|[#]?[0-9]+)[?!.]*$", textLower):
		
			# prevent forget spamming
			foiled = foilCheckForgets(nick, ident, host, channel)
			
			if foiled:
				meta.sendMsg(s, channel, foiled)
				return False
			
			
			#undo the last factoid
			word, reference = re.match(r"(f[eiou]r?g[ei]t|undo) ((th|d)at|[#]?[0-9]+)", textLower).group(1,2)
			
			#if not canDelete(nick, ident, host):
			#	meta.sendMsg(s, channel, "I can't let you do that %s." % nick)
			#	return False
			
			
			if reference == "that" or reference == "dat":
				if word == "undo":
					id = channels[channel]['lastCreatedId']
					channels[channel]['lastCreatedId'] = 0
					
					if id == channels[channel]['lastFactoidId']:
						channels[channel]['lastFactoidId'] = 0
						
				else: #forget
					id = channels[channel]['lastFactoidId']
					channels[channel]['lastFactoidId'] = 0
					
				if not id:
					meta.sendMsg(s, channel, "%s, %s what?" % (nick, word))
					return False
			else:
				#they used a factoid id
				reference = int(reference.lstrip('#'))
				id = reference
				
				if channels[channel]['lastFactoidId'] == id:
					channels[channel]['lastFactoidId'] = 0
				if channels[channel]['lastCreatedId'] == id:
					channels[channel]['lastCreatedId'] = 0
				
			
			
			
			cur.execute("""SELECT * FROM `factoids` WHERE `id`=? LIMIT 1""", (id,))
			conn.commit()
			
			res = cur.fetchone()
			
			if not res:
				meta.sendMsg(s, channel, "%s, that factoid doesn't exist." % nick)
				return False
			
			#if cur.fetchone()[0] == "0" and not (meta.isOp(channel, nick) or meta.isProtected(channel, nick)):
			if res[6] == "0":# and not (meta.isOp(channel, nick) or meta.isProtected(channel, nick)):
				
				meta.sendMsg(s, channel, "I can't let you do that %s." % nick)
				return False
			
			print("<<<", nick, "erased", id)
			
			
			cur.execute("""INSERT INTO 
				`del_factoids`	(`inkling`, `find`, `verb`, `tidbit`, `nick`, `editable`, `last_said`, `del_id`, `del_time`, `del_nick`, `del_ident`, `del_host`, `del_channel`) 
				VALUES		( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", 
				( res[1], res[2], res[3], res[4], res[5], res[6], res[7], id, time.time(), nick, ident, host, channel ))
			cur.execute("""DELETE FROM `factoids` WHERE `id`=?""", (id,))
			conn.commit()
			
			# add spam protection entry
			foilAddForget(nick, ident, host, channel, id)
			
			meta.sendMsg(s, channel, "Ok %s" % nick)
			return False
			
		###
		### ls
		###  - list (deleted) factoids
		###
		## TODO: add check for -v
		## TODO: add check for -d or -del
		elif re.match(r"ls.*$", textLower):
			
			## only authorized people can list factoids
			if not meta.isAuthor(nick, ident, host):
				meta.sendMsg(s, channel, "I'm afraid I can't let you do that %s" % (nick,))
				return False
				
			verbose = False
			deleted = False
			
			args = textLower[2:].split()
			
			if "-h" in args or "-help" in args or "--help" in args:
				meta.sendMsg(s, channel, "ls [-d] [-v] [-h]")
				meta.sendMsg(s, channel, "::   -d   Show deleted factoids (-del | --deleted)")
				meta.sendMsg(s, channel, "::   -v   Show every bit of info on each factoid (--verbose)")
				meta.sendMsg(s, channel, "::   -h   Display this help page (--help)")
				
				return False
				
			if "-v" in args or "--verbose" in args:
				verbose = True
				
			if "-d" in args or "-del" in args or "--deleted" in args:
				deleted = True
			
			if deleted:
				cur.execute("""SELECT * FROM `del_factoids` ORDER BY `id` DESC LIMIT 10""")
			else:
				cur.execute("""SELECT * FROM `factoids` ORDER BY `id` DESC LIMIT 10""")
			
			
			factoids = cur.fetchall()
			
			if deleted and not verbose:
				oShit = "{id}: {find} {verb} {reply} (Del: {deltime} {deleter})"
			elif deleted: # and verbose
				oShit = "{id}: {find} ({inkling}) {verb} {reply} :{creator} (Del:{delid} {deltime}:{delchan} {deleter}!{delident}@{delhost})"
			elif not deleted and not verbose: # normal
				oShit = "{id}: {find} {verb} {reply} :{creator}"
			else: # verbose normal factoids
				oShit = "{id}: {find} ({inkling}) {verb} {reply} :{creator} {lastsaid}"
				
			for res in factoids:
				meta.sendMsg(s, channel, oShit.format( \
					id = res[0], \
					inkling = res[1], \
					find = res[2], \
					verb = res[3], \
					reply = res[4], \
					creator = res[5], \
					editable = res[6], \
					lastsaid = res[7], \
					explicit = res[8], \
					delid = deleted and res[9] or "", \
					deltime = deleted and res[10] or "", \
					deleter = deleted and res[11] or "", \
					delident = deleted and res[12] or "", \
					delhost = deleted and res[13] or "", \
					delchan = deleted and res[14] or ""))
			return False
		
		
		###
		### un delete factoid
		###    unforget [id]|[deleter] [after]
		###
		elif re.match(r"unforget (?:(\d+)|(\S+)\s+(\d\d-\d\d-\d\d\d\d))[?!.]*$", textLower):
			
			r = re.match(r"unforget (?:(\d+)|(\S+)\s+(\d\d-\d\d-\d\d\d\d))[?!.]*$", text[7 :], re.I)
			(id, deleter, since) = r.groups()
			
			
			### Specific ID given. Recover one factoid from deletion.
			if id:
				cur.execute("""SELECT * FROM `del_factoids` WHERE `del_id`=? LIMIT 1""", (id,))
				conn.commit()
				res = cur.fetchone()
				if not res:
					meta.sendMsg(s, channel, "%s, I can not find any deleted factoid with that ID" % nick)
					return False
					
				"""
				0	`id` INTEGER PRIMARY KEY, 
				1	`inkling` TEXT NOT NULL, 
				2	`find` TEXT NOT NULL, 
				3	`verb` VARCHAR(32) NOT NULL, 
				4	`tidbit` TEXT NOT NULL, 
				5	`nick` VARCHAR(32) NOT NULL, 
				6	`editable` INTEGER(1) NOT NULL DEFAULT 1,
				7	`last_said` INTEGER NOT NULL DEFAULT 0,
				8	`explicit` INTEGER(1) NOT NULL DEFAULT 0,
				9	`del_id` INTEGER NOT NULL DEFAULT 0,
				10	`del_time` INTEGER NOT NULL DEFAULT 0
				11	`del_nick` VARCHAR(32) NOT NULL, 
				12	`del_ident` VARCHAR(32) NOT NULL, 
				13	`del_host` VARCHAR(128) NOT NULL, 
				14	`del_channel` VARCHAR(64) NOT NULL)"""
				
				cur.execute("""INSERT INTO 
							`factoids`	(`inkling`, `find`, `verb`, `tidbit`, `nick`, `editable`, `last_said`, `explicit`) 
							VALUES		(    ?,       ?,      ?,       ?,       ?,       ?,           ?,          ?)
						""",            ( res[1],   res[2],   res[3],   res[4],   res[5],  res[6],   time.time(),    res[8]))
						
				channels[channel]['lastCreatedId'] = cur.lastrowid
				channels[channel]['lastFactoidId'] = cur.lastrowid
				
				meta.sendMsg(s, channel, "Factoid Recovered - %s: %s %s %s :: by:%s del:%s" % (cur.lastrowid, res[2], res[3], res[4], res[5], res[11]))
				
				conn.commit()
				
				cur.execute("""DELETE FROM `del_factoids` WHERE `id`=?""", (id,))
				conn.commit()
				
				return False
			
			
			if not meta.isAuthor(nick, ident, host):
				meta.sendMsg(s, channel, "I'm afraid I can't let you do that, %s" % (nick,))
				return False
			
			### No specific id given. Go by deleter and date to recover multiple
			
			since = time.mktime(time.strptime(since,"%m-%d-%Y"))
			
			cur.execute("""SELECT * FROM `del_factoids` WHERE `del_nick` = ? AND `del_time` >= ?""", (deleter, since))
			conn.commit()
			
			dels = cur.fetchall()
			
			for res in dels:
				cur.execute("""INSERT INTO 
							`factoids`	(`inkling`, `find`, `verb`, `tidbit`, `nick`, `editable`, `last_said`, `explicit`) 
							VALUES		(    ?,       ?,      ?,       ?,       ?,       ?,           ?,          ?)
						""",            ( res[1],   res[2],   res[3],   res[4],   res[5],  res[6],   time.time(),  res[8]))
						
				#channels[channel]['lastCreatedId'] = cur.lastrowid
				#channels[channel]['lastFactoidId'] = cur.lastrowid
				
				#meta.sendMsg(s, channel, "Factoid Recovered - %s: %s %s %s :: by:%s del:%s" % (cur.lastrowid, res[2], res[3], res[4], res[5], res[11]))
				
				conn.commit()
				
				cur.execute("""DELETE FROM `del_factoids` WHERE `id`=?""", (res[0],))
				conn.commit()
				
				#res = cur.fetchone()
			
			meta.sendMsg(s, channel, "%d Factoids Recovered" % (len(dels),))
			return False
			
			
			
		###
		### what was that
		###  - get information about last said factoid
		###
		elif re.match(r"wh?at (was|were) (th|d)at[?!.]*$", textLower):
			#spout info about the last factoid
			if not channels[channel]['lastFactoidId']:
				meta.sendMsg(s, channel, "%s: What was what?" % nick)
				return False
				
			#meta.sendMsg(s, channel, "%s, That was factoid %d " % (nick, channels[channel]['lastFactoidId']))
			#return False
			
			id = channels[channel]['lastFactoidId']
			cur.execute("""SELECT * FROM `factoids` WHERE `id`=? LIMIT 1""", (id,))
			conn.commit()
			data = cur.fetchone()
			
			if not data:
				meta.sendMsg(s, channel, "%s, idk..." % nick)
				return False
			
			channels[channel]['lastFactoidId'] = int(data[0])
			
			#if data[6] == 1: editable = ""
			#else: editable = "!Not Editable!"
			
			meta.sendMsg(s, channel, "That was %s: %s %s %s :%s"
				% (data[0], data[2], data[3], data[4], data[5]))
				
			return False
			
		###
		### who made that
		###  - get information about the last factoid
		###
		elif re.match(r"who made ((th|d)at|[#]?[0-9]+)[?!.]*$", textLower):
			#spout info about the last factoid
			if not channels[channel]['lastFactoidId']:
				meta.sendMsg(s, channel, "%s: Who made what?" % nick)
				return False
			
			cur.execute("""SELECT `nick` FROM `factoids` WHERE `id`=? LIMIT 1""", (channels[channel]['lastFactoidId'],))
			conn.commit()
			who = cur.fetchone()
			if who:
				who = who[0]
				if who == nick:
					who = "you"
				meta.sendMsg(s, channel, "%s, %s made factoid %d " % (nick, who, channels[channel]['lastFactoidId']))
			else:
				meta.sendMsg(s, channel, "%s, idk..." % nick)
				
			return False
			
			
			
			
			
		###
		### mark that explicit
		###  - dont say a specific factoid in mixed company
		###
		elif re.match(r"(un)?mark (that|#?(\d+))( as)? explicit[?!.]*$", textLower):
			#only ops and above can do that
			if not (meta.isOp(channel, nick) or meta.isProtected(channel, nick)):
				meta.sendMsg(s, channel, "I can't let you do that %s." % nick)
				return False
			
			un, what, id = re.match(r"(un)?mark (that|#?(\d+))( as)? explicit[?!.]*$", textLower).group(1,2,3)
			
			if what == "that":
				id = channels[channel]['lastFactoidId']
			else:
				id = int(id)
			
			if not id:
				meta.sendMsg(s, channel, "%s: mark what?" % nick)
				return False
			
			
			res = cur.execute("""UPDATE `factoids` SET `explicit`=? WHERE `id`=?""",
					(int(not bool(un)), id))
			conn.commit()
			
			if res:
				meta.sendMsg(s, channel, "%s, done.." % nick)
			else:
				meta.sendMsg(s, channel, "%s, tried, couldn't do it." % nick)
			
			return False
			
			
			
			
		###
		### shut up
		###  - silence wally for a while (10 minutes) [see below for more]
		###
		elif re.match(r"shut (up|it) f[ouei]r a[ ]wh+ile[?!.]*$", textLower):
			channels[channel]['shutup'] = time.time() + 600
			meta.sendMsg(s, channel, "Ok %s, be back in 10 minutes." % nick)
			return False
		
		###
		### shut up
		###  - silence wally for a set amount of time [see below for more]
		###
		#elif re.match(r"shut (up|it) f[ouei]r (0-9)(m[in]|s[ec]|h|hour[s]|y|year[s])[?!.]*$", textLower):
		#	#channels[channel]['shutup'] = time.time() + 600
		#	#meta.sendMsg(s, channel, "Ok %s, be back in 10 minutes." % nick)
		#	return False
			
		###
		### shut up
		###  - silence wally for 2 minutes
		###
		elif re.match(r"shut (up|it)[?!.]*$", textLower):
			channels[channel]['shutup'] = time.time() + 120
			meta.sendMsg(s, channel, "Ok %s, be back in 2 minutes." % nick)
			return False
		
		###
		### count
		###  - count and return the factiods in his arsenal
		###
		elif re.match(r"count$", textLower):
			cur.execute("""SELECT COUNT(*) FROM `factoids`""")
			conn.commit()
			count = cur.fetchone()[0]
			
			meta.sendMsg(s, channel, "I have %s factoids." % count)
			#print("wally has", count, "factoids")
			return False
		
		###
		### factoid 666
		###  - recall and vomit a specific factoid
		###
		elif re.match(r"factoid [#]?[0-9]+$", textLower):
			id = int(re.match(r"factoid [#]?([0-9]+)", textLower).group(1))
			
			cur.execute("""SELECT * FROM `factoids` WHERE `id`=? LIMIT 1""", (id,))
			conn.commit()
			data = cur.fetchone()
			
			if not data:
				meta.sendMsg(s, channel, "%s, that factoid doesn't exist." % nick)
				return False
			
			channels[channel]['lastFactoidId'] = int(data[0])
			
			if data[6] == 1: editable = ""
			else: editable = "!Not Editable!"
			
			meta.sendMsg(s, channel, "Factoid %s: %s \003| %s \003| %s \003:%s \003%s"
				% (data[0], data[2], data[3], data[4], data[5], editable))
			
			
			return False
		
		###
		### search
		###  - search factoids via keywords
		###
		## TODO: add -del option for deleted factoids
		## TODO: add clause to search in 'replies' as well as 'finds'
		elif re.match(r"search([\s]?[\(\[\{]?[0-9]+[\)\}\]]?)? (.+)", textLower):
			#return False
			page, search = re.match(r"search([\s]?[\(\[\{]?[0-9]+[\)\}\]]?)? (.+)", textLower).group(1,2)
			
			if len(search) < 4:
				meta.sendMsg(s, channel, "query too short.")
				return False
			
			if not page:
				page = 0
			else:
				page = int(page.strip(" \t[]{}()"))
				
			search = "%"+search+"%"
			cur.execute("""SELECT * FROM `factoids` WHERE `find` LIKE ? ORDER BY `id` LIMIT 5 OFFSET ?""", (search, page))
			
			conn.commit()
			data = cur.fetchall()
			
			
			if data:
				result = ""
				
				for x in range(len(data)):
				
					temp = "%s: %s %s %s" \
							% (
								data[x][0], 
								#re.sub(r"(?i)(\b)(is|are|search|factoid)(\b)", r"\1\\\2\3", data[x][2]), 
								re.sub(r"(?i)(\b)(search|factoid)(\b)", r"\1\\\2\3", data[x][2]), 
								data[x][3], 
								data[x][4]
							  )
						
					if len(temp)+len(result) > 400: break
					
					if result: result = result +" \003| "+ temp
					else: result = temp
					
				meta.sendMsg(s, channel, "Results: %s" % result)
				
			else:
				meta.sendMsg(s, channel, "Sorry %s, I couldn't find anything." % nick)
			
			return False
		
		
		###
		### protect
		###  - channel ops can keep factoids from being deleted by regular folk
		###
		elif re.match(r"(unprotect|protect) ((th|d)at|[#]?[0-9]+)[?!.]*$", textLower):
			#only ops and above can do that
			if not (meta.isOp(channel, nick) or meta.isProtected(channel, nick)):
				meta.sendMsg(s, channel, "I can't let you do that %s." % nick)
				return False
				
			word,reference=re.match(r"(unprotect|protect) (that|[#]?[0-9]+)", textLower).group(1,2)
			
			if word == "protect":
			
				if reference == "that" or reference == "dat":
					id = channels[channel]['lastFactoidId']
				else:
					id = int(reference.lstrip("#"))
				
				cur.execute("""UPDATE `factoids` SET `editable`=? WHERE `id`=?""",
					(0, id))
				conn.commit()
				
			else: # unprotect
				
				meta.sendMsg(s, channel, "unprotect is no longer available." % nick)
				return False
				
				if reference == "that" or reference == "dat":
					id = channels[channel]['lastFactoidId']
				else:
					id = int(reference.lstrip("#"))
				
				cur.execute("""UPDATE `factoids` SET `editable`=? WHERE `id`=?""",
					(1, id))
				conn.commit()
			
			meta.sendMsg(s, channel, "Ok %s" % nick)
			return False
		
		elif textLower == "?" or \
			 textLower == "help" or \
			 textLower == "docs" or \
			 textLower == "manual" or \
			 textLower == "/?":
			 
			if "help" in meta.conf:
				meta.sendMsg(s, channel, meta.conf["help"])
			else:
				meta.sendMsg(s, channel, "https://github.com/MOSW/wallybot/wiki/Manual")
			
			return False
			
		elif textLower == "source":
			 
			if "source" in meta.conf:
				meta.sendMsg(s, channel, meta.conf["source"])
			else:
				meta.sendMsg(s, channel, "https://github.com/MOSW/wallybot")
			
			return False
		
		
		#search = re.search(r'\s(is|are|<[a-z]+>)\s', text, re.ASCII | re.I)
		search = re.search(r'\s(<[a-z]+>)\s', text, re.ASCII | re.I)
		
		if search:
		
			verb = search.group(0).strip()
			
			
			tSplit = text[7 :].split(" "+verb+" ", 1)
			if len(tSplit) != 2:
				meta.sendMsg(s, channel, "%s: huh?" % nick)
				return False
			
			find = tSplit[0].strip()
			tidbit = tSplit[1].strip()
			
			verbLower = verb.lower()
			
			if verbLower != "<action>" and verbLower != "<reply>":
				verb = verb.strip("<>")
				verbLower = verb.lower()
			else:
				verb = verbLower
			
			
			
			if len(find) < 2:
				meta.sendMsg(s, channel, "%s: The fact is too short." % nick)
				return False
				
			if len(tidbit) < 2:
				meta.sendMsg(s, channel, "%s: Your 'tidbit' is too short..." % nick)
				return False
			
			
			
			find = re.sub(r"(?i)\\(is|are|search|factoid)", r"\1", find)
			tidbit = re.sub(r"(?i)\\(is|are|search|factoid)", r"\1", tidbit)
			
			#find = find.replace("\\is", "is").replace("\\are", "are").replace("\\<", "<")
			#tidbit = tidbit.replace("\\is", "is").replace("\\are", "are").replace("\\<", "<")
			tidbit = tidbit.replace(r"\\<", r"<")
			
			#grab a one word inkling. this word is the largest word
			#max was not working correctly... so I implimented my own
			#inkling = max(find.split()).lower()
			inklingSearch = find
			
			#strip out the ^ and $ so they dont appear in our inkling
			if inklingSearch[0] == "^": inklingSearch = inklingSearch[1 :]
			if inklingSearch[-1] == "$" and inklingSearch[-1] != "\\": inklingSearch = inklingSearch[:-1]
			
			inkling = None
			for word in inklingSearch.split():
				#set it to begin with
				if not inkling:
					inkling = word
					continue
				
				if len(word) > len(inkling):
					inkling = word
			
			inkling = inkling.lower()
			
			cur.execute("""INSERT INTO 
							`factoids`	(`inkling`, `find`, `verb`, `tidbit`, `nick`, `last_said`) 
							VALUES		(    ?,       ?,      ?,       ?,       ?,          ?)
						""",            ( inkling,   find,   verb,   tidbit,   nick,        0))
			channels[channel]['lastCreatedId'] = cur.lastrowid
			channels[channel]['lastFactoidId'] = cur.lastrowid
			conn.commit()
			
			meta.sendMsg(s, channel, "Ok %s" % nick)
			
			print(">>>",nick+":", find, verb, tidbit, cur.lastrowid)
			
			return False
			
		
		##
		## Factoid lookup when being spoken to.
		##
		textLower = re.sub(r"^\001action", r"/me", textLower)
		#factoidList = factoid_lookup(textLower, [], [], 0)
		
		explicit = channel in meta.conf['censor_channel']
		
		factoidList = new_factoid_lookup(textLower, [], explicit)
		
		if factoidList:
			unknownCommand = False
			
		if unknownCommand:
			meta.sendMsg(s, channel, random.choice(meta.unknownCmdReplys).format(nick=nick,chan=channel))
		
		
	##
	## Factoid lookup when not being spoken to.
	##
	elif len(textLower) > 4:
		## Limit speech with chattiness level so he's not annoying
		## - Each chattiness level represents one message
		## - Once the level has reached he can speak.
		if channel not in chattichans:
			## add channel to chattiness and make him able to talk immediately
			chattichans[channel] = meta.conf['chattiness']
		
		
		chattichans[channel] = chattichans[channel]+1
		
		if chattichans[channel] < meta.conf['chattiness']: return True
		
		## chattiness level reached. He can talk now.
		#chattichans[channel] = 0
		
		textLower = re.sub(r"^\001action", r"/me", textLower)
		
		#factoidList = factoid_lookup(textLower, [], [], 0)
		
		## does this channel need to be censored?
		explicit = channel in meta.conf['censor_channel']
		
		factoidList = new_factoid_lookup(textLower, [], explicit)
		
		
	
	
	if factoidList:
		
		##
		## Some chattiness fun
		##
		if channel not in chattichans:
			chattichans[channel] = meta.conf['chattiness']
			
		## if he was talked to directly, allow him to talk again.
		if chattichans[channel] < meta.conf['chattiness']:
			chattichans[channel] = meta.conf['chattiness']
		else:
			## otherwise reset to zero chattiness when he speaks to start again.
			chattichans[channel] = 0
		
		
		
		reply = random.choice(factoidList)
		
		channels[channel]['lastFactoidId'] = int(reply[0])
		
		replyText = reply[4]
		
		cur.execute("""UPDATE `factoids` SET `last_said`=? WHERE `id`=?""",
					(time.time(), reply[0]))
		conn.commit()
		
		replyText = replyText.replace("who*", nick)
		replyText = replyText.replace("WHO*", nick.upper())
		
		replyText = replyText.replace("chan*", channel)
		replyText = replyText.replace("CHAN*", channel.upper())
		
		randNick = None
		if replyText.find("someone*") != -1:
			randNick = meta.randomUser(channel).nick
			replyText = replyText.replace("someone*", randNick)
		
		if replyText.find("SOMEONE*") != -1:
			if not randNick:
				randNick = meta.randomUser(channel).nick
			replyText = replyText.replace("SOMEONE*", randNick.upper())
		
		
		
		if reply[3] == "<reply>":
			meta.sendMsg(s, channel, replyText)
		elif reply[3] == "<action>":
			meta.sendMsg(s, channel, "\001ACTION "+replyText+"\001")
		else:
			meta.sendMsg(s, channel, reply[2]+" "+reply[3]+" "+replyText)
			
		return False
Example #5
0
def notice(s, sender, ident, host, channel, text):
	
	authd = meta.isAuthor(sender, ident, host)
	
	textLower = text.lower()
	
	if textLower == '+bucket' and authd:
		if meta.conf['bucket']:
			meta.sendNotice(s, sender, "Confirm - Bucket is already On.")
		else:
			meta.sendNotice(s, sender, "Confirm - Bucket is now On.")
			meta.conf['bucket'] = True
		return False
		
	elif textLower == '-bucket' and authd:
		if not meta.conf['bucket']:
			meta.sendNotice(s, sender, "Confirm - Bucket is already Off.")
		else:
			meta.sendNotice(s, sender, "Confirm - Bucket is now Off.")
			meta.conf['bucket'] = False
		return False
		
	if textLower.find('+censor ') == 0 and authd:
		censor = text[8:].split()
		for p in censor:
			if not p: continue
			if p in meta.conf['censor_channel']:
				meta.sendNotice(s, sender, "Confirm - Already censoring \"%s\"." % (p,))
			else:
				meta.conf['censor_channel'].append(p)
				meta.sendNotice(s, sender, "Confirm - Now censoring \"%s\"." % (p,))
			
		return False
		
	if textLower.find('-censor ') == 0 and authd:
		censor = text[8:].split()
		for p in censor:
			if not p: continue
			if p not in meta.conf['censor_channel']:
				meta.sendNotice(s, sender, "Confirm - Wasn't censoring \"%s\"." % (p,))
			else:
				meta.conf['censor_channel'].remove(p)
				meta.sendNotice(s, sender, "Confirm - Not censoring \"%s\"." % (p,))
			
		return False
		
	elif textLower.find('ignore ') == 0 and authd:
		ignore = text[7:].split()
		for p in ignore:
			if not p: continue
			if p in meta.conf['ignore']:
				meta.sendNotice(s, sender, "Confirm - Already ignoring \"%s\"." % (p,))
			else:
				meta.conf['ignore'].append(p)
				meta.sendNotice(s, sender, "Confirm - Now ignoring \"%s\"." % (p,))
		return False
		
	elif textLower.find('unignore ') == 0 and authd:
		ignore = text[9:].split()
		for p in ignore:
			if not p: continue
			if p in meta.conf['ignore']:
				meta.conf['ignore'].remove(p)
				meta.sendNotice(s, sender, "Confirm - Now Listening to \"%s\"." % (p,))
			else:
				meta.sendNotice(s, sender, "Confirm - \"%s\" not currently ignored." % (p,))
		return False
		
	elif textLower == 'mode?':
		if meta.conf['bucket']:
			meta.sendNotice(s, sender, "Mode: Bucket is On.")
		else:
			meta.sendNotice(s, sender, "Mode: Bucket is Off.")
Example #6
0
def notice(s, sender, ident, host, channel, text):
	
	# Don't parse anything from nick or chan server. They wont be telling us
	# to do things.
	senderLower = sender.lower()
	if senderLower == 'chanserv' or senderLower == 'nickserv':
		return True
	
	authd = meta.isAuthor(sender, ident, host)
	
	textLower = text.lower()
	
	if textLower.find('join ') == 0 and authd:
		meta.send(s, "JOIN %s\r\n" % textLower[5:].strip())
		return False
	
	elif textLower.find('part ') == 0 and authd:
		meta.send(s, "PART %s\r\n" % textLower[5:].strip())
		return False
	
	elif textLower.find('nick ') == 0 and authd:
		meta.send(s, "NICK %s\r\n" % text[5:].strip())
		meta.conf['nick'] = text[5:].strip()
		return False
	
	elif textLower.find('nickpass ') == 0 and authd:
		meta.sendMsg(s, "NickServ", "IDENTIFY %s" % textLower[9:].strip())
		return False
	
	elif textLower.find('reload ') == 0 and authd:
		print("Reloading Module:", textLower[7:].strip())
		meta.reload.append(textLower[7:].strip())
		return False
		
	elif textLower.find('test ') == 0 and authd:
		meta.sendMsg(s, "Joey", "asdf1456")
		return False
		
	elif textLower.find('raw ') == 0 and authd:
		meta.send(s, "%s\r\n" % textLower[4:])
		return False
	
	elif textLower.find('msg ') == 0 and authd:
		rest = text[4:].strip()
		x = rest.find(' ')
		if not x: return False
		meta.sendMsg(s, rest[:x].rstrip(), rest[x+1:].lstrip())
		return False
		params = text[4:].strip().split()
		if len(params) < 2: return False
		meta.sendMsg(s, params[0], text[4+strlen(params[0]):].strip())
		return False
		
	
	elif textLower.find('notice ') == 0 and authd:
		rest = text[4:].strip()
		x = rest.find(' ')
		if not x: return False
		meta.sendMsg(s, rest[:x].rstrip(), rest[x+1:].lstrip())
		return False
		params = text[7:].strip().split()
		if len(params) < 2: return False
		meta.sendMsg(s, params[0], text[4+strlen(params[0]):].strip())
		return False
		
	elif textLower == 'mode?':
		if meta.conf['autovoice']:
			meta.sendNotice(s, sender, "Mode: AutoVoice is On.")
		else:
			meta.sendNotice(s, sender, "Mode: AutoVoice is Off.")
		# continue through to the other modules.
		# This command should return all the modules state to the requesting
		# user.
		return True
	
	noBlock = True
	
	# break down our text into commands to be processed by 
	cmds = text.split()
	while(cmds):
		#print(cmds[0])
		
		if cmds[0] == '-autovoice' and authd:
			if not meta.conf['autovoice']:
				meta.sendNotice(s, sender, "Confirm - AutoVoice is already Off.")
			else:
				meta.sendNotice(s, sender, "Confirm - AutoVoice is now Off.")
				meta.conf['autovoice'] = False
			noBlock = False
			
		elif cmds[0] == '+autovoice' and authd:
			if meta.conf['autovoice']:
				meta.sendNotice(s, sender, "Confirm - AutoVoice is already On.")
			else:
				meta.sendNotice(s, sender, "Confirm - AutoVoice is now On.")
				meta.conf['autovoice'] = True
			noBlock = False
			
		elif cmds[0] == '+auth':
			# This command takes 1 parameter that should immediatly follow it.
			# pop off the current command (+auth) so that we can grab the pass
			cmds.pop(0)
			
			# grab the pass
			upass = cmds[0]
			
			if upass == meta.conf['auth']:
				# save the authors exact identity
				meta.setAuthor(sender, ident, host)
				
				meta.sendNotice(s, sender, "Confirm - You are now Authorized.")
				print(sender, "is now authorized.")
				
				# set the local authorized variable so that the user is
				# authorized for the rest of the commands.
				authd = True
				
				# no other modules should ever get their hands on the password
				noBlock = False
			else:
				print("FAILED AUTHORIZATION BY", sender, ident, host)
			
		elif cmds[0] == '-auth':
			if authd:
				# un auth the sender
				meta.unsetAuthor()
				
				meta.sendNotice(s, sender, "Confirm - Authorization Removed.")
				print(sender, "has been deauthorized.")
				
				noBlock = False
			else:
				print("FAILED DEAUTH BY", sender, ident, host)
				
		elif cmds[0] == '+loud' and authd:
			if meta.conf['loud']:
				meta.sendNotice(s, sender, "CONFIRM - I WAS ALREADY REALLY REALLY ANNOYING.")
			else:
				meta.conf['loud'] = True
				meta.sendNotice(s, sender, "CONFIRM - I AM NOW REALLY REALLY ANNOYING.")
		elif cmds[0] == '-loud' and authd:
			if not meta.conf['loud']:
				meta.sendNotice(s, sender, "Confirm - Loud was already Off.")
			else:
				meta.conf['loud'] = False;
				meta.sendNotice(s, sender, "Confirm - Loud is now Off.")
				
		elif cmds[0] == '+tenso' and authd:
			if meta.conf['tenso']:
				meta.sendNotice(s, sender, "CONFIRM - TENSO was already On.")
			else:
				meta.conf['tenso'] = True
				meta.sendNotice(s, sender, "CONFIRM - TENSO")
		elif cmds[0] == '-tenso' and authd:
			if not meta.conf['tenso']:
				meta.sendNotice(s, sender, "Confirm - TENSO was already Off.")
			else:
				meta.conf['tenso'] = False;
				meta.sendNotice(s, sender, "Confirm - TENSO is now Off.")
			
		#elif cmds[0] == '+reload' and authd:
		#	cmds.pop(0)
		#	print("trying to reload:", cmds[0])
		#	print(__main__.__dict__)
		#	for plugin in __main__.plugins:
		#		print(" plugin:", plugin.__name__)
		#		if plugin.__name__ == cmds[0]:
		#			plugin = imp.reload(plugin)
		#			break
			
		elif cmds[0] == '-quit' and authd:
			meta.quit = True
			noBlock = False
			
		elif cmds[0] == '-restart' and authd:
			meta.quit = True
			meta.restart = True
			noBlock = False
		
		
		# if the first command fails dont continue trying to process commands
		# This is useful in situations where the notice is something like a 
		# talk command and this module shouldn't process anything in that
		# message.
		if noBlock: return True
		
		# pop the old command that we just worked on, off the queue
		cmds.pop(0)
		
	return noBlock
Example #7
0
def msg(s, nick, ident, host, channel, text):
	
	
	
	#print(channel)
	#no channel specific commands in private chat
	if channel == meta.conf['nick']:
		inChannel = False
		channel = nick
	else:
		inChannel = True
		
	
	if nick in meta.conf['ignore'] or host in meta.conf['ignorehost']:
		return False
	
	
	checkPigs(s, nick, channel, text)
	
	
	print(channel+":", nick,"|",text)
	
	
	
	if not re.match(r"wally[,:] ", text, re.I):
		return True
	
	if channel in meta.LOUD and not re.match(r"bitch[,:] ", text, re.I):
		return True
	
	
	text = text[7 :]
	textLower = text.lower()
	
	#print("In !1_main msg func", meta.canMute(channel, nick), inChannel)
	
	if textLower == "you there?":
		meta.sendMsg(s, channel, "yes")
		return True
	
	elif textLower[: 5] == "mute " and meta.canMute(channel, nick) and inChannel:
		#mute Joey until pigs fly
		#mute Joey until hell freezes over
		#mute Joey until ...your mom
		
		
		
		userEnd = text.find(' ', 5)
		
		#print("In mute", userEnd)
		
		if userEnd > 0:
			user = text[5 : userEnd]
			params = textLower[userEnd+1 :]
			
			# mute me 1m
			# mute me until pigs fly
			if user.lower() == 'me':
				user = nick
			
			if params[:6] == 'until ' or params[:4] == 'til ':
				if params[:4] == 'til ':
					params = params[4:]
				else:
					params = params[6:]
				
				# improper syntax
				if not params:
					meta.sendMsg(s, channel, "Until when? Finish your statements...")
					return False
				
				try:
					# add the user to the 'muted until' list
					stemmed = groundPigs(user, channel, params, nick)
				except:
					traceback.print_exc()
					input()
				
				print("Muting", user, "until", stemmed)
				
				c, u = meta.isUser(channel, user)
				if c and u:
					meta.users[c][u].mute( s )
				else:
					print(user, 'is not a user')
					meta.sendMsg(s, channel, "Mute who?")
					
				return False
			
			if not re.match(r"\d+[smhdwyc]?", params):
				return True
			
			if params[-1:] == 's':#seconds
				muteTime = float(params[ :-1])
			elif params[-1:] == 'm':#minutes
				muteTime = float(params[ :-1]) * 60
			elif params[-1:] == 'h':#hours
				muteTime = float(params[ :-1]) * 3600
			elif params[-1:] == 'd':#days
				muteTime = float(params[ :-1]) * 86400
			elif params[-1:] == 'w':#weeks
				muteTime = float(params[ :-1]) * 604800
			elif params[-1:] == 'y':#years
				muteTime = float(params[ :-1]) * 31556926
			elif params[-1:] == 'c':#Centuries
				muteTime = float(params[ :-1]) * 3155692600
			else:
				muteTime = float(params) #seconds
			
		else:
			user = text[5 :]
			
			if user.lower() == 'me':
				user = nick
			
			muteTime = 0
			
		c, u = meta.isUser(channel, user)
		if c and u:
			print("Muting", u, muteTime)
			meta.users[c][u].mute( s, muteTime )
		else:
			print(user, 'is not a user')
			meta.sendMsg(s, channel, "Mute who?")
			
		return False
		
		
	elif textLower.find('unmute ') == 0 and meta.canMute(channel, nick) and inChannel:
		user = text[7 :]
		
		if user.lower() == 'me':
			user = nick
			
		c, u = meta.isUser(channel, user)
		if c and u:
			meta.users[c][u].unmute(s)
			removePig(u, channel)
			#print("Unmuting", u)
		else:
			meta.sendMsg(s, channel, "Unmute who?")
		return False
		
	elif textLower.find('ban ') == 0:
		if not inChannel: return False
		
		if not meta.canBan(channel, nick):
			meta.sendMsg(s, channel, "%s: You do not have the power!" % nick)
			return False
			
		if not meta.canBan(channel, meta.conf['nick']):
			#meta.sendMsg(s, channel, "%s: I do not have the power!" % nick)
			return True
			
		
		r = re.match(r"ban\s+([^\s]+)\s*(?:(?:for\s+)?(.*?))?[!.?]*$", textLower)
		
		if not r:
			meta.sendMsg(s, channel, "%s: Invalid syntax." % nick)
			return False
		
		user, timeStr = r.groups()
		
		c, user = meta.isUser(channel, user)
		
		if not user:
			meta.sendMsg(s, channel, "%s: ban who?" % nick)
			return False
		
		x = meta.userInfo[user]
		
		length = timeOffset(timeStr)
		
		if not timeStr or (length and length < 0):
			meta.ban(s, channel, host=x['host'])
			return False
		
		elif not length:
			meta.sendMsg(s, channel, "%s: Invalid time." % nick)
			return False
		
		
		meta.timedBan(s, channel, length, host=x['host'])
		
		#meta.sendMsg(s, channel, "%s, You are awarded one tricky-dick-fun-bill for finding an undocumented unfinished feature!"%nick)
		return False
	
	elif textLower.find('unban ') == 0:
		if not inChannel: return False
		
		if not meta.canBan(channel, nick):
			meta.sendMsg(s, channel, "%s: You do not have the power!" % nick)
			return False
			
		if not meta.canBan(channel, meta.conf['nick']):
			#meta.sendMsg(s, channel, "%s: I do not have the power!" % nick)
			return True
		
		r = re.match(r"unban\s+([^\s]+?)[!.?\s]*$", textLower)
		
		if not r:
			meta.sendMsg(s, channel, "%s: Invalid syntax." % nick)
			return False
		
		(user,) = r.groups()
		
		c, user = meta.isUser(channel, user)
		
		if not user:
			meta.sendMsg(s, channel, "%s: unban who?" % nick)
			return False
		
		x = meta.userInfo[user]
		
		banmask = meta.unban(s, channel, host=x['host'])
		
		return False
	elif False and textLower == 'be loud' and ((inChannel and meta.canMute(channel, nick)) or not inChannel):
		while channel in meta.LOUD:
			meta.LOUD.remove(channel)
		meta.LOUD.append(channel)
		
		meta.sendMsg(s, channel, "%s: Ok."%nick)
		return False
		
	elif False and (textLower == 'not so loud' or textLower == 'be cool') and \
		((inChannel and meta.canMute(channel, nick)) or not inChannel):
		if channel in meta.LOUD:
			meta.LOUD.remove(channel)
			meta.sendMsg(s, channel, "%s: Ok."%nick)
			return False
			
		
	elif (textLower == 'restart' or textLower == 'reboot') and meta.isAuthor(nick, ident, host):
		meta.quit = True
		meta.restart = True
		return False
		
	elif (textLower == 'quit' or textLower == 'exit') and meta.isAuthor(nick, ident, host):
		meta.quit = True
		return False