Giter Club home page Giter Club logo

ntfy's Introduction

About ntfy

Version_ Docs_ Build_ WinBuild_ Coverage_ SayThanks_

ntfy brings notification to your shell. It can automatically provide desktop notifications when long running commands finish or it can send push notifications to your phone when a specific command finishes. Confused? This video demonstrates some of this functionality:

image

Quickstart

$ sudo pip install ntfy
$ ntfy send test
# send a notification when the command `sleep 10` finishes
# this sends the message '"sleep 10" succeeded in 0:10 minutes'
$ ntfy done sleep 10
$ ntfy -b pushover -o user_key t0k3n send 'Pushover test!'
$ ntfy -t 'ntfy' send "Here's a custom notification title!"
$ echo -e 'backends: ["pushover"]\npushover: {"user_key": "t0k3n"}' > ~/.ntfy.yml
$ ntfy send "Pushover via config file!"
$ ntfy done --pid 6379  # pid extra
$ ntfy send ":tada: ntfy supports emoji! :100:"  # emoji extra
# Enable shell integration
$ echo 'eval "$(ntfy shell-integration)"' >> ~/.bashrc

Install

The install technique in the quickstart is the suggested method of installation. It can be installed in a virtualenv, but with some caveats: Linux notifications require --system-site-packages for the virtualenv and OS X notifications don't work at all.

๐Ÿง NOTE: Linux Desktop Notifications require Python DBUS bindings. See here for more info.

Shell integration

ntfy has support for automatically sending notifications when long running commands finish in bash and zsh. In bash it emulates zsh's preexec and precmd functionality with rcaloras/bash-preexec. To enable it add the following to your .bashrc or .zshrc:

eval "$(ntfy shell-integration)"

By default it will only send notifications for commands lasting longer than 10 seconds and if the terminal is focused. Terminal focus works on X11(Linux) and with Terminal.app and iTerm2 on MacOS. Both options can be configured via the --longer-than and --foreground-too options.

To avoid unnecessary notifications when running interactive programs, programs listed in AUTO_NTFY_DONE_IGNORE don't generate notifications. For example:

export AUTO_NTFY_DONE_IGNORE="vim screen meld"

Extras

ntfy has a few features that require extra dependencies.
  • ntfy done -p $PID requires installing as pip install ntfy[pid]
  • emoji support requires installing as pip install ntfy[emoji]
  • XMPP support requires installing as pip install ntfy[xmpp]
  • Telegram support requires installing as pip install ntfy[telegram]
  • Instapush support requires installing as pip install ntfy[instapush]
  • Slack support requires installing as pip install ntfy[slack]
  • Slack Incoming webhook - simpler slack implementation that doesn't have additional dependencies
  • Rocket.Chat support requires installing as pip install ntfy[rocketchat]

To install multiple extras, separate with commas: e.g., pip install ntfy[pid,emoji].

Configuring ntfy

ntfy is configured with a YAML file stored at ~/.ntfy.yml or in standard platform specific locations:

  • Linux - ~/.config/ntfy/ntfy.yml
  • macOS - ~/Library/Application Support/ntfy/ntfy.yml
  • Windows - C:\Users\<User>\AppData\Local\dschep\ntfy.yml

Backends

The backends key specifies what backends to use by default. Each backend has its own configuration, stored in a key of its own name. For example:

---
backends:
    - pushover
pushover:
    user_key: hunter2
pushbullet:
    access_token: hunter2
simplepush:
    key: hunter2
slack:
    token: slacktoken
    recipient: "#slackchannel"
xmpp:
     jid: "[email protected]"
     password: "xxxx"
     mtype: "chat"
     recipient: "[email protected]"

If you want mulitple configs for the same backend type, you can specify any name and then specify the backend with a backend key. For example:

---
pushover:
    user_key: hunter2
cellphone:
    backend: pushover
    user_key: hunter2

See the backends below for available backends and options. As of v2.6.0 ntfy also supports 3rd party backends

Pushover - pushover

Required parameters:
  • user_key
Optional parameters:
  • sound
  • priority
  • expire
  • retry
  • callback
  • api_token - use your own application token
  • device - target a device, if omitted, notification is sent to all devices
  • url
  • url_title
  • html

Pushbullet - pushbullet

Required parameter:
Optional parameters:
  • device_iden - a device identifier, if omited, notification is sent to all devices
  • email - send notification to pushbullet user with the specified email or send an email if they aren't a pushullet user

Simplepush - simplepush

Required parameter:
  • key - Your Simplepush key, created by installing the Android App (no registration required) at https://simplepush.io
Optional parameters:
  • event - sets ringtone and vibration pattern for incoming notifications (can be defined in the simplepush app)

XMPP - xmpp

Requires parameters:
  • jid
  • password
  • recipient
Optional parameters
  • hostname (if not from jid)
  • port
  • path_to_certs
  • mtype

Requires extras, install like this: pip install ntfy[xmpp].

To verify the SSL certificates offered by a server: path_to_certs = "path/to/ca/cert"

Without dnspython library installed, you will need to specify the server hostname if it doesn't match the jid.

Specify port if other than 5222. NOTE: Ignored without specified hostname

NOTE: Google Hangouts doesn't support XMPP since 2017

Telegram - telegram

Requires extras, install like this: pip install ntfy[telegram].

Requires ntfy to be installed as ntfy[telegram]. This backend is configured the first time you will try to use it: ntfy -b telegram send "Telegram configured for ntfy".

Pushjet - pushjet

Required parameter:
Optional parameters:
  • endpoint - custom Pushjet API endpoint

    (defaults to https://api.pushjet.io)

  • level - The importance level from 1(low) to 5(high)
  • link

Notifico - notifico

Required parameter:
  • webhook - The webhook link, created at https://n.tkte.ch/

    (choose Plain Text service when creating the webhook)

Slack - slack

Requires extras, install like this: pip install ntfy[slack].

Required parameter:
  • token - The Slack service secret token, either a legacy user token created at https://api.slack.com/custom-integrations/legacy-tokens or a token obtained by creating an app at https://api.slack.com/apps?new_app=1 with chat:write:bot scope and linking it to a workspace.
  • recipient - The Slack channel or user to send notifications to. If you use the # symbol the message is send to a Slack channel and if you use the @ symbol the message is send to a Slack user.

Slack Incoming Webhook - slack_webhook ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Required parameter: * url - the URL of the incoming webhook * user - The Slack channel or user to send notifications to

Instapush - insta

Requires extras, install like this pip install ntfy[instapush].

Instapush does not support notification title. It sends template-driven notifications, so you have to setup you events on the dashboard first. The backend is called insta due to homonymy with the instapush python wrapper

Required parameters:
  • appid - The application id
  • secret - The application secret
  • event_name - The instapush event to be used
  • trackers - The array of trakers to use

Note on trackers: Trackers are placeholders for events (a sort of notification template). If you defined more than one tracker in your event you'll have to provide more messages. At the moment, the only way to do so is to separate each message with a colon (:) character. You can also escape the separator character: Example:

ntfy -b insta send "message1:message2"
ntfy -b insta send "message1:message2\:with\:colons"

Prowl - prowl

Optional parameters:
  • api_key
  • provider_key
  • priority
  • url

Works via dbus, works with most DEs like Gnome, KDE, XFCE and with libnotify.

The following dependecies should be installed.

$ sudo apt install python-dbus # on ubuntu/debian

You will need to install some font that supports emojis (in Debian fonts-symbola or Gentoo media-fonts/symbola).

Optional parameters:
  • icon - Specifies path to the notification icon, empty string for no icon.
  • urgency - Specifies the urgency level (low, normal, critical).
  • transient - Skip the history (exp: the Gnome message tray) (true, false).
  • soundfile - Specifies the notification sound file (e.g. /usr/share/sounds/notif.wav).
  • timeout - Specifies notification expiration time level (-1 - system default, 0 - never expire).

Windows Desktop Notifications - win32

Uses pywin32.

Mac OS X Notification Center - darwin

Requires ntfy to be installed globally (not in a virtualenv).

System log - systemlog

Uses the syslog core Python module, which is not available on Windows platforms.

Optional parameters:
  • prio - Syslog priority level. Default is ALERT. Possible values are:
    • EMERG
    • ALERT
    • CRIT
    • ERR
    • WARNING
    • NOTICE
    • INFO
    • DEBUG
  • facility - Syslog facility. Default is LOCAL5. Possible values are:
    • KERN
    • USER
    • MAIL
    • DAEMON
    • AUTH
    • LPR
    • NEWS
    • UUCP
    • CRON
    • SYSLOG
    • LOCAL0
    • LOCAL1
    • LOCAL2
    • LOCAL3
    • LOCAL4
    • LOCAL5
    • LOCAL6
    • LOCAL7
  • fmt - Format of the message to be sent to the system logger. The title and the message are specified using the following placeholders:

    • {title}
    • {message}

    Default is [{title}] {message}.

Termux:API - termux

Requires the app to be install from the Play store and the CLI utility be installed with apt install termux-api.

Pushalot - pushalot

Required parameter:
Optional parameters:
  • source - source of the notification
  • ttl - message expire time in minutes (time to live)
  • url - URL to include in the notifications
  • url_title - visible URL title (ignored if no url specified)
  • image - URL of image included in the notifications
  • important - mark notifications as important
  • silent - mark notifications as silent

Rocket.Chat - rocketchat

Requires extras, install like this: pip install ntfy[rocketchat].

Required parameters:
  • url - URL of your Rocket.Chat instance
  • username - login username
  • password - login password
  • room - room/channel name to post in

Matrix.org - matrix

Requires extras, install like this: pip install ntfy[matrix].

Required parameters:
  • url - URL of your homeserver instance
  • roomId - room to post in
  • userId - login userid
  • password - login password
  • token - access token

You must either specify token, or userId and password.

Webpush - ntfy_webpush ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Webpush support is provded by an external ntfy module, install like this: pip install ntfy ntfy-webpush.

Required parameters:
  • subscription_info - A PushSubscription Object
  • private_key - the path to private key file or anything else that works with pywebpush.

For more info, see _ntfy-webpush <https://github.com/dschep/ntfy-webpush>`_

3rd party backends

To use or implement your own backends, specify the full path of the module as your backend. The module needs to contain a module with a function called notify with the following signature:

def notify(title, message, **kwargs):
    """
    kwargs contains retcode if using ntfy done or ntfy shell-integration
    and all options in your backend's section of the config
    """
    pass

Other options

Title is configurable with the title key in the config. Example:

---
title: Customized Title

Backends ToDo

Testing

python setup.py test

Contributors

ntfy's People

Contributors

a1fred avatar adamnovak avatar andrewguenther avatar barakplasma avatar clementpinard avatar dali99 avatar danryder avatar dschep avatar giuseongit avatar henryx avatar jeffgreenca avatar jlesage avatar josetomastocino avatar juanpabloaj avatar jungle-boogie avatar mobiusklein avatar oz123 avatar piskvor avatar proinsias avatar pyhedgehog avatar rahiel avatar rcaloras avatar sambrightman avatar scalp42 avatar schwert avatar thomwiggers avatar tjbenator avatar tryer3000 avatar tymm avatar webworxshop avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ntfy's Issues

Demo setup

Hi,

Nice work. Would you bother to explain the demo video setup you have ?
I guess you are running commands on your android phone ?

Thanks.

Better README

  • Document shell focus support
  • Better intro (what to focus on more? shell integration? push notifications?)
  • Update install for single file exe
  • Fixup references to extras
  • Re-record demo (how could I demo shell integration?)

Using ntfy background shell?

I want to use ntfy to notify me from my headless serve (ubuntu 14).
A script starts at inserting a disc in the drive
SUBSYSTEM=="block", KERNEL=="sr0", ACTION=="change", RUN+="/usr/local/bin/add-disc.sh"
In add-disc.sh i do some differnet things (in the backgrond -> headless) and want be notified via ntfy. All commandos in add-disc.sh works - not nfty.
Is there a parameter to let nfty work in background?

ntfy issue on Raspbian

Hello!

I have a problem with ntfy on my Raspberry Pi 2 Model B running the last version of Raspbian. All my packages are up to date.

I installed ntfy with sudo pip install ntfy without any error.

If I type just ntfy, no problem, the help page is displayed. But when I try to add any argument I have that error :

pi@raspberrypi:~ $ ntfy send test
Warning: there was a problem loading ~/.ntfy.json (Expecting property name: line 5 column 3 (char 80))Traceback (most recent call last):
File "/usr/local/bin/ntfy", line 11, in
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/ntfy/cli.py", line 128, in main
return send_notification(args.func(args), args, config)
File "/usr/local/lib/python2.7/dist-packages/ntfy/cli.py", line 74, in send_notification
*_backend_config)
File "/usr/local/lib/python2.7/dist-packages/ntfy/backends/default.py", line 9, in notify
module.notify(title=title, message=message, *_kwargs)
File "/usr/local/lib/python2.7/dist-packages/ntfy/backends/linux.py", line 7, in notify
bus = dbus.SessionBus()
File "/usr/lib/python2.7/dist-packages/dbus/_dbus.py", line 211, in new
mainloop=mainloop)
File "/usr/lib/python2.7/dist-packages/dbus/_dbus.py", line 100, in new
bus = BusConnection.new(subclass, bus_type, mainloop=mainloop)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 122, in new
bus = cls._new_for_bus(address_or_type, mainloop=mainloop)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NotSupported: Unable to autolaunch a dbus-daemon without a $DISPLAY for X11

The error is talking about ~/.ntfy.json but I'm pretty sure that the file is ok because I copied it from the Wiki ^^

Hope you can find a solution :)

Custom User-Agent

Add 'ntfy/VERSION' to beginning of requests.utils.default_user_agent().

Single file executable

Options:

  • PyInstaller (crossplatform)
  • py2exe (windows)
  • cxfreeze (linux)
  • py2app (macoss)

A potential pitfall: virtualenv issue. Possible solution (tested on Linux): create virtualenv but then use system python and add that virtualenv's site-packages to PYTHONPATH. (or.. just pip install --target)

shell ignore option fail

Hello,

Really happy that #19 exists but it doesn't seem to read the ignore options in my .zshrc profile:

eval "$(ntfy shell-integration)"                                                                                                                                                                                                               
AUTO_NTFY_DONE_TIMEOUT=${AUTO_NTFY_DONE_TIMEOUT:-40}                                                                                                                                                                                           
AUTO_NTFY_DONE_IGNORE=${AUTO_NTFY_DONE_IGNORE:-emacs gstat info less /usr/local/bin/lua53 mail man meld most mutt nano screen ssh tail tmux top vi vim}

Pushover notification: "/usr/local/bin/lua53" succeeded in 1:09 minutes
and for python3: "python3" succeeded in 1:27 minutes

Is there something wrong in my configuration above?
I've re-loaded the zshrc profile many times with source .zshrc and completely logged off and back but it continues to ignore settings for python and lua.

Can't get the retcode from --pid

$ ntfy done --pid 55977
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/obrian/bin/ntfy/__main__.py", line 8, in <module>
  File "/Users/obrian/bin/ntfy/ntfy/cli.py", line 298, in main
ValueError: too many values to unpack

Less noisy errors for desktop notifications

I use the same .bashrc on desktop and server systems so I don't want shell integration complaining about lack of dbus missing or DISPLAY env var not being set if I haven't set a push based notification. Focus support should also only warn if it doesn't work.

Comparison between string and int when giving optional priority argument on command line

Executing ntfy with Pushover backend this way:
$ ntfy -o priority 2 send "f*ck"

yields to this error:
ERROR: Failed to send notification using pushover
Traceback (most recent call last):
File "/usr/lib/python3.5/site-packages/ntfy/init.py", line 30, in notify
module.notify(message=message, title=title, **backend_config)
File "/usr/lib/python3.5/site-packages/ntfy/backends/pushover.py", line 63, in notify
if priority <= 2 and priority >= -2:
TypeError: unorderable types: str() <= int()

https://github.com/dschep/ntfy/blob/master/ntfy/backends/pushover.py#L63

Telegram support

ntfy is nifty. Are you interested in adding support for Telegram? I made a package that could be used. It has a configure function to guide users in setting it up and a send function to send stuff.

conf = "~/.config/ntfy/telegram-send.conf"
telegram_send.configure(conf)
telegram_send.send(messages=["hello"], conf=conf)

That call to configure saves the credentials (api token, and which user to send messages to) in the conf file and the call to send uses it to send a message.

I'd like to help if you're interested.

send notifcation when in another terminal tab

when running with

export AUTO_NTFY_DONE_UNFOCUSED_ONLY=-b 

Notification are send only when the window isn't focused, but when one works with multiple tabs open,
it will be nice to have notifications sent too. The solution right now is to completely disable this option
and accept that notifications will be sent even if the current tab is focused.

Pushbullet not working

I have an issue with the pushbullet backend:

> ntfy -b pushbullet send "hey"
Traceback (most recent call last):
  File "/usr/bin/ntfy", line 11, in <module>
    load_entry_point('ntfy==2.1.1', 'console_scripts', 'ntfy')()
  File "/usr/lib/python3.5/site-packages/ntfy/cli.py", line 304, in main
    **dict(args.option.get(None, [])))
  File "/usr/lib/python3.5/site-packages/ntfy/__init__.py", line 34, in notify
    backend_config.update(kwargs)
AttributeError: 'NoneType' object has no attribute 'update'
cat ~/.config/ntfy/ntfy.yml 
backends:
- linux
- pushbullet

pushbullet:
access_key: <my_key>

SSL Exceptions when using single file binary

$ ntfy -b pushover -o user_key secret_token send 'Pushover test!'
ERROR: Failed to send notification using pushover
Traceback (most recent call last):
  File "/usr/local/bin/ntfy/ntfy/__init__.py", line 34, in notify
    module.notify(message=message, title=title, **backend_config)
  File "/usr/local/bin/ntfy/ntfy/backends/pushover.py", line 107, in notify
    headers={'User-Agent': USER_AGENT})
  File "/usr/local/bin/ntfy/requests/api.py", line 107, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/local/bin/ntfy/requests/api.py", line 53, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/bin/ntfy/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/bin/ntfy/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/bin/ntfy/requests/adapters.py", line 447, in send
    raise SSLError(e, request=request)
SSLError: [Errno 20] Not a directory

Where my secret_token is replaced with my actual user token.

Thoughts?

ntfy[xmpp] request to give up on timeouts

XMPP service jit.si is down ATM so my notifications can't be sent. However, ntfy[xmpp] tries over and over to make a connection:

ERROR: Could not connect to [2001:41d0:a:1c2c::17]:5222. Socket Error #65: No route to host
ERROR: Socket Error #54: Connection reset by peer
ERROR: Could not connect to [2001:41d0:a:1c2c::17]:5222. Socket Error #65: No route to host
ERROR: Error reading from XML stream.
ERROR: Could not connect to [2001:41d0:a:1c2c::17]:5222. Socket Error #65: No route to host
ERROR: Socket Error #54: Connection reset by peer
ERROR: Could not connect to [2001:41d0:a:1c2c::17]:5222. Socket Error #65: No route to host
ERROR: Socket Error #54: Connection reset by peer
ERROR: Could not connect to [2001:41d0:a:1c2c::17]:5222. Socket Error #65: No route to host
ERROR: Error reading from XML stream.
ERROR: Could not connect to [2001:41d0:a:1c2c::17]:5222. Socket Error #65: No route to host
ERROR: Socket Error #54: Connection reset by peer
ERROR: Could not connect to [2001:41d0:a:1c2c::17]:5222. Socket Error #65: No route to host

Could it be made to quit trying to connect after 60 to 120 seconds?

AttributeError: 'Namespace' object has no attribute 'pid'

By calling ntfy done sleep 2 I'm getting:

Traceback (most recent call last):
  File "/usr/local/bin/ntfy", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/ntfy/cli.py", line 247, in main
    message = args.func(args)
  File "/usr/local/lib/python2.7/dist-packages/ntfy/cli.py", line 26, in run_cmd
    if args.pid:
AttributeError: 'Namespace' object has no attribute 'pid'

It does not matter what I append to done. I'm getting the same Traceback.
Anyway what is the correct syntax for calling ntfy done with a pid?
I'm using ntfy 1.3.0 including ntfy[emoji] and ntfy[pid].

ntfy for pid

Hello,

I have 1.2.0.post13 how do I get the pid functionality?

Send push notification when command finishes

positional arguments:
  {send,done,shell-integration}
    send                send a notification
    done                run a command and send a notification when done
    shell-integration   automatically get notifications when long running
                        commands finish     

Get ntfy.yaml from /etc

It would be nice if ntfy could read the config from /etc/ntfy/ntfy.yaml if no ~/config/ntfy/ntfy.yaml exists.

work within virtualenvs on Ubuntu

Unlike #72, which is about the structure of the virtualenv's metadata, ntfy doesn't work on Ubuntu because it needs to import dbus, and you can't pip install dbus easily, so you need to use the system version.

One potential fix for this is to simply hack in a sys.path.append that adds the directory where the importable dbus is found, import it, and then sys.path.pop() to remove it; this will be more restrictive than a full-on --system-site-packages virtualenv, but can still get that one library from the system.

ntfy shell integration ignoring timeout

Hi,

Version of ntfy: 2.0.3
Platform: i386 freebsd
python version: 3.4.4

shell integration in my .zshrc:

eval "$(ntfy shell-integration)"
AUTO_NTFY_DONE_TIMEOUT=60
AUTO_NTFY_DONE_IGNORE='atop emacs gstat info less lua53 jupyter mail man meld most mutt nano screen ssh sqlite3 tail tmux top vi vim' 

On the client.pushover.com site:

[email protected]:/usr~
"sleep 50" succeeded in 0:50 minutes

Does this happen with your bash integration?

WARNING: Failed to send notification using linux

After installing the dependencies, I tried ntfy.

root@3b84f399b67d:~# ntfy -b linux -v send 'test'
WARNING: Failed to send notification using linux
root@3b84f399b67d:~# ntfy send test
WARNING: Failed to send notification using linux
root@3b84f399b67d:~# ntfy done sleep 2
WARNING: Failed to send notification using linux

Without any other exceptions showing, I can not find out the root cause.

Context Manager based notifier

Just a random silly idea: using a context manager to help with notifying about tasks

Would intergrate well and easily with personal python scripts n' stuff, or any codebases which would benefit from being able to easily add in notifications (buildbots perhaps?)

(note: the following code isn't exactly clean or complete, if you want this to be made into a pull request or whatever, I can)

class TaskNotifier:
    def __init__(self, task_name, on_enter=True, on_exit=True, on_error=True,
                 config=None, **kwargs):
        self.task_name = task_name
        self.on_enter = on_enter
        self.on_exit = on_exit
        self.on_error = on_error
        self.config = config
        self.kwargs = kwargs

    def __enter__(self):
        # start_time = now()
        if self.on_enter:
            # questionmark notification icon?
            ntfy.notify("Task: {}".format(self.task_name),
                        "task has started!")

    def __exit__(self, exc_type, exc_value, traceback):
        # task_time = start_time - now()
        # task_time = enprettyfy(task_time)
        if exc_type and self.on_error:
            # X notification icon?
            ntfy.notify("Task: {}".format(self.task_name),
                        "task has errored out after {}!".format(task_time))
        elif self.on_exit:
            # Tick notification icon?
            ntfy.notify("Task: {}".format(self.task_name),
                        "task has finished in {}!".format(task_time))
        # if self.suppress_error: return true ?

It would also simplify the whole run-a-process command already within the library (not that it isn't already)

def for_a_process_thing(commandline):
    with TaskNotifier(commandline):
        subprocess.check_call(commandline)

However this is just a silly idea, a tad bit complicated for what it does, and might not be worth the maintenance cost! but if you like the idea, I'd be happy to implement it for you

longer than than flag for done command

And a flag like --longer-than 60 to ntfy done to suppress notifications for jobs that end in less than a minute. Even a value of 1 is useful, because it prevents notifications from being sent immediately because you got the command wrong.

Create Issue Template

Go back through closed tickets to see what the most frequently missing needed info was. Basic starting point:

How was ntfy installed?

  • Global pip (sudo pip install ntfy)
  • Single file bin (curl'd)
  • Virtualenv pip (virtualenv foobar && foobar/bin/pip install ntfy)

What version is installed?

$ ntfy --version

What Operating System are you running?

  • Linux
  • MacOS X
  • Windows
  • Other? (BSD?)

What does your config file contain (eg: ~/.ntfy.yml)


---
# paste your yaml :)

xmpp config?

Hello,

I've instaledl 'ntfy[xmpp]' but I don't know what the yml file needs to look like and how I connect it to a xmpp server. Do you have any documentation that can be shared so I can set it up?

Thanks,
sean

Better error when missing config keys

Currently get messages like this, which aren't useful to users:

ERROR: Failed to send notification using pushover
Traceback (most recent call last):
ย  File "/usr/local/lib/python2.7/dist-packages/ntfy/__init__.py", line 30, in notify
ย ย ย  module.notify(message=message, title=title, **backend_config)
TypeError: notify() takes at least 3 arguments (2 given)

If possible, introspect the function signature to find what the arguments accepted are.

Multiple configs for the same backend type (e.g. 2 XMPP configs)

It'd make sense to allow multiple configurations for the same backend type in your config file. I propose doing this by adding a special backend parameter to options that is used instead of the name listed in the backends option and the backend's top level key. For example, to have a configs that send to different devices in pushover:


---
backends:
    - pushover
pushover:
    user_key: t0k3n
cell:
    user_key: t0k3n
    device: nexus5x
    backend: pushover

Then ntfy send foobar would send a notification to all your pushover devices, where as ntfy -b cell send foobar would only go to the device named nexus5x using pushover.

cc @danryder

usage intro

Upon running with out a config, it'd be nice to have zsh-like options of:

1) do nothing (this messge reapears next time)
2) create an empty config file (supresses this message and use desktop notifications)
3) configure a push notifications

Where 3 would then guide you through a wizard.

Allow using multiple backends at once

It could be useful to use both desktop and cloud notifications at the same time.

Config example:

{
    "backends": ["default", "pushbullet"],
    "pushbullet": {"access_token": "<redacted>"}
}

CLI Example:

ntfy -b default,pushbullet send foobar

Suggested by @danryder as well.

Pushover's access_token not recognized

If setting the access_token option for Pushover (as mentioned in the Readme and in the code's documentation), the following error is printed in the console:

ERROR: Got unknown arguments: {'access_token'}

The same happens if specifying options through the CLI:

$ ntfy -b pushover -o user_key MYUSERKEY -o access_token MYACCESSTOKEN send 'Pushover test!'
ERROR: Got unknown arguments: {'access_token'}

TypeError: notify() got multiple values for keyword argument 'title'

My ntfy.yml

   pushover:
     user_key: key
   pokemon:
     backend: pushover
     user_key: key
     api_token: key
     title: Pokemon Go

Gives error

`ntfy -b pokemon send 'Lvl up'`
ERROR: Failed to send notification using pushover
Traceback (most recent call last):
  File "c:\python34\lib\site-packages\ntfy\__init__.py", line 48, in notify
    **backend_config)
TypeError: notify() got multiple values for keyword argument 'title'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.