A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

72 行
2.0 KiB

  1. # -*- coding: utf-8 -*-
  2. # A somewhat advanced calculator: http://futureboy.us/fsp/frink.fsp.
  3. import re
  4. import urllib
  5. from 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()