Last active
February 25, 2025 06:36
-
-
Save deseven/dd03b26895232465211ef09f75400d94 to your computer and use it in GitHub Desktop.
Upload file to Mattermost (API v4)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Thanks. It helped me a lot in CI/CD Deployments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're welcome!