WikiLinker.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import json
  2. import logging
  3. import re
  4. import time
  5. SUBREDDIT_NAME = 'Piracy'
  6. console_logger = logging.getLogger('console_logger')
  7. class Linker:
  8. keywords_url = 'https://www.reddit.com/r/Piracy/wiki/keywords_json'
  9. keywords_json_file = 'settings/WikiLinker_keywords.json'
  10. cache_frequency_secs = 5 * 60
  11. max_matches = 3
  12. def __init__(self, reddit):
  13. self.subreddit = reddit.subreddit(SUBREDDIT_NAME)
  14. self.last_cached = 0
  15. self.keywords = None
  16. self._load_keywords()
  17. def handle_comment(self, comment):
  18. if comment.subreddit.display_name != SUBREDDIT_NAME:
  19. return
  20. self._load_keywords()
  21. kw_matches = self._get_kw_matches(comment)
  22. if kw_matches:
  23. self._send_reply(comment, kw_matches)
  24. def _get_kw_matches(self, comment):
  25. kw_matches = []
  26. for keyword in self.keywords:
  27. keyword_re = fr'!{keyword}\b'
  28. if re.search(keyword_re, comment.body, re.IGNORECASE):
  29. kw_matches.append(keyword)
  30. if len(kw_matches) >= self.max_matches:
  31. break
  32. return kw_matches
  33. def _send_reply(self, comment, kw_matches):
  34. console_logger.info(f" Replying to keyword(s)")
  35. reply_body = 'Here are your link(s)!\n\n'
  36. for i, kw in enumerate(kw_matches):
  37. wiki_name = self.keywords[kw][0]
  38. wiki_url = self.keywords[kw][1]
  39. reply_body += f'{i + 1}. Link to [{wiki_name}]({wiki_url})\n\n'
  40. reply_body += f' \n\n---\n\n^^^^I ^^^^am ^^^^a ^^^^Bot. ^^^^Here ^^^^is ^^^^a [^^^^list ^^^^of ^^^^keywords.]({self.keywords_url})'
  41. myreply = comment.reply(reply_body)
  42. myreply.disable_inbox_replies()
  43. def _load_keywords(self):
  44. if time.time() - self.last_cached > self.cache_frequency_secs:
  45. with open(self.keywords_json_file, 'r', encoding='utf8') as f:
  46. self.keywords = json.load(f)
  47. self.last_cached = time.time()