WebHooks & Python & Discord! Oh My!

So I had a need earlier on today. The need for simple end-user notifications. This need has some backstory, however...

The plex container that I run on Docker is basically bulletproof. It does everything super quickly and is easy to restart for updates or to clear out some disk I/O issue with my NAS. The NAS is the only thing that's really causing it issues because it's a 5 year old Drobo which is in serious need of an upgrade! So if the Drobo locks up and kills all of the I/O to it, the containers need a reboot. Oddly enough, the Drobo itself doesn't need a reboot (or even to be remounted) but that's an investigation for another day. Here, we come to my need: to alert users when the container was 'down for maintenance.'

I've recently started using Discord for support issues with anything I host for friends and family (NextCloud, Plex, DokuWiki, etc) because it's easy to make channels for each type of support request, as well as easily message either an individual user or a whole group of users at once. Every time I'm doing maintenance on the container, I have to post in the channel to let everyone know that it's happening and that takes more than 0 effort. This clearly requires automation!

Discord offers WebHook functionality which I've found to be super useful for this purpose. WebHooks are a bit like a reverse API. The server sends data whenever it has it, as opposed to an API which the client queries on a regular basis and can either get data or get a 'nope' in response. Kind of wasteful when you think about it that way. I found this video quite helpful when searching out the bare essentials. You can make a WebHook that posts to a specific channel on your server (useful for my purposes as I can have a seperate WebHook for each of the above hosted applications). I'm also an avid Python fan, therefore everything musts be automated in Python! I'm low key getting kind of into GO lately though

Luckily, if you don't count the shebang, it's 4 lines of code!


import requests

discord_url = "https://discordapp.com/api/webhooks/<hookid>/<tokenid>"

data = {"content": "Plex container is rebooting..."}

requests.post(discord_url, data=data)

There you have it! All I've done with this so far is make a script that restarts the plex container and it calls this script just before reboot. I'm planning to add some more logic to it for monitoring purposes (e.g. time the container restart, see if it hangs, etc) and in the future set up a log monitor on some of the containers so that if they can't see the NAS for whatever reason, a script fires off a couple of WebHooks posts and then restarts it for me. The ultimate in laziness automation!