Advertisement
obernardovieira

Slack Bot (say hi!)

Oct 15th, 2016
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. #### app/botfunc.py
  2.  
  3.  
  4. def bot_process_message(command):
  5.     response = 'I cant understand!'
  6.     if command.startswith('hi'):
  7.         response = 'hi friend'
  8.  
  9.     return response
  10.  
  11.  
  12.  
  13.  
  14.  
  15. #### app/bot.py
  16.  
  17. import os
  18. import time
  19. from slackclient import SlackClient
  20. import json
  21. from botfunc import bot_process_message
  22. from dotenv import load_dotenv
  23. load_dotenv(".env")
  24.  
  25.  
  26. BOT_ID = os.environ.get("BOT_ID")
  27. SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
  28. AT_BOT = "<@" + str(BOT_ID) + ">"
  29. slack_client = SlackClient(SLACK_BOT_TOKEN)
  30.  
  31.  
  32. def handle_command(command, channel):
  33.     response = bot_process_message(command)
  34.  
  35.     slack_client.api_call("chat.postMessage", channel=channel,
  36.                           text=response, as_user=True)
  37.  
  38.  
  39. def parse_slack_output(slack_rtm_output):
  40.     print(slack_rtm_output)
  41.     output_list = slack_rtm_output
  42.  
  43.     if output_list and len(output_list) > 0:
  44.         for output in output_list:
  45.             if output and 'text' in output and AT_BOT in output['text']:
  46.                 # return text after the @ mention, whitespace removed
  47.                 return output['text'].split(AT_BOT)[1].strip().lower(), \
  48.                    output['channel']
  49.  
  50.     return None, None
  51.  
  52. def run_bot():
  53.     if slack_client.rtm_connect():
  54.         print("bot connected and running!")
  55.         while True:
  56.             command, channel = parse_slack_output(slack_client.rtm_read())
  57.             if command and channel:
  58.                 handle_command(command, channel)
  59.             time.sleep(1)
  60.     else:
  61.         print("Connection failed. Invalid Slack token or bot ID?")
  62.  
  63.  
  64.  
  65.  
  66.  
  67. #### main.py
  68.  
  69. from app.bot import run_bot
  70.  
  71. if __name__ == "__main__":
  72.     run_bot()
  73.  
  74.  
  75. ### .env
  76. BOT_ID = (your bot id)
  77. SLACK_BOT_TOKEN = (your token)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement