Guest User

Untitled

a guest
Feb 17th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.68 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. NUM_SECS_IN_DAY=86400
  3.  
  4. import json
  5. import time
  6. from datetime import datetime
  7. from argparse import ArgumentParser
  8. from slackclient import SlackClient
  9.  
  10. parser = ArgumentParser(description="Read messages from the specified slack channel")
  11. parser.add_argument("-t", "--slack-token", action="store", dest="slack_token", required=True,
  12. help="Slack API Token")
  13. parser.add_argument("-c", "--channel-id", action="store", dest="channel_id", required=True,
  14. help=("Channel ID - obtained for a channel by reading URL when"
  15. " accessing channel in Slack Client."))
  16. parser.add_argument("-n", "--number-messages-to-read", action="store",
  17. dest="number_messages_to_read",
  18. default=100,
  19. help="Number of messages to read in an attempt")
  20. parser.add_argument("-u", "--username", action="store",
  21. dest="username_to_filter_by",
  22. help="Filter messages by username (generally used for apps)")
  23. parser.add_argument("-uid", "--user-id", action="store",
  24. dest="userid_to_filter_by",
  25. help="Filter messages by userid (generally used by users)")
  26. parser.add_argument("-d", "--days", action="store",
  27. dest="days_to_filter_by",
  28. help="Filter messages to show only ones posted in last X days")
  29. parser.add_argument("-o", "--outfile", action="store", dest="outfile",
  30. default="out-messages-in-channel.txt",
  31. help="Output file for storing messages in channel")
  32. args = parser.parse_args()
  33. channel_id = args.channel_id
  34. number_messages_to_read = args.number_messages_to_read
  35. slack_token = args.slack_token
  36. username_to_filter_by = args.username_to_filter_by
  37. userid_to_filter_by = args.userid_to_filter_by
  38. days_to_filter_by = args.days_to_filter_by
  39. outfile = args.outfile
  40.  
  41. print("[*] Initializing Slack Client with the slack token provided")
  42. sc = SlackClient(slack_token)
  43.  
  44. print("[*] Reading {} messages from channel: {} via SlackClient's channel:history function".format(number_messages_to_read, channel_id))
  45. out = sc.api_call("channels.history", channel=channel_id, count=number_messages_to_read)
  46.  
  47. print("[*] Parsing response to ensure that there were not errors")
  48. if "ok" in out:
  49.  
  50. if out["ok"] == True:
  51.  
  52. print("[+] Messages downloaded ok.")
  53. if "messages" in out:
  54. out_messages = out["messages"]
  55. else:
  56. out_messages = []
  57.  
  58. if username_to_filter_by:
  59. print("[*] Filtering messages by username: {}".format(username_to_filter_by))
  60.  
  61. out_with_username = []
  62.  
  63. num_messages_found_matching_criteria = 0
  64. for message in out_messages:
  65. if "username" in message and message["username"].lower() == username_to_filter_by.lower():
  66. num_messages_found_matching_criteria += 1
  67. out_with_username.append(message)
  68.  
  69. print("[+] Number of messages found matching username: {} criteria: {}".format(username_to_filter_by, num_messages_found_matching_criteria))
  70.  
  71. out_messages = out_with_username
  72.  
  73. if userid_to_filter_by:
  74. print("[*] Filtering messages by userid: {}".format(userid_to_filter_by))
  75.  
  76. out_with_userid = []
  77.  
  78. num_messages_found_matching_criteria = 0
  79. for message in out_messages:
  80. if "user" in message and message["user"].lower() == userid_to_filter_by.lower():
  81. num_messages_found_matching_criteria += 1
  82. out_with_userid.append(message)
  83.  
  84. print("[+] Number of messages found matching user: {} criteria: {}".format(userid_to_filter_by, num_messages_found_matching_criteria))
  85.  
  86. out_messages = out_with_userid
  87.  
  88. if days_to_filter_by:
  89. now = datetime.now()
  90. now_epoch = time.mktime(now.timetuple())
  91.  
  92. print("[*] Filtering messages for ones posted in the last {} days".format(days_to_filter_by))
  93.  
  94. out_within_specified_days = []
  95.  
  96. num_messages_found_matching_criteria = 0
  97. for message in out_messages:
  98. message_epoch_time = float(message["ts"])
  99. # print("[v] message_epoch_time = {}, now_epoch = {}".format(message_epoch_time, now_epoch))
  100.  
  101. if (now_epoch - message_epoch_time) < (int(days_to_filter_by) * NUM_SECS_IN_DAY):
  102. num_messages_found_matching_criteria += 1
  103. out_within_specified_days.append(message)
  104.  
  105. print("[+] Number of messages found matching days to filter by: {} criteria: {}".format(days_to_filter_by, num_messages_found_matching_criteria))
  106. out_messages = out_within_specified_days
  107.  
  108. print("[*] Writing messages in output as JSON to file: {}".format(outfile))
  109. formatted_out = json.dumps(out_messages, indent=4)
  110. with open(outfile, "w+") as f:
  111. f.write(formatted_out)
  112. else:
  113.  
  114. print("[-] Error occurred when downloading the messages from channel: {}".format(channel_id))
  115. if "error" in out:
  116. error = out["error"]
  117. print("[-] Error that occurred: {}".format(error))
  118. else:
  119.  
  120. print("[-] No 'error' key status returned in JSON output - something went wrong.")
  121. print("[-] Dumping the entire response: ")
  122. formatted_out = json.dumps(out, indent=4)
  123. print("{}".format(formatted_out))
  124.  
  125. else:
  126.  
  127. print("[-] No 'ok' key status returned in JSON output - something went wrong.")
  128. print("[-] Dumping the entire response: ")
  129. formatted_out = json.dumps(out, indent=4)
  130. print("{}".format(formatted_out))
Add Comment
Please, Sign In to add comment