mod_util.py

Mon, 10 Nov 2014 02:42:57 +0200

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Mon, 10 Nov 2014 02:42:57 +0200
changeset 77
8f45af91a4f3
parent 76
a2fe9ba3041a
child 102
2bad379cd416
permissions
-rw-r--r--

- added missing global statement

import math
import urllib2
import json
from modulecore import command_error

ModuleData = {
	'commands':
	[
		{
			'name': 'convert',
			'description': 'Performs numeric conversion',
			'args': '<value> as <valuetype>',
			'level': 'normal',
		},
		
		{
			'name': 'ud',
			'description': 'Looks up a term in urban dictionary',
			'args': '<term...>',
			'level': 'normal',
		},
	]
}

def cmd_convert (bot, args, replyto, **rest):
	value = float (args['value'])
	valuetype = args['valuetype']
	
	if valuetype in ['radians', 'degrees']:
		if valuetype == 'radians':
			radvalue = value
			degvalue = (value * 180.) / math.pi
		else:
			radvalue = (value * math.pi) / 180.
			degvalue = value
		
		bot.privmsg (replyto, '%s radians, %s degrees (%s)' %
			(radvalue, degvalue, degvalue % 360.))
		return
	
	if valuetype in ['celsius', 'fahrenheit']:
		if valuetype == 'celsius':
			celvalue = value
			fahrvalue = value * 1.8 + 32
		else:
			celvalue = (value - 32) / 1.8
			fahrvalue = value
		
		bot.privmsg (replyto, '%s degrees celsius, %s degrees fahrenheit' % (celvalue, fahrvalue))
		return
	
	command_error ('unknown valuetype %s, expected one of: degrees, radians (angle conversion), ' +
		'celsius, fahrenheit (temperature conversion)' % valuetype)

def cmd_ud (bot, args, replyto, **rest):
	try:
		url = 'http://api.urbandictionary.com/v0/define?term=%s' % (args['term'].replace (' ', '%20'))
		response = urllib2.urlopen (url).read()
		data = json.loads (response)
		
		if not 'list' in data \
		or len(data['list']) == 0 \
		or not 'word' in data['list'][0] \
		or not 'definition' in data['list'][0]:
			command_error ("couldn't find a definition of \002%s\002" % args['term'])
		
		word = data['list'][0]['word']
		definition = data['list'][0]['definition'].replace ('\r', ' ').replace ('\n', ' ').replace ('  ', ' ')
		up = data['list'][0]['thumbs_up']
		down = data['list'][0]['thumbs_down']
		bot.privmsg (replyto, "\002%s\002: %s\0033 %d\003 up,\0035 %d\003 down" % (word, definition, up, down))
	except Exception as e:
		command_error ('Urban dictionary lookup failed: %s' % e)

mercurial