Skip to content

Instantly share code, notes, and snippets.

@robrant
Last active October 11, 2021 20:56
Show Gist options
  • Save robrant/f7ab157795aae11514fa78f4c284e332 to your computer and use it in GitHub Desktop.
Save robrant/f7ab157795aae11514fa78f4c284e332 to your computer and use it in GitHub Desktop.
Count number of messages in a slack channel
#!/usr/bin/python
'''
Script to count messages by user posted to a channel for a given date range.
Install:
# sudo pip install -r requirements.txt
Also you will need to obtain a slack API token:
https://api.slack.com/docs/oauth-test-tokens
Usage Example:
# SLACK_SEARCH_FROM=2018-07-30 \
SLACK_SEARCH_TO=2018-08-20 \
SLACK_CHANNEL_NAME=dev \
SLACK_API_TOKEN=<token> \
python slack-count-messages.py
'''
import os
import json
import datetime
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
channel_name = os.environ["SLACK_CHANNEL_NAME"]
date_from = os.environ["SLACK_SEARCH_FROM"]
date_to = os.environ["SLACK_SEARCH_TO"]
sc = SlackClient(slack_token)
# Get the channel ids
channels = sc.api_call("channels.list")
channel_id = None
for channel in channels['channels']:
if channel['name'] == channel_name:
channel_id = channel['id']
if channel_id == None:
raise Exception("cannot find channel " + channel_name)
countable_messages = []
messages_bots = []
messages_with_attachment = []
messages_with_subtypes = []
reply_counts = []
reaction_counts = []
oldest = datetime.datetime.strptime(date_from, "%Y-%m-%d")
latest = datetime.datetime.strptime(date_to, "%Y-%m-%d")
number_days = (latest - oldest).days
delta = datetime.timedelta(days=2).total_seconds()
query_oldest = (oldest - datetime.datetime(1970, 1, 1)).total_seconds()
for i in range(1, number_days):
query_latest = query_oldest + delta
#print datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=query_oldest), datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=query_latest)
history = sc.api_call("channels.history", channel=channel_id, oldest=query_oldest, latest=query_latest)
query_oldest = query_latest
# Build master set of messages from multiple time range calls
for message in history['messages']:
if message['type'] != 'message':
continue
if message.has_key('bot_id'):
messages_bots.append(message)
continue
if message.has_key('subtype'):
messages_with_subtypes.append(message)
continue
if message.has_key('attachments'):
messages_with_attachment.append(message)
if message.has_key('replies') and not message.has_key('parent_user_id'):
reply_count = len(message['replies'])
reply_counts.append(reply_count)
if message.has_key('reactions') and not message.has_key('parent_user_id'):
message_reaction_count = 0
for reaction in message['reactions']:
message_reaction_count += int(reaction['count'])
reaction_counts.append(message_reaction_count)
countable_messages.append(message)
mean_reply_count = sum(reply_counts)/float(len(reply_counts))
mean_reaction_count = sum(reaction_counts)/float(len(reaction_counts))
# response = {
# "start_date" : date_from,
# "end_date" : date_to,
# "channel" : channel_name,
# "message_count" : len(countable_messages),
# "message_mean_replies" : mean_reply_count,
# "message_with_attachment_count" : len(messages_with_attachment)
# }
print 'Messages this quarter: {}'.format(len(countable_messages))
print 'With attachments: {}'.format(len(messages_with_attachment))
print 'Mean replies per top level message: {}'.format(mean_reply_count)
print 'Mean reactions per top level message: {}'.format(mean_reaction_count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment