Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Upload file to Mattermost (API v4)
#!/bin/bash
# your mattermost installation url
mattermost="https://example.com"
# bot token, get it in Integrations > Bot Accounts
token=abcdef123456
# set to true for debug output
debug=false
checkDep() {
for prog in "$@"; do
command -v $prog >/dev/null 2>&1 || { echo "Please install these dependencies first: $@" && return 1; }
done
}
checkDep curl jq || exit 1
if [ ! -f "$2" ]; then
echo "syntax: $0 channel_id path_to_file"
exit 2
fi
if [ "$debug" == "true" ]; then
curlParam=''
else
curlParam='-s'
fi
output=$(curl $curlParam --location --request POST "$mattermost/api/v4/files?channel_id=$1" \
--header "Authorization: Bearer $token" \
--header "Content-Type: multipart/form-data" \
--form "files=@$2")
if [ "$debug" == "true" ]; then
echo "$output"
fi
file_id=$(echo "$output" | jq -M -c -r '.file_infos[].id' 2>/dev/null)
if [ -z "$file_id" ]; then
echo "Failed to upload file :("
exit 3
fi
output=$(curl $curlParam --location --request POST "$mattermost/api/v4/posts" \
--header "Authorization: Bearer $token" \
--header "Content-Type: application/json" \
--data "{\"file_ids\":[\"$file_id\"],\"message\":\"\",\"channel_id\":\"$1\"}")
if [ "$debug" == "true" ]; then
echo "$output"
fi
post_id=$(echo "$output" | jq -M -c -r '.id' 2>/dev/null)
if [ -z "$post_id" ]; then
echo "Failed to create post :("
exit 4
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.