Commits

Chris Mulligan  committed 3867ee5

* Added log search to the web interface

Plus a grab-bag of random improvements made over the past week
* Improved handler registry for @contains
* Fixed !strategy so it uses a random list, rather than scraping the site
* User configurable pastebin that actually works
* Fix the pmxbot contains function so it doesn't include YG specific commands that don't exist
* made the !help command more readable (IMHO)
* 3 more nailedit excuses

  • Participants
  • Parent commits 0fbc4b7

Comments (0)

Files changed (6)

File pmxbot/botbase.py

 import re
 import feedparser
 import socket
+import random
 
 from threading import Thread
 
 		msg = (''.join(e.arguments())).decode('utf8', 'ignore')
 		nick = e.source().split('!', 1)[0]
 		channel = e.target()
-		if msg == '':
-			pass
-		else:
+		if msg > '':
 			if channel not in self._nolog:
 				logger.message(channel, nick, msg)
 			self.handle_action(c, e, channel, nick, msg)
+			
 	
 	def on_privmsg(self, c, e):
 		msg = (''.join(e.arguments())).decode('utf8', 'ignore')
 		nick = e.source().split('!', 1)[0]
 		channel = nick
-		if msg == '':
-			pass
-		else:
+		if msg > '':
 			self.handle_action(c, e, channel, nick, msg)
 
 	def on_invite(self, c, e):
 		secret = False
 		for typ, name, f, doc, channels, exclude, rate in _handler_registry:
 			if typ in ('command', 'alias') and lc_cmd == '!%s' % name:
+				if ' ' in msg:
+					msg = msg.split(' ', 1)[-1].lstrip()
+				else:
+					msg = ''
 				try:
-					if ' ' in msg:
-						msg = msg.split(' ', 1)[-1].lstrip()
-					else:
-						msg = ''
 					res = f(c, e, channel, nick, msg)
 				except Exception, e:
 					res = "DO NOT TRY TO BREAK PMXBOT!!!"
+					res += '\n%s' % e
 					traceback.print_exc()
 				break
 			elif typ in('contains', '#') and name in lc_msg:
 def contains(name, channels=None, exclude=None, rate=1.0, priority=1, doc=None):
 	def deco(func):
 		if name == '#' or priority == 2:
-			_handler_registry.append(('#', name.lower(), func, doc, channels, exclude, rate))
+			_handler_registry.append(('contains', name.lower(), func, doc, channels, exclude, rate))
 		else:
 			_handler_registry.append(('contains', name.lower(), func, doc, channels, exclude, rate))
 		_handler_registry.sort(key=lambda x: (_handler_sort_order[x[0]], 0-len(x[1]), x[1]))

File pmxbot/pmxbot.py

 
 @command('strategy', doc='Social Media Strategy, courtsey of http://whatthefuckismysocialmediastrategy.com/')
 def strategy(client, event, channel, nick, rest):
-	html = get_html('http://whatthefuckismysocialmediastrategy.com/')
-	res = plaintext(re.search(r"""<span class="bigfuckingtext">(.+?)</span>""", html).group(1))
-	return res
+	return random.choice(socialstrategies)
 	
 
 @command('oregontrail', aliases=('otrail',), doc='It\'s edutainment!')
 		yield "I blame %s for everything!  it's your fault!  it's all your fault!!" % blamee
 		yield "/me cries and weeps in despair"
 		
-@command("paste", aliases=(), doc="Drop a link to your latest paste on %s" % config.librarypaste)
+@command("paste", aliases=(), doc="Drop a link to your latest paste")
 def paste(client, event, channel, nick, rest):
-	post_url = browser.catch_redirect_url("%s/last/%s" % (config.librarypaste, nick))
-	if post_url:
-		return post_url
+	req = urllib.urlopen("%slast/%s" % (config.librarypaste, nick))
+	if req.getcode() >= 200 and req.getcode() < 400:
+		return req.geturl()
 	else:
 		return "hmm.. I didn't find a recent paste of yours, %s. Checkout %s" % (nick, config.librarypaste)
 
 def rand_bot(client, event, channel, nick, rest):
 	if (channel == config.inane_channel and random.random() < .2):
 		normal_functions = [featurecreep, insult, motivate, compliment, cheer,
-			golfclap, excuse, nastygram, curse, bless, job, hire, 
-			bakecake, cutcake, oregontrail, chain, tinytear, blame,
-			reweight, panic, rubberstamp, dance, annoy, klingon, 
+			golfclap, excuse, nastygram, curse, bless, job, hire, oregontrail,
+			chain, tinytear, blame, panic, rubberstamp, dance, annoy, klingon, 
 			storytime, murphy]
-		quote_functions = [quote, falconer, gir, zim, zoidberg, simpsons, bender, hal, grail]
+		quote_functions = [quote, zoidberg, simpsons, bender, hal, grail, R, anchorman, hangover]
 		ftype = random.choice('n'*len(normal_functions) + 'q'*len(quote_functions))
 		if ftype == 'n':
 			func = random.choice(normal_functions)
 					if aliases:
 						res += " (%s)" % ', '.join(aliases)
 					yield res
-		o = StringIO("|".join(mk_entries()))
+		o = StringIO(" ".join(mk_entries()))
 		more = o.read(160)
 		while more:
 			yield more

File pmxbot/saysomething.py

 	db.text_factory = str
 	WORDS_SQL = '''SELECT message FROM logs order by random() limit %s''' % max
 	lines = db.execute(WORDS_SQL)
-	QUOTE_SQL = '''SELECT quote FROM quotes where library = 'pmx''''
+	QUOTE_SQL = '''SELECT quote FROM quotes where library = 'pmx' '''
 	quotes = db.execute(QUOTE_SQL) 
 	for line in lines + quotes:
 		words = line[0].strip().lower().split()

File pmxbot/util.py

 	"Ninety percent of everything is crap",
 ]
 
+socialstrategies = [
+	"Facilitate audience conversations and drive engagement with social currency",
+	"Maximise breakthrough by leveraging influencers",
+	"Amplify word of mouth by motivating influencers",
+	"Humanise the brand by driving the audience conversations",
+	"Harness social currency to drive buzz",
+	"Drive break through conversations with an engaging viral",
+	"Utilise social currency to amplify experiences and drive conversations",
+	"Maximise buzz by driving word of mouth from relevant influencers",
+	"Increase organic growth by exposing audiences to the brand through breakthrough viral communications",
+	"Encourage positive conversations to drive advocacy",
+	"Target influencers with engaging assets to act as platforms for conversation",
+	"Provide brand ambassadors with compelling conversation hooks to enter into communities and fuel advocacy",
+	"Expose new and relevant communities to the brand by providing assets to encourage brand evangelism",
+	"Enhance the customer experience by facilitating authentic conversations",
+	"Expose new users to the brand through organic conversations",
+	"Build loyalty & increased engagement through ongoing conversation and brand experience",
+	"Strengthen the emotional connection with the brand by building relationship",
+	"Maximise the customer experience, driving engagement and bringing the brand alive",
+	"Ignite the existing community and attract new members by amplifying the experience with relevant and engaging content",
+	"Identify relevant and compelling hooks for the audience, create content around the hooks and integrate it into their social repertoires",
+	"Activate audience by giving them compelling social experiences, encouraging advocacy",]
+
+
 def wchoice(d):
 	l = []
 	for item, num in d.iteritems():
 	'''It looks like I'll be "working" from "home" today''',
 	"I've been maliciously sunburned, and need to stay home and get jumped by my chihuahuas",
 	"I need to go get a haircut",
+	"I stepped out to get my marriage license",
+	"I, um...",
+	"I, um... won't be in...",
 ]
 
 def passagg(recipient='', sender=''):

File pmxbotweb/templates/search.html

+{% extends "base.html" %}
+{% block body %}
+
+<h3>{{ num_results }} Results Found for "{{ term }}" (showing most recent first)</h3>
+
+{% for chan, date, marker, history in search_results %}
+<div class="result_heading">
+<a href="{{ request.base }}/day/{{ chan }}/{{ date }}#{{ marker }}"><i>{{ date }} in {{ chan }}</i></a>
+</div>
+<div class="logsection">
+{% for tm, name, msg in history %}
+	<div class="logline">
+	[{{ tm }}] &lt;<span>{{ name }}</span>&gt; {{ msg }}
+	</div>
+{% endfor %}
+</div>
+<br/>
+<br/>
+{% endfor %}
+
+
+
+{% endblock %}

File pmxbotweb/viewer.py

 		context['bottom100'] = karmaList(db, -100)
 		return page.render(**context)
 	default.exposed = True
-		
+
+def search_logs(term, db):
+	terms = term.strip().split()
+
+	SEARCH_SQL = 'SELECT id, date(datetime), time(datetime), datetime, channel, nick, message FROM logs WHERE %s' % (' AND '.join(["message like '%%%s%%'" % x for x in terms]))
+
+	matches = []
+	alllines = []
+	search_res = db.execute(SEARCH_SQL)
+	for id, date, time, dt, channel, nick, message in search_res:
+			line = (time, nick, message)
+			if line in alllines:
+				continue
+			prev2 = db.execute('SELECT time(datetime), nick, message from logs where channel = ? and datetime < ? order by datetime desc limit 2', [channel, dt])
+			next2 = db.execute('SELECT time(datetime), nick, message from logs where channel = ? and datetime > ? order by datetime asc limit 2', [channel, dt])
+			lines = prev2.fetchall() + [line] + next2.fetchall()
+			marker = make_anchor(line)
+			matches.append((channel, date, marker, lines))
+			alllines.extend(lines)
+	return matches		
 
 class SearchPage(object):
-	pass
+	def default(self, term=''):
+		page = jenv.get_template('search.html')
+		context = get_context()
+		dbfile = cherrypy.request.app.config['db']['database']
+		db = sqlite.connect(dbfile)
+		db.text_factory = lambda x: unicode(x, "utf-8", "ignore")
+	
+		if not term:
+			raise cherrypy.HTTPRedirect(cherrypy.request.base)
+		results = sorted(search_logs(term, db), key=lambda x: x[1], reverse=True)
+		context['search_results'] = results
+		context['num_results'] = len(results)
+		context['term'] = term
+		return page.render(**context)
+	default.exposed = True
+		
 	
 class HelpPage(object):
 	def __init__(self):