- added a basic /idgames search

Fri, 23 May 2014 19:25:37 +0300

author
Santeri Piippo <crimsondusk64@gmail.com>
date
Fri, 23 May 2014 19:25:37 +0300
changeset 2
1a24dd2d598e
parent 1
29c7e9d13a30
child 3
53486417a8e5

- added a basic /idgames search

cobalt.py file | annotate | diff | comparison | revisions
--- a/cobalt.py	Tue May 13 23:29:37 2014 +0300
+++ b/cobalt.py	Fri May 23 19:25:37 2014 +0300
@@ -34,6 +34,8 @@
 import traceback
 import re
 import json
+import urllib
+import urllib2
 from suds.xsd.doctor import Import
 from suds.xsd.doctor import ImportDoctor
 from suds.client import Client
@@ -48,6 +50,8 @@
 g_admins = g_config['admins']
 g_mynick = g_config['nickname']
 
+g_idgamesSearchURL = 'http://www.doomworld.com/idgames/api/api.php?action=search&query=%s&type=title&sort=date&out=json'
+
 #
 # SOAP stuff
 #
@@ -164,7 +168,8 @@
 
 	def handle_read (self):
 		lines = self.recv (4096).splitlines()
-		for line in lines:
+		for utfline in lines:
+			line = utfline.decode("utf-8").encode("ascii","ignore")
 			print "[%s] -> %s" % (self.name, line)
 
 			if line.startswith ("PING :"):
@@ -241,10 +246,45 @@
 			if len(args) < 2:
 				raise logical_exception ("usage: .%s <target> <message...>" % command)
 			self.privmsg (args[0], " ".join (args[1:]))
-		elif command == "ticket":
+		elif command == 'ticket':
 			if len(args) != 1:
 				raise logical_exception ("usage: .%s <ticket>" % command)
 			self.get_ticket_data (replyto, args[0], True)
+		elif command == 'idgames':
+			try:
+				if len(args) < 1:
+					raise logical_exception ('usage: .%s <keywords>' % command)
+
+				url = g_idgamesSearchURL % urllib.quote (" ".join (args[0:]))
+				response = urllib2.urlopen (url).read()
+				data = json.loads (response)
+
+				if 'content' in data and 'file' in data['content']:
+					if type (data['content']['file']) is list:
+						files = data['content']['file']
+					else:
+						files = [data['content']['file']]
+
+					i = 0
+					for filedata in files:
+						if i >= 5:
+							break
+
+						self.privmsg (replyto, '- %s: \'%s\' by \'%s\', rating: %s: %s' % \
+							(filedata['filename'], filedata['title'], filedata['author'], filedata['rating'], filedata['url']))
+
+						i += 1
+					self.privmsg (replyto, "(%d / %d results posted)" % (i, len(files)))
+				elif 'warning' in data and 'message' in data['warning']:
+					raise logical_exception (data['warning']['message'])
+				elif 'error' in data and 'message' in data['error']:
+					raise logical_exception (data['error']['message'])
+				else:
+					raise logical_exception ("Incomplete JSON response from doomworld.com/idgames")
+			except logical_exception as e:
+				raise e
+			except Exception as e:
+				raise logical_exception ('Search failed: %s' % `e`)
 		else:
 			raise logical_exception ("unknown command `.%s`" % command)
 

mercurial