How do I extract posts from a Mattermost channel?

Last week I faced the challenge to extract user posts from Mattermost without using the database. I checked the Mattermost API documentation and came up with a few simple curl commands to achieve this. You can easily build this into a python script or pipe the result into a JSON file to process it afterwards.

Here is what I did:

# Please replace the capital letter words with your environment, tokens etc.
# Login using your credentials (System-Admin)
curl -i -d '{"login_id":"USERNAME","password":"PASSWORD"}' https://MATTERMOST/api/v4/users/login

# Gives you a token for next operations like this:
token: wqgwrca75ibumynq7p1kpzbutw

# Search the team to get the team ID
curl -i -H 'Authorization: Bearer TOKEN' -X POST -d '{ "term": "TEAMNAME"}' https://MATTERMOST/api/v4/teams/search

# Gives you a team ID like this:
"id":"trwd6spc8fd65pymp3dy8rtg4o"

# Search a channel in the team you want to get the posts from:
curl -i -H 'Authorization: Bearer TOKEN' -X POST -d '{ "term": "CHANNELNAME"}' https://MATTERMOST/api/v4/teams/TEAMID/channels/search

# Gives you a channel ID like this:
"id":"z8d65yhzxfrh5nzadyp9aa56qw"

# Get the posts from the channel
curl -i -H 'Authorization: Bearer TOKEN' https://MATTERMOST/api/v4/channels/CHANNELID/posts

Hope this helps!
Christian

7 Likes

On top of the suggestion by @cjohannsen81, you might also be interested to give the database a try (if you don’t prefer to use the API) by using the following query:

SELECT
Teams.DisplayName AS Team,
Channels.DisplayName AS Channel,
Channels.Type,
(SELECT COUNT(*) FROM mattermost.Posts WHERE Posts.ChannelId = Channels.Id AND Posts.DeleteAt = 0) AS Posts
FROM
mattermost.Channels
JOIN
mattermost.Teams ON Channels.TeamId = Teams.Id
WHERE
Channels.DeleteAt = 0 AND
Channels.Type <> 'D' AND
Teams.DeleteAt = 0
ORDER BY
Team, Channel;

Credits to Craig Vitter for sharing this in the get_posts_by_team_and_channel.sql page.