Enhance Supybots Calculator
The calc function in Math of the mainline Supybot plugins is a little disappointing. It is unable to solve for variables and really doesn't include much logic besides exceptions to explain why it cannot handle your math expression.
Why not use a separate application... like qalc.
First, lets start off by investigating what code already exists: open the file /usr/share/python-support/supybot/supybot/plugins/Math/plugin.py
def calc(self, irc, msg, args, text):
"""<math expression>
Returns the value of the evaluated <math expression>. The syntax is
Python syntax; the type of arithmetic is floating point. Floating
point arithmetic is used in order to prevent a user from being able to
crash to the bot with something like '10**10**10**10'. One consequence
is that large values such as '10**24' might not be exact.
"""
if text != text.translate(utils.str.chars, '_[]'):
irc.error('There\'s really no reason why you should have '
'underscores or brackets in your mathematical '
'expression. Please remove them.')
return
#text = text.translate(utils.str.chars, '_[] \t')
if 'lambda' in text:
irc.error('You can\'t use lambda in this command.')
return
... lets keep the source short .....
except NameError, e:
irc.error('%s is not a defined function.' % str(e).split()[1])
except Exception, e:
irc.error(str(e))
calc = wrap(calc, ['text'])
Great, so you discovered the amount of polish you can affirm to a chunk of turd... let's fix it.
First, go ahead and copy the entire Math plugin to your bot's personal plugin folder and begin opening plugin.py again for editing.
Find the calc function again and replace it with this:
def calc(self, irc, msg, args, text):
"""<math expression>
Returns the value of the evaluated <math expression>. The syntax is
Qalculate syntax.
"""
if text != text.translate(utils.str.chars, '_[]'):
irc.error('There\'s really no reason why you should have '
'underscores or brackets in your mathematical '
'expression. Please remove them.')
return
import os
text = "\"" + text + "\""
irc.reply( os.popen("qalc " + text).read().strip("\n") )
calc = wrap(calc, ['text'])
We keep the first if statement since it stops if you're abusing your math expression anyway. After this, we add quotes to the expression so use special characters, such as parenthesis, as is. Finally, we reply with the first line of output from qalc :).
A big note, however: remember to run qalc once as a user as it will ask to download current exchange rates. Forgetting that step will result in a stalled bot. Second, configure supybot to use your plugin folder with higher precedence otherwise you will load the unmodified plugin again.
Now, just send the reload Math command to your bot and have fun.
[19:05:46] <damentz> .calc 3x^2 + 2x - 8 = 0 [19:05:46] <devastate> damentz: ((3 * (x^2)) + (2 * x) - 8) = 0 = approx. x = 1.3333333 or x = -2 [19:03:45] <damentz> .calc $/CAD [19:03:46] <devastate> damentz: dollar / CAD = approx. 1.2384326