Skip to content

Commit 420bde9

Browse files
committed
Use black for code formatting
1 parent 52ecef5 commit 420bde9

File tree

3 files changed

+156
-27
lines changed

3 files changed

+156
-27
lines changed

cli.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
from ConfigParser import RawConfigParser, NoSectionError, NoOptionError
2+
from argparse import ArgumentParser, RawDescriptionHelpFormatter
3+
import os
4+
from pushover import Pushover
5+
6+
7+
def read_config(config_path):
8+
config_path = os.path.expanduser(config_path)
9+
config = RawConfigParser()
10+
params = {"users": {}}
11+
files = config.read(config_path)
12+
if not files:
13+
return params
14+
params["token"] = config.get("main", "token")
15+
for name in config.sections():
16+
if name != "main":
17+
user = {}
18+
user["user_key"] = config.get(name, "user_key")
19+
try:
20+
user["device"] = config.get(name, "device")
21+
except NoOptionError:
22+
user["device"] = None
23+
params["users"][name] = user
24+
return params
25+
26+
27+
def main():
28+
parser = ArgumentParser(
29+
description="Send a message to pushover.",
30+
formatter_class=RawDescriptionHelpFormatter,
31+
epilog="""
32+
For more details and bug reports, see: https://github.com/Thibauth/python-pushover""",
33+
)
34+
parser.add_argument("--token", help="API token")
35+
parser.add_argument(
36+
"--user",
37+
"-u",
38+
help="User key or section name in the configuration",
39+
required=True,
40+
)
41+
parser.add_argument(
42+
"-c",
43+
"--config",
44+
help="configuration file\
45+
(default: ~/.pushoverrc)",
46+
default="~/.pushoverrc",
47+
)
48+
parser.add_argument("message", help="message to send")
49+
parser.add_argument("--url", help="additional url")
50+
parser.add_argument("--url-title", help="url title")
51+
parser.add_argument("--title", "-t", help="message title")
52+
parser.add_argument(
53+
"--priority", "-p", help="notification priority (-1, 0, 1 or 2)", type=int
54+
)
55+
parser.add_argument(
56+
"--retry",
57+
"-r",
58+
help="resend interval in seconds (required for priority 2)",
59+
type=int,
60+
)
61+
parser.add_argument(
62+
"--expire",
63+
"-e",
64+
help="expiration time in seconds (required for priority 2)",
65+
type=int,
66+
)
67+
parser.add_argument(
68+
"--version",
69+
"-v",
70+
action="version",
71+
help="output version information and exit",
72+
version="""
73+
%(prog)s 1.0
74+
Copyright (C) 2013-2018 Thibaut Horel <thibaut.horel@gmail.com>
75+
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
76+
This is free software: you are free to change and redistribute it.
77+
There is NO WARRANTY, to the extent permitted by law.""",
78+
)
79+
80+
args = parser.parse_args()
81+
params = read_config(args.config)
82+
if args.priority == 2 and (args.retry is None or args.expire is None):
83+
parser.error("priority of 2 requires expire and retry")
84+
if args.user in params["users"]:
85+
user_key = params["users"][args.user]["user_key"]
86+
device = params["users"][args.user]["device"]
87+
else:
88+
user_key = args.user
89+
device = None
90+
token = args.token or params["token"]
91+
92+
Pushover(token).message(
93+
user_key,
94+
args.message,
95+
device=device,
96+
title=args.title,
97+
priority=args.priority,
98+
url=args.url,
99+
url_title=args.url_title,
100+
timestamp=True,
101+
retry=args.retry,
102+
expire=args.expire,
103+
)
104+
105+
106+
if __name__ == "__main__":
107+
main()

pushover.py

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
RECEIPT_URL = BASE_URL + "receipts/"
2525
GLANCE_URL = BASE_URL + "glances.json"
2626

27+
2728
class RequestError(Exception):
2829
"""Exception which is raised when Pushover's API returns an error code.
2930
@@ -38,7 +39,7 @@ def __str__(self):
3839
return "\n==> " + "\n==> ".join(self.errors)
3940

4041

41-
class Request:
42+
class Request(object):
4243
"""Base class to send a request to the Pushover server and check the return
4344
status code. The request is sent on instantiation and raises
4445
a :class:`RequestError` exception when the request is rejected.
@@ -70,9 +71,11 @@ class MessageRequest(Request):
7071
can poll the status of the notification with the :func:`poll` function.
7172
"""
7273

73-
params = {"expired": "expires_at",
74-
"called_back": "called_back_at",
75-
"acknowledged": "acknowledged_at"}
74+
params = {
75+
"expired": "expires_at",
76+
"called_back": "called_back_at",
77+
"acknowledged": "acknowledged_at",
78+
}
7679

7780
def __init__(self, payload):
7881
Request.__init__(self, "post", MESSAGE_URL, payload)
@@ -122,18 +125,35 @@ def cancel(self):
122125
cancels the notification early.
123126
"""
124127
if not self.status["done"]:
125-
return Request("post", self.url + "/cancel.json", {"token": self.payload["token"]})
128+
return Request(
129+
"post", self.url + "/cancel.json", {"token": self.payload["token"]}
130+
)
131+
else:
132+
return None
126133

127134

128-
class Pushover:
135+
class Pushover(object):
129136
"""This is the main class of the module. It represents a Pushover app and
130137
is tied to a unique API token.
131138
132139
* ``token``: Pushover API token
133140
"""
134141

135142
_SOUNDS = None
136-
message_keywords = ["title", "priority", "sound", "callback", "timestamp", "url", "url_title", "device", "retry", "expire", "html", "attachment"]
143+
message_keywords = [
144+
"title",
145+
"priority",
146+
"sound",
147+
"callback",
148+
"timestamp",
149+
"url",
150+
"url_title",
151+
"device",
152+
"retry",
153+
"expire",
154+
"html",
155+
"attachment",
156+
]
137157
glance_keywords = ["title", "text", "subtext", "count", "percent", "device"]
138158

139159
def __init__(self, token):
@@ -149,7 +169,6 @@ def sounds(self):
149169
Pushover._SOUNDS = request.answer["sounds"]
150170
return Pushover._SOUNDS
151171

152-
153172
def verify(self, user, device=None):
154173
"""Verify that the `user` and optional `device` exist. Returns
155174
`None` when the user/device does not exist or a list of the user's
@@ -165,14 +184,13 @@ def verify(self, user, device=None):
165184
else:
166185
return request.answer["devices"]
167186

168-
169187
def message(self, user, message, **kwargs):
170188
"""Send `message` to the user specified by `user`. It is possible
171189
to specify additional properties of the message by passing keyword
172190
arguments. The list of valid keywords is ``title, priority, sound,
173191
callback, timestamp, url, url_title, device, retry, expire and html``
174192
which are described in the Pushover API documentation.
175-
193+
176194
For convenience, you can simply set ``timestamp=True`` to set the
177195
timestamp to the current timestamp.
178196
@@ -187,9 +205,9 @@ def message(self, user, message, **kwargs):
187205
if key not in Pushover.message_keywords:
188206
raise ValueError("{0}: invalid message parameter".format(key))
189207
elif key == "timestamp" and value is True:
190-
payload[key] = int(time.time())
208+
payload[key] = int(time.time())
191209
elif key == "sound" and value not in self.sounds:
192-
raise ValueError("{0}: invalid sound".format(value))
210+
raise ValueError("{0}: invalid sound".format(value))
193211
else:
194212
payload[key] = value
195213

setup.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,22 @@
22

33
from setuptools import setup
44

5-
setup(name='python-pushover',
6-
version='1.0',
7-
description="Comprehensive bindings and command line utility for the "
8-
"Pushover notification service",
9-
long_description=open("README.rst").read() + "\n"
10-
+ open("AUTHORS.rst").read() + "\n" + open("CHANGES.rst").read(),
11-
url='https://github.com/Thibauth/python-pushover',
12-
author='Thibaut Horel',
13-
author_email='thibaut.horel+pushover@gmail.com',
14-
py_modules=['pushover', 'cli'],
15-
entry_points={"console_scripts": ["pushover = cli:main"]},
16-
install_requires=['requests>=1.0'],
17-
use_2to3=True,
18-
license='GNU GPLv3'
19-
)
5+
setup(
6+
name="python-pushover",
7+
version="1.0",
8+
description="Comprehensive bindings and command line utility for the "
9+
"Pushover notification service",
10+
long_description=open("README.rst").read()
11+
+ "\n"
12+
+ open("AUTHORS.rst").read()
13+
+ "\n"
14+
+ open("CHANGES.rst").read(),
15+
url="https://github.com/Thibauth/python-pushover",
16+
author="Thibaut Horel",
17+
author_email="thibaut.horel+pushover@gmail.com",
18+
py_modules=["pushover", "cli"],
19+
entry_points={"console_scripts": ["pushover = cli:main"]},
20+
install_requires=["requests>=1.0"],
21+
use_2to3=True,
22+
license="GNU GPLv3",
23+
)

0 commit comments

Comments
 (0)