Sending Notification to Slack from Jupyter Notebook

If you want to run a cell that may take a long time, it would be helpful if Jupyter sends a notification when the cell is finished. I implemented the feature by just combining Jupyter’s custom magic and Slack’s Incoming Webhooks.

The following is my implementation. Put it in ~/.ipython/profile_default/startup/nbnotifier.py to call from Jupyter.

import json
import socket

from IPython.core.magic import register_line_magic
import requests


@register_line_magic
def slack(line):
    webhooks_url = '<Incoming Webhooks URL>'
    payload = {
        'text':
        line
        if line else 'A cell that was running on *{}* has finished.'.format(
            socket.gethostname())
    }
    r = requests.post(webhooks_url, data=json.dumps(payload))

Note that '<Incoming Webhooks URL>' should be replaced with yours.

The following shows usage. By writing %slack [message] at the end of the cell, you can receive notification when it has finished.

Jupyter Slack
nbnotifier_no-arg_jupyter > nbnotifier_no-arg_slack
nbnotifier_no-arg_jupyter > nbnotifier_arg_slack
Avatar
Ryo Takahashi
Ph.D. student at Tohoku University
comments powered by Disqus