-
-
Save pydemo/85513de751c735e32c3c5c09224b64f7 to your computer and use it in GitHub Desktop.
count slack messages posted to a channel by user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
''' | |
Script to count messages by user posted to a channel for a given date range. | |
Install: | |
# sudo pip install slackclient | |
Also you will need to obtain a slack API token: | |
https://api.slack.com/docs/oauth-test-tokens | |
Usage Example: | |
# python SLACK_SEARCH_FROM=2016-11-01 SLACK_SEARCH_TO=2016-12-01 \ | |
SLACK_CHANNEL_NAME=general SLACK_API_TOKEN=<token> \ | |
slack-messages-by-user.py | |
''' | |
import os | |
from datetime 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"] | |
oldest = (datetime.strptime(date_from, "%Y-%m-%d") - datetime(1970, 1, 1)).total_seconds() | |
latest = (datetime.strptime(date_to, "%Y-%m-%d") - datetime(1970, 1, 1)).total_seconds() | |
sc = SlackClient(slack_token) | |
users_list = sc.api_call("users.list") | |
users = {} | |
for user in users_list['members']: | |
users[user['id']] = user['profile']['first_name'] + ' ' + user['profile']['last_name'] | |
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) | |
history = sc.api_call("channels.history", channel=channel_id, oldest=oldest, latest=latest) | |
posts_by_user = {} | |
for message in history['messages']: | |
if message['user'] in posts_by_user: | |
posts_by_user[users[message['user']]] += 1 | |
else: | |
posts_by_user[users[message['user']]] = 1 | |
for user, count in posts_by_user.items(): | |
print user, 'posted', count, 'messages' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment