-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpushover-notify
executable file
·239 lines (185 loc) · 5.95 KB
/
pushover-notify
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/env python3
"""pushover-notify: Send a notification to me using Pushover.
Example config file (~/.config/pushover-notify.toml):
[pushover]
appname = "Gallifrey"
api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
user_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Optional: Alternative apps:
[app.foo]
appname = "Foo"
api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
"""
import sys
import os
import platform
# https://github.com/Wyattjoh/pushover
# from pushover import Pushover
import pushover
import requests
import toml
__script_name__ = os.path.basename(sys.argv[0])
__version__ = "0.2.2"
def get_config_file():
"""Return the path of the config file.
If $PUSHOVER_NOTIFY_CONFIG is set, it overriddes any default values.
Tests if a per-user config file exists, and if not, if a global
one exists. If no config file is found, a FileNotFoundError is raised.
TODO: Use an exception that better fits this use-case.
User config:
$HOME/.config/pushover-notify.toml
Global config:
/etc/pushover-notify.toml
"""
if "PUSHOVER_NOTIFY_CONFIG" in os.environ:
return os.getenv("PUSHOVER_NOTIFY_CONFIG")
for path in ["~/.config/pushover-notify.toml", "/etc/pushover-notify.toml"]:
if os.path.exists(os.path.expanduser(path)):
return os.path.expanduser(path)
# This point is only reached if no config file exists at all.
raise FileNotFoundError(
"No pushover-notify.toml config file found. You may set a custom location "
"with $PUSHOVER_NOTIFY_CONFIG, or you have to manually create one."
)
def called_from_script():
"""Test if executed by a script instead of an interactive shell.
If called from an interactive shell, python is the process group leader. But if executed
from within a shell script, that shell is the process group leader.
@see https://stackoverflow.com/a/50283852
"""
# print(os.getpid.__name__, os.getpid())
# print(os.getpgid.__name__, os.getpgid(0))
# print(os.getsid.__name__, os.getsid(0))
return os.getpgid(0) == os.getsid(0)
def pushover_send(
api_key: str,
user_key: str,
message: str,
title: str = "",
priority: int = -1,
url: str = "",
url_title: str = None,
sound: str = "shoot"
):
po = pushover.Pushover(api_key)
po.user(user_key)
# if called_from_script():
# priority += 1
# message += "\nPRIORITY=" + str(priority)
msg = po.msg(message)
if len(title) > 0:
msg.set("title", title)
else:
msg.set("title", platform.node())
# Message priority
# Pushover's default value is 0, but we use -1.
msg.set("priority", priority)
# Pass a URL with an optional title to the message
if len(url) > 1:
msg.set("url", url)
if len(url_title) > 1:
msg.set("url_title", url_title)
# Notification sound
# Default to my custom sound "shoot" instead of "pushover"
if len(sound) > 1:
msg.set("sound", sound)
return po.send(msg)
def push(token, user, message, title=None, url=None, image=None):
api_url = "https://api.pushover.net/1/messages.json"
if not image:
r = requests.post(
api_url,
data={
token: token,
user: user,
message: message,
title: title,
url: url
}
)
else:
image_attachment = "image." + ".".join(image[0].split(".")[:-1])
r = requests.post(
api_url,
data={
token: token,
user: user,
message: message,
title: title,
url: url
},
files={
"attachment": (
image_attachment,
open(image[0], "rb"),
image[1]
)
}
)
print(r.text)
def version(output_stream=sys.stdout):
print(__script_name__ + " " + __version__, file=output_stream)
def usage(output_stream=sys.stdout):
print("Usage:", file=output_stream)
print(f"\techo \"<message>\" | {__script_name__} <title>", file=output_stream)
print("", file=output_stream)
print("Environment variables:", file=output_stream)
print("\tPUSHOVER_NOTIFY_CONFIG Use this config file instead of the default", file=output_stream)
print("\t one (/etc/pushover-notify.toml).", file=output_stream)
print("\tPUSHOVER_APP_ID Don't use the default API key. Reads from the", file=output_stream)
print("\t TOML section [app.<app-id>] instead of [pushover].", file=output_stream)
print("\tPUSHOVER_PRIORITY Message priority (-2...1, default: 0)", file=output_stream)
print("", file=output_stream)
def main(message, title, priority):
try:
config = toml.load(CONFIG_FILE)
except toml.decoder.TomlDecodeError:
print(f"FATAL ERROR: Config file \"{CONFIG_FILE}\" is no valid TOML!", file=sys.stderr)
sys.exit(2)
USER_KEY = config.get("pushover").get("user_key")
if CONFIG_SECTION[:4] == "app.":
API_KEY = config.get("app").get(CONFIG_SECTION[4:]).get("api_key")
else:
API_KEY = config.get("pushover").get("api_key")
# print(SCRIPT_NAME + " :: api_key = \"" + API_KEY + "\"")
# print(SCRIPT_NAME + " :: user_key = \"" + USER_KEY + "\"")
# _ret = push(
# API_KEY,
# USER_KEY,
# message,
# title,
# "http://torchwood.tardis.malte70.de",
# image = ["gnome-document-save-512.png", "image/png"]
# )
# if _ret is not None:
# print(SCRIPT_NAME + " :: Return value of push():\n" + _ret, file=sys.stderr)
if not pushover_send(API_KEY, USER_KEY, message, title, priority):
print(f"[{__script_name__}] Error: pushover_send() failed.")
# CONFIG_FILE = os.getenv("PUSHOVER_NOTIFY_CONFIG", "/etc/pushover-notify.toml")
CONFIG_FILE = get_config_file()
if "PUSHOVER_APP_ID" in os.environ.keys():
CONFIG_SECTION = "app." + os.environ.get("PUSHOVER_APP_ID")
else:
CONFIG_SECTION = "pushover"
PRIORITY = -1
if "PUSHOVER_PRIORITY" in os.environ.keys():
PRIORITY = int(os.environ.get("PUSHOVER_PRIORITY"))
if __name__ == "__main__":
if "--help" in sys.argv or "-h" in sys.argv:
usage()
sys.exit(0)
elif "--version" in sys.argv:
version()
sys.exit(0)
if len(sys.argv) < 2:
title = ""
else:
title = sys.argv[1]
if sys.stdin.isatty():
print("Please enter a message:", file=sys.stderr)
try:
message = sys.stdin.read()
except KeyboardInterrupt:
print("\nCtrl+C pressed. Aborting...")
sys.exit(1)
main(message, title, PRIORITY)