Advertisement
Guest User

Untitled

a guest
Jun 29th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. from slackclient import SlackClient
  2. import time
  3. import re
  4. import datetime
  5.  
  6.  
  7. class Bot(object):
  8.  
  9. def __init__(self, token, searches):
  10. self.searches = searches
  11. self.client = SlackClient(token)
  12. self.username = {}
  13. self.user_id = {}
  14.  
  15. def run(self):
  16. if self.client.rtm_connect():
  17. try:
  18. self.user_id = self.client.api_call("auth.test")['user_id']
  19. self.username = self.client.api_call("auth.test")['user']
  20. self._log(self.username + ": " + self.user_id)
  21. except:
  22. print Exception
  23. while True:
  24. self.process_messages(self.client.rtm_read())
  25. time.sleep(0.25)
  26. else:
  27. self._log("Connection failed.")
  28.  
  29. def _log(self, message, level=' DEBUG '):
  30. """
  31. TODO this should actually put logs somewhere useful;
  32. """
  33. print str(datetime.datetime.utcnow()) + level + message
  34.  
  35. def filter_speak(self, room, message):
  36. """
  37. posts a message to a channel if it matches the call.
  38. """
  39. for call in self.searches:
  40. response = self.searches[call]
  41. if re.search(call, message):
  42. self.client.api_call("chat.postMessage", as_user="true",
  43. channel=room, text=response)
  44.  
  45. def process_messages(self, messages):
  46. for msg in messages:
  47. # We're only interested in entries of type "message"
  48. if msg['type'] == "message":
  49. # TODO also check the text of expanded links.
  50. if 'text' in msg:
  51. body = msg['text']
  52. elif 'subtype' in msg:
  53. if msg['subtype'] == "message_changed":
  54. body = msg['message']['text']
  55. else:
  56. self._log(msg + " didn't appear to have text or subtype?")
  57.  
  58. if 'user' in msg:
  59. if msg['user'] != self.user_id:
  60. self.filter_speak(message=body, room=msg['channel'])
  61.  
  62. from app import Bot
  63. from os import environ
  64.  
  65. pairs = {}
  66.  
  67. pairs["[kK]nock[, -]*[kK]nock"] = "Who's there?"
  68.  
  69. pope_bot = Bot(environ['API_TOKEN'], pairs)
  70. pope_bot.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement