Mattermost Recipe: Notify Mattermost when a directory is changed
Problem
You’re waiting for a file to be uploaded to your server, but don’t want to keep refreshing your FTP client
Solution
1. Install inotify-tools
inotify-tools
is a package available for most Unix systems that includes inotifywatch
and inotifywait
utilities. To install:
CentOS/Red Hat:
sudo yum install inotify-tools
Ubuntu/Debian:
sudo apt-get install inotify tools
2. Create an incoming webhook in Mattermost
Instructions are available in our docs.
3. Write a script
Here’s a simple script that will watch a directory and send a request to the Webhook.
#!/bin/bash
webhook_url="https://chat.example.com/hooks/dk3xou5fh7ham7xhhezjtr5hxj"
if [[ -d $1 ]]; then
watch_path=$1
else
echo "$1 must be a directory"
exit 1
fi
inotifywait -q -m $watch_path -e create -e moved_to |
while read path action file; do
message_text="The file $file appeared in directory $path via $action"
curl --silent --output /dev/null -i -X POST -H 'Content-Type: application/json' -d "{\"text\": \"$message_text\"}" $webhook_url
done
To run it, copy it to a file, e.g. watch-directory.sh
, make it executable with chmod +x
and then run it like this:
$ ./watch-directory.sh ~/test
Then, in another terminal, cd
to the directory you’re watching, and run this command:
$ touch a_file.txt
$ cp ~/src.txt test
$ mv ~/main.rb test/
When you do that, you should see these messages posted to Mattermost:
Discussion
inotifywait
uses Linux’s inotify
API, which provides system monitoring information. This API has been ported to numerous programming languages including Go so it’s possible to make a Mattermost plugin using it.
inotifywait
can monitor several different kinds of file events. For example, checking for the CLOSE_WRITE
event will let you know when a file has been changed. This could be used to monitor configuration files for changes. The UNMOUNT
event, which is triggered when the remote filesystem is unmounted, which could notify you if a fileserver goes down.
Because inotify
has an API there are a lot of other solutions. In my first recipe I used incrontab
to monitor a directory to trigger video processing. But if you need to quickly monitor a directory from a terminal inotifywait
is the way to go.
Feedback appreciated!