redditinfo.py 1.7 KB

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