Skip to content

Instantly share code, notes, and snippets.

@so298
Last active May 31, 2024 23:12
Show Gist options
  • Save so298/e219e2b7a3f906d600ce7ec3b5b6adda to your computer and use it in GitHub Desktop.
Save so298/e219e2b7a3f906d600ce7ec3b5b6adda to your computer and use it in GitHub Desktop.
Simple command line tool to run a command and send a message to a Slack webhook if the command fails. (No external library dependencies!!)
#!/usr/bin/env python3
'''
Command line tool to run a command and send a message to a Slack webhook if the command fails.
'''
import subprocess
import urllib
import urllib.request
import urllib.parse
import argparse
def call_slack_webhook(webhook, message):
data = urllib.parse.urlencode({'payload': f'{{"text": "{message}"}}'}).encode()
req = urllib.request.Request(webhook, data=data)
urllib.request.urlopen(req)
def main():
parser = argparse.ArgumentParser(description='Watch subprocesses')
parser.add_argument('--slack_webhook', help='Slack webhook URL')
parser.add_argument('command', nargs=argparse.REMAINDER, help='Command to run')
args = parser.parse_args()
webhook = args.slack_webhook
command = args.command
if not command:
parser.error('No command provided')
command_str = ' '.join(command)
print(f'Running command: `{command_str}`')
proc = subprocess.run(command)
if proc.returncode != 0:
message = f'Command failed with exit code {proc.returncode}: `{command_str}`'
print(message)
if webhook:
call_slack_webhook(webhook, message)
else:
message = f'Command successfully ended: `{command_str}`'
print(message)
if webhook:
call_slack_webhook(webhook, message)
return proc.returncode
if __name__ == '__main__':
exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment