Additional IRC commands and bot tasks for EarwigBot 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.

100 lines
4.0 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2014 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from json import loads
  23. from socket import (AF_INET, AF_INET6, error as socket_error, gethostbyname,
  24. inet_pton)
  25. from urllib2 import urlopen
  26. from earwigbot.commands import Command
  27. class Geolocate(Command):
  28. """Geolocate an IP address (via http://ipinfodb.com/)."""
  29. name = "geolocate"
  30. commands = ["geolocate", "locate", "geo", "ip"]
  31. def setup(self):
  32. self.config.decrypt(self.config.commands, self.name, "apiKey")
  33. try:
  34. self.key = self.config.commands[self.name]["apiKey"]
  35. except KeyError:
  36. self.key = None
  37. log = 'Cannot use without an API key for http://ipinfodb.com/ stored as config.commands["{0}"]["apiKey"]'
  38. self.logger.warn(log.format(self.name))
  39. def process(self, data):
  40. if not self.key:
  41. msg = 'I need an API key for http://ipinfodb.com/ stored as \x0303config.commands["{0}"]["apiKey"]\x0F.'
  42. log = 'Need an API key for http://ipinfodb.com/ stored as config.commands["{0}"]["apiKey"]'
  43. self.reply(data, msg.format(self.name))
  44. self.logger.error(log.format(self.name))
  45. return
  46. if data.args:
  47. address = data.args[0]
  48. else:
  49. try:
  50. address = gethostbyname(data.host)
  51. except socket_error:
  52. msg = "Your hostname, \x0302{0}\x0F, is not an IP address!"
  53. self.reply(data, msg.format(data.host))
  54. return
  55. if not self.is_ip(address):
  56. msg = "\x0302{0}\x0F is not an IP address!"
  57. self.reply(data, msg.format(address))
  58. return
  59. url = "http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=json"
  60. query = urlopen(url.format(self.key, address)).read()
  61. res = loads(query)
  62. country = res["countryName"].title()
  63. region = res["regionName"].title()
  64. city = res["cityName"].title()
  65. latitude = res["latitude"]
  66. longitude = res["longitude"]
  67. utcoffset = res["timeZone"]
  68. if not country and not region and not city:
  69. self.reply(data, "IP \x0302{0}\x0F not found.".format(address))
  70. return
  71. if country == "-" and region == "-" and city == "-":
  72. self.reply(data, "IP \x0302{0}\x0F is reserved.".format(address))
  73. return
  74. msg = "{0}, {1}, {2} ({3}, {4}), UTC {5}"
  75. geo = msg.format(country, region, city, latitude, longitude, utcoffset)
  76. self.reply(data, geo)
  77. def is_ip(self, address):
  78. """Return ``True`` if the input is an IP address, else ``False``.
  79. This tests for IPv4 and IPv6 using :py:func:`socket.inet_pton`.
  80. """
  81. try:
  82. inet_pton(AF_INET, address)
  83. except socket_error:
  84. try:
  85. inet_pton(AF_INET6, address)
  86. except socket_error:
  87. return False
  88. return True