mod_util.py

changeset 154
df862cca1773
parent 153
497b7290977d
child 155
5a9b5065f53f
equal deleted inserted replaced
153:497b7290977d 154:df862cca1773
28 28
29 from __future__ import print_function 29 from __future__ import print_function
30 import math 30 import math
31 import json 31 import json
32 import re 32 import re
33 from modulecore import command_error 33 import modulecore
34 import modulecore as ModuleCore
35 import utility 34 import utility
36 import calc 35 import calc
37 import urllib.parse 36 import urllib.parse
38 37
39 ModuleData = { 38 ModuleData = {
106 'name': 'bitly', 105 'name': 'bitly',
107 'description': 'Shortens a link using bit.ly', 106 'description': 'Shortens a link using bit.ly',
108 'args': '<link>', 107 'args': '<link>',
109 'level': 'normal' 108 'level': 'normal'
110 }, 109 },
111
112 {
113 'name': 'py',
114 'description': 'Evaluates python',
115 'args': '<command...>',
116 'level': 'normal'
117 }
118 ] 110 ]
119 } 111 }
120 112
121 def cmd_convert (bot, args, reply, **rest): 113 def cmd_convert (bot, args, reply, error, **rest):
122 try: 114 try:
123 value = float (args['value']) 115 value = float (args['value'])
124 except Exception as e: 116 except Exception as e:
125 command_error (str (e)) 117 error (str (e))
126 118
127 valuetype = args['valuetype'] 119 valuetype = args['valuetype']
128 120
129 if valuetype in ['radians', 'degrees']: 121 if valuetype in ['radians', 'degrees']:
130 if valuetype == 'radians': 122 if valuetype == 'radians':
146 fahrvalue = value 138 fahrvalue = value
147 139
148 reply ('%s degrees celsius, %s degrees fahrenheit' % (celvalue, fahrvalue)) 140 reply ('%s degrees celsius, %s degrees fahrenheit' % (celvalue, fahrvalue))
149 return 141 return
150 142
151 command_error ('unknown valuetype %s, expected one of: degrees, radians (angle conversion), ' + 143 error ('unknown valuetype %s, expected one of: degrees, radians (angle conversion), ' +
152 'celsius, fahrenheit (temperature conversion)' % valuetype) 144 'celsius, fahrenheit (temperature conversion)' % valuetype)
153 145
154 def cmd_ud (bot, args, reply, **rest): 146 def cmd_ud (bot, args, reply, error, **rest):
155 try: 147 try:
156 url = 'http://api.urbandictionary.com/v0/define?term=%s' % (args['term'].replace (' ', '%20')) 148 url = 'http://api.urbandictionary.com/v0/define?term=%s' % (args['term'].replace (' ', '%20'))
157 response = utility.read_url (url) 149 response = utility.read_url (url)
158 data = json.loads (response) 150 data = json.loads (response)
159 151
160 if not 'list' in data \ 152 if not 'list' in data \
161 or len(data['list']) == 0 \ 153 or len(data['list']) == 0 \
162 or not 'word' in data['list'][0] \ 154 or not 'word' in data['list'][0] \
163 or not 'definition' in data['list'][0]: 155 or not 'definition' in data['list'][0]:
164 command_error ("couldn't find a definition of \002%s\002" % args['term']) 156 error ("couldn't find a definition of \002%s\002" % args['term'])
165 157
166 word = data['list'][0]['word'] 158 word = data['list'][0]['word']
167 definition = data['list'][0]['definition'].replace ('\r', ' ').replace ('\n', ' ').replace (' ', ' ') 159 definition = data['list'][0]['definition'].replace ('\r', ' ').replace ('\n', ' ').replace (' ', ' ')
168 up = data['list'][0]['thumbs_up'] 160 up = data['list'][0]['thumbs_up']
169 down = data['list'][0]['thumbs_down'] 161 down = data['list'][0]['thumbs_down']
170 reply ("\002%s\002: %s\0033 %d\003 up,\0035 %d\003 down" % (word, definition, up, down)) 162 reply ("\002%s\002: %s\0033 %d\003 up,\0035 %d\003 down" % (word, definition, up, down))
171 except Exception as e: 163 except Exception as e:
172 command_error ('Urban dictionary lookup failed: %s' % e) 164 error ('Urban dictionary lookup failed: %s' % e)
173 165
174 def cmd_commands (bot, reply, ident, host, **rest): 166 def cmd_commands (bot, reply, ident, host, **rest):
175 commandlist = ModuleCore.get_available_commands (ident, host) 167 commandlist = modulecore.get_available_commands (ident, host)
176 partitioned=[] 168 partitioned=[]
177 169
178 while len (commandlist) > 0: 170 while len (commandlist) > 0:
179 partitioned.append (commandlist[0:15]) 171 partitioned.append (commandlist[0:15])
180 commandlist = commandlist[15:] 172 commandlist = commandlist[15:]
181 173
182 for part in partitioned: 174 for part in partitioned:
183 reply ('\002Available commands\002: %s' % (", ".join (part))) 175 reply ('\002Available commands\002: %s' % (", ".join (part)))
184 176
185 def cmd_help (bot, reply, ident, host, args, **rest): 177 def cmd_help (bot, reply, ident, host, args, error, **rest):
186 cmd = ModuleCore.get_command_by_name (args['command']) 178 cmd = modulecore.get_command_by_name (args['command'])
187 179
188 if not cmd: 180 if not cmd:
189 command_error ('unknown command \'%s\'' % args['command']) 181 error ('unknown command \'%s\'' % args['command'])
190 182
191 if not ModuleCore.is_available (cmd, ident, host): 183 if not modulecore.is_available (cmd, ident, host):
192 command_error ('you may not use %s' % cmd['name']) 184 error ('you may not use %s' % cmd['name'])
193 185
194 reply ('%s %s: %s' % (cmd['name'], cmd['args'], cmd['description'])) 186 reply ('%s %s: %s' % (cmd['name'], cmd['args'], cmd['description']))
195
196 def mathsubstitute (expr, token, value):
197 rex = re.compile (r'^(.*)\b' + token + r'\b(.*)$')
198 match = rex.match (expr)
199
200 while match:
201 expr = match.group(1) + str (value) + match.group(2)
202 match = rex.match (expr)
203
204 return expr
205 187
206 def cmd_calcfunctions (bot, reply, **rest): 188 def cmd_calcfunctions (bot, reply, **rest):
207 reply ('Available functions for .calc: %s' % \ 189 reply ('Available functions for .calc: %s' % \
208 ', '.join (sorted ([name for name, data in calc.Functions.items()]))) 190 ', '.join (sorted ([name for name, data in calc.Functions.items()])))
209 191
210 def cmd_calc (bot, reply, args, **rest): 192 def cmd_calc (bot, reply, args, **rest):
211 reply (calc.Calculator().calc (args['expression'])) 193 reply (calc.Calculator().calc (args['expression']))
212 194
213 def cmd_more (commandObject, **rest): 195 def cmd_more (commandObject, **rest):
214 ModuleCore.print_responses (commandObject) 196 modulecore.print_responses (commandObject)
215 197
216 def cmd_yes (**k): 198 def cmd_yes (**k):
217 ModuleCore.confirm (k, True) 199 modulecore.confirm (k, True)
218 200
219 def cmd_no (**k): 201 def cmd_no (**k):
220 ModuleCore.confirm (k, False) 202 modulecore.confirm (k, False)
221 203
222 def cmd_bitly (reply, args, **k): 204 def cmd_bitly (reply, args, **k):
223 reply ('Result: %s' % utility.shorten_link (args['link'])) 205 reply ('Result: %s' % utility.shorten_link (args['link']))
224 206
225 def cmd_py (reply, args, **rest): 207 @modulecore.irc_command (args='<command...>')
208 def py (reply, args, **rest):
209 ''' Evaluates the given Python string using appspot.com '''
226 url = 'http://eval.appspot.com/eval?statement=' + urllib.parse.quote (args['command']) 210 url = 'http://eval.appspot.com/eval?statement=' + urllib.parse.quote (args['command'])
227 result = utility.read_url (url).splitlines() 211 result = utility.read_url (url, timeout=15).splitlines()
212
213 if not result:
214 reply ('No output.')
215 return
228 216
229 # \x0f is the 'reset colors' code, prepended to all reply lines to prevent other bots from 217 # \x0f is the 'reset colors' code, prepended to all reply lines to prevent other bots from
230 # reacting to this .py call. 218 # reacting to this .py call.
231 if result[0] == 'Traceback (most recent call last):': 219 if result[0] == 'Traceback (most recent call last):':
232 reply ('\x0f' + result[-1]) 220 reply ('\x0f' + result[-1])

mercurial