A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

calc.py 2.0 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. # A somewhat advanced calculator: http://futureboy.us/fsp/frink.fsp.
  3. import re
  4. import urllib
  5. from irc.classes import BaseCommand
  6. class Calc(BaseCommand):
  7. def get_hooks(self):
  8. return ["msg"]
  9. def get_help(self, command):
  10. return "A somewhat advanced calculator: see http://futureboy.us/fsp/frink.fsp for details."
  11. def check(self, data):
  12. if data.is_command and data.command == "calc":
  13. return True
  14. return False
  15. def process(self, data):
  16. if not data.args:
  17. self.connection.reply(data, "What do you want me to calculate?")
  18. return
  19. query = ' '.join(data.args)
  20. query = self.cleanup(query)
  21. url = "http://futureboy.us/fsp/frink.fsp?fromVal=%s" % urllib.quote(query)
  22. result = urllib.urlopen(url).read()
  23. r_result = re.compile(r'(?i)<A NAME=results>(.*?)</A>')
  24. r_tag = re.compile(r'<\S+.*?>')
  25. match = r_result.search(result)
  26. if not match:
  27. self.connection.reply(data, "Calculation error.")
  28. return
  29. result = match.group(1)
  30. result = r_tag.sub("", result) # strip span.warning tags
  31. result = result.replace("&gt;", ">")
  32. result = result.replace("(undefined symbol)", "(?) ")
  33. result = result.strip()
  34. if not result:
  35. result = '?'
  36. elif " in " in query:
  37. result += " " + query.split(" in ", 1)[1]
  38. res = "%s = %s" % (query, result)
  39. self.connection.reply(data, res)
  40. def cleanup(self, query):
  41. fixes = [
  42. (' in ', ' -> '),
  43. (' over ', ' / '),
  44. (u'£', 'GBP '),
  45. (u'€', 'EUR '),
  46. ('\$', 'USD '),
  47. (r'\bKB\b', 'kilobytes'),
  48. (r'\bMB\b', 'megabytes'),
  49. (r'\bGB\b', 'kilobytes'),
  50. ('kbps', '(kilobits / second)'),
  51. ('mbps', '(megabits / second)')
  52. ]
  53. for original, fix in fixes:
  54. query = re.sub(original, fix, query)
  55. return query.strip()