redditinfo.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import requests
  2. import version
  3. try:
  4. import praw
  5. successful_import = True
  6. except ImportError:
  7. print "WARNING: redditinfo requires praw (https://github.com/praw-dev/praw/, or pip install praw)."
  8. successful_import = False
  9. if successful_import is True:
  10. import re
  11. from event import Event
  12. class RedditInfo:
  13. def __init__(self, events=None, printer_handle=None, bot=None, say=None):
  14. self.events = events
  15. self.printer = printer_handle
  16. self.interests = ['__reddit__']
  17. self.bot = bot
  18. self.say = say
  19. self.user_agent = 'pybot ' + version.__version__ + ' by /u/hlmtre; http://bitbucket.org/hlmtre/pybot'
  20. self.help = None
  21. reddit = Event("__reddit__")
  22. reddit.define("https?://www.reddit.com/[\S]+|https?://reddit.com/[\S]+|reddit.com/[\S]+")
  23. reddit.subscribe(self)
  24. self.bot.register_event(reddit, self)
  25. def handle(self, event):
  26. url = re.search("https?://www.reddit.com/[\S]+|https?://reddit.com/[\S]+|reddit.com/[\S]+", event.line).group(0)
  27. me = praw.Reddit(self.user_agent)
  28. try:
  29. s = me.get_submission(url)
  30. except requests.exceptions.MissingSchema:
  31. s = me.get_submission('http://'+url)
  32. except TypeError:
  33. return
  34. message = '[REDDIT] ' + s.title
  35. if s.is_self:
  36. message = message + ' (self.' + s.subreddit.display_name + ')'
  37. else:
  38. message = message + ' to r/' + s.subreddit.display_name
  39. if s.over_18:
  40. message = message + ' 05[NSFW]'
  41. #TODO implement per-channel settings db, and make this able to kick
  42. if s.author:
  43. author = s.author.name
  44. else:
  45. author = '[deleted]'
  46. message = (message + ' | ' + author)
  47. #TODO add creation time with s.created
  48. self.printer("PRIVMSG " + event.channel + " :" + message + "\n")