Guest User

Untitled

a guest
Oct 26th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.86 KB | None | 0 0
  1. import os
  2. import time
  3. import re
  4. from slackclient import SlackClient
  5. import MySQLdb
  6.  
  7. # instantiate Slack client
  8. slack_client = SlackClient('xoxb-XXXXXXXXXXXXXXXXXXX')
  9. # starterbot's user ID in Slack: value is assigned after the bot starts up
  10. starterbot_id = None
  11.  
  12. # database
  13. db_host = '..'
  14. db_name = '..'
  15. db_user = '..'
  16. db_password = '..'
  17.  
  18. # constants
  19. RTM_READ_DELAY = 2 # 2 second delay between reading from RTM
  20. EXAMPLE_COMMAND = "Passoword: || Module: || SQL: "
  21. MENTION_REGEX = "^<@(|[WU].+?)>(.*)"
  22.  
  23. help = "To get password for a user (Password: email_id) \n To activate company module (Module: all company_id) \n Can write your own SQL queries (SQL: query) \n Happy Coding. :-)"
  24.  
  25. ///
  26. SQL Commands
  27. ///
  28.  
  29. def parse_bot_commands(slack_events):
  30. """
  31. Parses a list of events coming from the Slack RTM API to find bot commands.
  32. If a bot command is found, this function returns a tuple of command and channel.
  33. If its not found, then this function returns None, None.
  34. """
  35. for event in slack_events:
  36. if event["type"] == "message" and not "subtype" in event:
  37. user_id, message = parse_direct_mention(event["text"])
  38. if user_id == starterbot_id:
  39. return message.lower(), event["channel"]
  40. return None, None
  41.  
  42.  
  43. def parse_direct_mention(message_text):
  44. """
  45. Finds a direct mention (a mention that is at the beginning) in message text
  46. and returns the user ID which was mentioned. If there is no direct mention, returns None
  47. """
  48. matches = re.search(MENTION_REGEX, message_text)
  49. # the first group contains the username, the second group contains the remaining message
  50. return (matches.group(1), matches.group(2).strip()) if matches else (None, None)
  51.  
  52.  
  53. def handle_command(command, channel):
  54. """
  55. Executes bot command if the command is known
  56. """
  57.  
  58. # Open database connection
  59. db = MySQLdb.connect(db_host, db_user, db_password, db_name)
  60.  
  61. # Default response is help text for the user
  62. default_response = "Not sure what you mean. Try *{}* ".format(EXAMPLE_COMMAND)
  63.  
  64. # Finds and executes the given command, filling in response
  65. response = None
  66. if command in ['hi', 'hey', 'hello']:
  67. response = 'Hey.. How may I help you.'
  68. if command == 'help':
  69. response = help
  70. else:
  71. try:
  72. command = command.split(':')
  73. if command[0] == 'password':
  74. response = get_password(command[2], db)
  75.  
  76. if command[0] == 'module':
  77. response = module_activation(command[1], db)
  78.  
  79. if command[0] == 'sql':
  80. response = raw_sql(command[1], db)
  81. except Exception as e:
  82. print e
  83.  
  84. db.close()
  85.  
  86. # Sends the response back to the channel
  87. slack_client.api_call(
  88. "chat.postMessage",
  89. channel=channel,
  90. text=response or default_response
  91. )
  92.  
  93.  
  94. def get_password(command, db):
  95. response = ''
  96. cursor = db.cursor()
  97. try:
  98. email = command.split('|')
  99. sql = password.format(email[0])
  100. cursor.execute(sql)
  101. data = cursor.fetchall()
  102. if data:
  103. for d in data:
  104. response += 'Name: ' + str(d[0]) + ' ' + str(d[1]) + ', Email: ' + str(d[2]) + ', Password: ' + str(d[3]) + ', Company Id: ' + str(d[4])
  105. else:
  106. response = 'No data found.'
  107. except Exception as e:
  108. print(e)
  109. pass
  110.  
  111. return response
  112.  
  113.  
  114. def module_activation(cmd, db):
  115. cursor = db.cursor()
  116. try:
  117. all_modules = [inventory, reporting, integration, access, tagging, multiple_unit, gst, payment, bi, production, approval]
  118. module, company = cmd.split(' ')
  119. if module == 'all':
  120. for module in all_modules:
  121. for script in module:
  122. cursor.execute(script.format(company))
  123.  
  124. response = 'Done'
  125. except:
  126. response = 'Not Done.'
  127.  
  128. return response
  129.  
  130.  
  131. def raw_sql(sql, db):
  132. response = ''
  133. if sql.startswith('happycoding'):
  134. sql = sql.replace('happycoding', '')
  135. cursor = db.cursor()
  136. cursor.execute(sql)
  137. response = cursor.fetchall()
  138. return response
  139.  
  140.  
  141. if __name__ == "__main__":
  142. if slack_client.rtm_connect(with_team_state=False):
  143. print("Starter Bot connected and running!")
  144. # Read bot's user ID by calling Web API method `auth.test`
  145. starterbot_id = slack_client.api_call("auth.test")["user_id"]
  146. while True:
  147. command, channel = parse_bot_commands(slack_client.rtm_read())
  148. if command == 'exit':
  149. slack_client.api_call(
  150. "chat.postMessage",
  151. channel=channel,
  152. text = 'Bye..'
  153. )
  154. break
  155. if command:
  156. handle_command(command, channel)
  157. time.sleep(RTM_READ_DELAY)
  158. else:
  159. print("Connection failed. Exception traceback printed above.")
Add Comment
Please, Sign In to add comment