Skip to content

Instantly share code, notes, and snippets.

@raybuhr
Created March 1, 2016 07:22
Show Gist options
  • Save raybuhr/bc6b11d33dc59dc04002 to your computer and use it in GitHub Desktop.
Save raybuhr/bc6b11d33dc59dc04002 to your computer and use it in GitHub Desktop.
function to pull slack message history
# coding: utf-8
from slacker import Slacker
import pandas as pd
def pull_messages(slack_api_token, channel_name, from_time=None):
"""
slack_api_token can be registered at https://api.slack.com/tokens.
from_time assumes unix_timestamp, such as 1456709957.004145
-- mysql can convert between unix and posix time easily
with the function FROM_UNIXTIME so best to just keep that
form since it is how the slack api delivers the json payload
example:
datalife = pull_messages(SLACK_API_TOKEN, 'datalife')
"""
slack = Slacker(slack_api_token)
slack_channels = slack.channels.list()
channels = slack_channels.body['channels']
channels = pd.DataFrame.from_dict(channels)
channel_ = channels[channels['name'] == channel_name]['id']
data = slack.channels.history(
channel_.values[0], count=1000, oldest=from_time)
msg = pd.DataFrame.from_dict(data.body['messages'])
slack_users = slack.users.list()
users = slack_users.body['members']
users = pd.DataFrame.from_dict(users)
users = users[['id', 'profile']]
user_profile = pd.DataFrame(list(users['profile']))
users = pd.concat([users, user_profile], axis=1)
users = users[['id', 'email', 'real_name']]
ch_history = pd.merge(
msg, users, left_on='user', right_on='id', how='left')
ch_history = ch_history[['ts', 'text', 'user', 'email', 'real_name']]
return ch_history
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment