Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

114 строки
4.1 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2015 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 urllib2 import urlopen, HTTPError
  24. from earwigbot.commands import Command
  25. class Stars(Command):
  26. """Get the number of stargazers for a given GitHub repository."""
  27. name = "stars"
  28. commands = ["stars", "stargazers"]
  29. API_REPOS = "https://api.github.com/repos/{repo}"
  30. API_USERS = "https://api.github.com/users/{user}/repos?per_page=100"
  31. EXAMPLE = "!stars earwig/earwigbot"
  32. def process(self, data):
  33. if not data.args:
  34. msg = "Which GitHub repository or user should I look up? Example: \x0306{0}\x0F."
  35. self.reply(data, msg.format(self.EXAMPLE))
  36. return
  37. arg = data.args[0]
  38. if "/" in arg:
  39. self.handle_repo(data, arg)
  40. else:
  41. self.handle_user(data, arg)
  42. def handle_repo(self, data, arg):
  43. """Handle !stars <user>/<repo>."""
  44. repo = self.get_repo(arg)
  45. if repo is None:
  46. self.reply(data, "Repository not found. Is it private?")
  47. return
  48. count = int(repo["stargazers_count"])
  49. plural = "" if count == 1 else "s"
  50. msg = "\x0303{0}\x0F has \x02{1}\x0F stargazer{2}: {3}"
  51. self.reply(data, msg.format(
  52. repo["full_name"], count, plural, repo["html_url"]))
  53. def handle_user(self, data, arg):
  54. """Handle !stars <user>."""
  55. repos = self.get_user_repos(arg)
  56. if repos is None:
  57. self.reply(data, "User not found.")
  58. return
  59. star_count = sum(repo["stargazers_count"] for repo in repos)
  60. repo_count = len(repos)
  61. star_plural = "" if star_count == 1 else "s"
  62. repo_plural = "" if len(repos) == 1 else "s"
  63. if len(repos) == 100:
  64. star_count = "{0}+".format(star_count)
  65. repo_count = "{0}+".format(repo_count)
  66. if len(repos) > 0:
  67. name = repos[0]["owner"]["login"]
  68. url = repos[0]["owner"]["html_url"]
  69. else:
  70. name = arg
  71. url = "https://github.com/{0}".format(name)
  72. msg = "\x0303{0}\x0F has \x02{1}\x0F stargazer{2} across \x02{3}\x0F repo{4}: {5}"
  73. self.reply(data, msg.format(
  74. name, star_count, star_plural, repo_count, repo_plural, url))
  75. def get_repo(self, repo):
  76. """Return the API JSON dump for a given repository.
  77. Return None if the repo doesn't exist or is private.
  78. """
  79. try:
  80. query = urlopen(self.API_REPOS.format(repo=repo)).read()
  81. except HTTPError:
  82. return None
  83. res = loads(query)
  84. if res and "id" in res and not res["private"]:
  85. return res
  86. return None
  87. def get_user_repos(self, user):
  88. """Return the API JSON dump for a given user's repositories.
  89. Return None if the user doesn't exist.
  90. """
  91. try:
  92. query = urlopen(self.API_USERS.format(user=user)).read()
  93. except HTTPError:
  94. return None
  95. res = loads(query)
  96. if res and isinstance(res, list):
  97. return res
  98. return None