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:

# 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:

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

Hope this helps!


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:

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

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