Skip to content

Instantly share code, notes, and snippets.

@demmer
Created December 2, 2016 22:59
Show Gist options
  • Save demmer/617afb2575c445ba25afc432eb37583b to your computer and use it in GitHub Desktop.
Save demmer/617afb2575c445ba25afc432eb37583b to your computer and use it in GitHub Desktop.
count slack messages posted to a channel by user
#!/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'
@eldarbogdanov
Copy link

Looks like you meant if users[message['user']] in posts_by_user: in place of if message['user'] in posts_by_user:.

Also, at least these days, the API is paginated, and only returns latest 100 messages by default.

@marians
Copy link

marians commented Jan 10, 2020

The code example is no longer applicable to the current slackclient. It starts with the import statement (should be import slack) and continues with creation of a client (client = slack.WebClient(slack_token)).

@shubhamgajbhiye1994
Copy link

Hi , If I want triggered based response then how we can perform the task?

@Ash515
Copy link

Ash515 commented Sep 8, 2021

Its shows error in method depreciation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment