Skip to content

Instantly share code, notes, and snippets.

@deseven
Last active January 20, 2024 03:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save deseven/dd03b26895232465211ef09f75400d94 to your computer and use it in GitHub Desktop.
Save deseven/dd03b26895232465211ef09f75400d94 to your computer and use it in GitHub Desktop.
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
@komodin
Copy link

komodin commented Jun 10, 2021

Thanks! Your script helped me a lot.

@deseven
Copy link
Author

deseven commented Jun 11, 2021

You're welcome!

@karthik1710
Copy link

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