Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. import os
  2. import time
  3. from slackclient import SlackClient
  4. from github import Github
  5.  
  6. GITHUB_ID = os.environ.get('GITHUB_ID')
  7. GITHUB_PASS = os.environ.get('GITHUB_PASS')
  8. github = Github(GITHUB_ID, GITHUB_PASS)
  9.  
  10. BOT_ID = os.environ.get("BOT_ID")
  11. AT_BOT = "<@" + BOT_ID + ">"
  12. EXAMPLE_COMMAND = "do"
  13. BOT_NAME = 'suki-bot'
  14.  
  15. slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
  16.  
  17. org = github.get_organization(os.environ.get('GITHUB_ORG'))
  18. repo = org.get_repo(os.environ.get('GITHUB_REPO'))
  19.  
  20. def do_execute(parts):
  21. if len(parts) < 2:
  22. return "Not Execute."
  23.  
  24. response = "Not Execute."
  25. if parts[1] == 'issues':
  26. response = ""
  27. issues = repo.get_issues()
  28. if issues:
  29. for issue in issues:
  30. response += "[%04d]"%(issue.number) + issue.title + "\n"
  31.  
  32. return response
  33.  
  34. def handle_command(command, channel):
  35. """
  36. Receives commands directed at the bot and determines if they
  37. are valid commands. If so, then acts on the commands. If not,
  38. returns back what it needs for clarification.
  39. """
  40. print(command, channel)
  41. response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
  42. "* command with numbers, delimited by spaces."
  43.  
  44. parts = command.strip().split()
  45. response = do_execute(parts)
  46. try:
  47. slack_client.api_call("chat.postMessage", channel=channel,
  48. text=response, as_user=True)
  49. except Exception:
  50. print("[error] : " + response)
  51.  
  52. def parse_slack_output(slack_rtm_output):
  53. """
  54. The Slack Real Time Messaging API is an events firehose.
  55. this parsing function returns None unless a message is
  56. directed at the Bot, based on its ID.
  57. """
  58. output_list = slack_rtm_output
  59. if output_list and len(output_list) > 0:
  60. for output in output_list:
  61. if output and 'text' in output and AT_BOT in output['text']:
  62. # return text after the @ mention, whitespace removed
  63. return output['text'].split(AT_BOT)[1].strip().lower(), \
  64. output['channel']
  65. return None, None
  66.  
  67. if __name__ == "__main__":
  68. READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
  69. if slack_client.rtm_connect():
  70. print("%s connected and running!"%(BOT_NAME))
  71. while True:
  72. command, channel = parse_slack_output(slack_client.rtm_read())
  73. if command and channel:
  74. handle_command(command, channel)
  75. time.sleep(READ_WEBSOCKET_DELAY)
  76. else:
  77. print("Connection failed. Invalid Slack token or bot ID?")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement