mod_util.py

changeset 105
84bd617a2520
parent 102
2bad379cd416
child 106
31583e5b2f49
equal deleted inserted replaced
104:27294de7b0d3 105:84bd617a2520
1 import math 1 import math
2 import urllib2 2 import urllib2
3 import json 3 import json
4 import subprocess
5 import re
4 from modulecore import command_error 6 from modulecore import command_error
5 import modulecore as ModuleCore 7 import modulecore as ModuleCore
6 8
7 ModuleData = { 9 ModuleData = {
8 'commands': 10 'commands':
30 32
31 { 33 {
32 'name': 'help', 34 'name': 'help',
33 'description': 'Prints help about a given command', 35 'description': 'Prints help about a given command',
34 'args': '<command>', 36 'args': '<command>',
37 'level': 'normal',
38 },
39
40 {
41 'name': 'calc',
42 'description': 'Calculates a mathematical expression using apcalc',
43 'args': '<expression...>',
35 'level': 'normal', 44 'level': 'normal',
36 }, 45 },
37 ] 46 ]
38 } 47 }
39 48
106 115
107 if not ModuleCore.is_available (cmd, ident, host): 116 if not ModuleCore.is_available (cmd, ident, host):
108 command_error ('you may not use %s' % cmd['name']) 117 command_error ('you may not use %s' % cmd['name'])
109 118
110 bot.privmsg (replyto, '%s %s: %s' % (cmd['name'], cmd['args'], cmd['description'])) 119 bot.privmsg (replyto, '%s %s: %s' % (cmd['name'], cmd['args'], cmd['description']))
120
121 def cmd_calc (bot, replyto, args, **rest):
122 expr = args['expression']
123
124 try:
125 # I want pi around so yeah
126 pirex = re.compile (r'^(.*)\bpi\b(.*)$')
127 match = pirex.match (expr)
128
129 while match:
130 expr = match.group(1) + '3.14159265358979323846264338327950288' + match.group(2)
131 match = pirex.match (expr)
132
133 result = subprocess.check_output (['calc', expr], stderr=subprocess.STDOUT) \
134 .replace ('\t', '') \
135 .replace ('\n', '')
136
137 errmatch = re.compile (r'^.*\bError\b.*$').match (result)
138
139 if errmatch:
140 command_error ('math error')
141 return
142
143 bot.privmsg (replyto, 'Result: %s' % result)
144 except subprocess.CalledProcessError as e:
145 command_error (e.output.split('\n')[0])
146 except OSError as e:
147 command_error ('failed to execute calc: ' + e.strerror)

mercurial