selfping 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- selfping/__init__.py +4 -0
- selfping/__main__.py +3 -0
- selfping/_version.py +1 -0
- selfping/cli.py +265 -0
- selfping/client.py +152 -0
- selfping/py.typed +0 -0
- selfping-1.0.0.dist-info/METADATA +126 -0
- selfping-1.0.0.dist-info/RECORD +11 -0
- selfping-1.0.0.dist-info/WHEEL +4 -0
- selfping-1.0.0.dist-info/entry_points.txt +2 -0
- selfping-1.0.0.dist-info/licenses/LICENSE +21 -0
selfping/__init__.py
ADDED
selfping/__main__.py
ADDED
selfping/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
selfping/cli.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import signal
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import webbrowser
|
|
11
|
+
from collections.abc import Mapping, Sequence
|
|
12
|
+
from getpass import getpass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Callable, TextIO
|
|
15
|
+
|
|
16
|
+
from ._version import __version__
|
|
17
|
+
from .client import SelfPingError, send_ping
|
|
18
|
+
|
|
19
|
+
HELP = """selfping: text yourself from the terminal.
|
|
20
|
+
|
|
21
|
+
selfping "Deploy finished" send a text
|
|
22
|
+
some-job | selfping send what you pipe in
|
|
23
|
+
selfping run -- pytest run a command, get a text when it ends
|
|
24
|
+
selfping login save your API key on this computer
|
|
25
|
+
selfping logout remove the saved key
|
|
26
|
+
selfping --version print the version
|
|
27
|
+
|
|
28
|
+
Options for run:
|
|
29
|
+
--label <name> name the command in the text
|
|
30
|
+
|
|
31
|
+
To send a text that starts with a dash, put -- before it:
|
|
32
|
+
selfping -- "-5 degrees and falling"
|
|
33
|
+
|
|
34
|
+
The key comes from SELFPING_API_KEY when it is set, otherwise from
|
|
35
|
+
selfping login. Get a key at https://www.selfping.com/dashboard
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
DASHBOARD_URL = "https://www.selfping.com/dashboard"
|
|
39
|
+
NO_KEY_MESSAGE = (
|
|
40
|
+
"No API key. Run `selfping login` or set SELFPING_API_KEY. "
|
|
41
|
+
"Get a key at https://www.selfping.com/dashboard\n"
|
|
42
|
+
)
|
|
43
|
+
MAX_LENGTH = 1600
|
|
44
|
+
KEY_PATTERN = re.compile(r"^[A-Za-z0-9_-]{16,64}$")
|
|
45
|
+
USER_AGENT = f"selfping-python-cli/{__version__}"
|
|
46
|
+
|
|
47
|
+
Sender = Callable[..., object]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def credentials_path(env: Mapping[str, str]) -> Path:
|
|
51
|
+
base = env.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
52
|
+
return Path(base) / "selfping" / "credentials"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def load_key(env: Mapping[str, str]) -> str | None:
|
|
56
|
+
from_env = env.get("SELFPING_API_KEY", "").strip()
|
|
57
|
+
if from_env:
|
|
58
|
+
return from_env
|
|
59
|
+
try:
|
|
60
|
+
return credentials_path(env).read_text(encoding="utf-8").strip() or None
|
|
61
|
+
except OSError:
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def format_duration(seconds: float) -> str:
|
|
66
|
+
total = max(0, round(seconds))
|
|
67
|
+
hours, rest = divmod(total, 3600)
|
|
68
|
+
minutes, secs = divmod(rest, 60)
|
|
69
|
+
if hours:
|
|
70
|
+
return f"{hours}h{minutes}m"
|
|
71
|
+
if minutes:
|
|
72
|
+
return f"{minutes}m{secs}s"
|
|
73
|
+
return f"{secs}s"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def run_message(label: str, code: int, seconds: float) -> str:
|
|
77
|
+
took = format_duration(seconds)
|
|
78
|
+
if code < 0:
|
|
79
|
+
try:
|
|
80
|
+
name = signal.Signals(-code).name
|
|
81
|
+
except ValueError:
|
|
82
|
+
name = f"signal {-code}"
|
|
83
|
+
return f"{label} stopped by {name} after {took}"
|
|
84
|
+
if code == 0:
|
|
85
|
+
return f"{label} finished in {took}"
|
|
86
|
+
return f"{label} FAILED in {took} (exit {code})"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def clip(text: str) -> str:
|
|
90
|
+
trimmed = text.strip()
|
|
91
|
+
return trimmed[-MAX_LENGTH:] if len(trimmed) > MAX_LENGTH else trimmed
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def describe_error(err: Exception) -> str:
|
|
95
|
+
if isinstance(err, SelfPingError):
|
|
96
|
+
return f"{err.message} {err.hint}" if err.hint else err.message
|
|
97
|
+
return str(err)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class CommandLine:
|
|
101
|
+
def __init__(
|
|
102
|
+
self,
|
|
103
|
+
*,
|
|
104
|
+
env: Mapping[str, str] | None = None,
|
|
105
|
+
stdin: TextIO | None = None,
|
|
106
|
+
stdout: TextIO | None = None,
|
|
107
|
+
stderr: TextIO | None = None,
|
|
108
|
+
sender: Sender = send_ping,
|
|
109
|
+
open_browser: Callable[[str], object] = webbrowser.open,
|
|
110
|
+
ask: Callable[[str], str] = getpass,
|
|
111
|
+
run_command: Callable[[Sequence[str]], int] | None = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
self.env = os.environ if env is None else env
|
|
114
|
+
self.stdin = sys.stdin if stdin is None else stdin
|
|
115
|
+
self.stdout = sys.stdout if stdout is None else stdout
|
|
116
|
+
self.stderr = sys.stderr if stderr is None else stderr
|
|
117
|
+
self.sender = sender
|
|
118
|
+
self.open_browser = open_browser
|
|
119
|
+
self.ask = ask
|
|
120
|
+
self.run_command = run_command or _run_command
|
|
121
|
+
|
|
122
|
+
def send(self, message: str) -> int:
|
|
123
|
+
key = load_key(self.env)
|
|
124
|
+
if not key:
|
|
125
|
+
self.stderr.write(NO_KEY_MESSAGE)
|
|
126
|
+
return 1
|
|
127
|
+
try:
|
|
128
|
+
self.sender(clip(message), api_key=key, user_agent=USER_AGENT)
|
|
129
|
+
except (SelfPingError, OSError) as err:
|
|
130
|
+
self.stderr.write(f"selfping: text not sent. {describe_error(err)}\n")
|
|
131
|
+
return 1
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
def login(self) -> int:
|
|
135
|
+
if self.stdin.isatty():
|
|
136
|
+
self.stdout.write(
|
|
137
|
+
f"Opening {DASHBOARD_URL}. Copy your API key there, then paste it here.\n"
|
|
138
|
+
)
|
|
139
|
+
self.stdout.flush()
|
|
140
|
+
with contextlib.suppress(webbrowser.Error, OSError):
|
|
141
|
+
self.open_browser(DASHBOARD_URL)
|
|
142
|
+
raw = self.ask("Paste your SelfPing API key: ")
|
|
143
|
+
else:
|
|
144
|
+
raw = self.stdin.read()
|
|
145
|
+
key = raw.strip()
|
|
146
|
+
if not KEY_PATTERN.match(key):
|
|
147
|
+
self.stderr.write(
|
|
148
|
+
"That does not look like a SelfPing API key. "
|
|
149
|
+
"Copy it from https://www.selfping.com/dashboard\n"
|
|
150
|
+
)
|
|
151
|
+
return 1
|
|
152
|
+
path = credentials_path(self.env)
|
|
153
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
154
|
+
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
155
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
156
|
+
handle.write(f"{key}\n")
|
|
157
|
+
with contextlib.suppress(OSError):
|
|
158
|
+
os.chmod(path, 0o600)
|
|
159
|
+
self.stdout.write(
|
|
160
|
+
f'Saved to {path}. Try it: selfping "Hello from my terminal"\n'
|
|
161
|
+
)
|
|
162
|
+
if self.env.get("SELFPING_API_KEY"):
|
|
163
|
+
self.stdout.write(
|
|
164
|
+
"Note: SELFPING_API_KEY is set in this shell and takes priority over the saved key.\n"
|
|
165
|
+
)
|
|
166
|
+
return 0
|
|
167
|
+
|
|
168
|
+
def logout(self) -> int:
|
|
169
|
+
path = credentials_path(self.env)
|
|
170
|
+
with contextlib.suppress(FileNotFoundError):
|
|
171
|
+
path.unlink()
|
|
172
|
+
self.stdout.write(f"Removed {path}.\n")
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
def unknown_option(self, option: str) -> int:
|
|
176
|
+
self.stderr.write(
|
|
177
|
+
f"selfping: unknown option {option}. Run selfping --help to see the options.\n"
|
|
178
|
+
)
|
|
179
|
+
return 2
|
|
180
|
+
|
|
181
|
+
def run(self, args: Sequence[str]) -> int:
|
|
182
|
+
label: str | None = None
|
|
183
|
+
rest = list(args)
|
|
184
|
+
while rest and rest[0].startswith("-"):
|
|
185
|
+
if rest[0] == "--":
|
|
186
|
+
rest = rest[1:]
|
|
187
|
+
break
|
|
188
|
+
if rest[0] != "--label":
|
|
189
|
+
return self.unknown_option(rest[0])
|
|
190
|
+
if len(rest) < 2 or rest[1].startswith("-"):
|
|
191
|
+
self.stderr.write(
|
|
192
|
+
"selfping: --label needs a name, like --label deploy\n"
|
|
193
|
+
)
|
|
194
|
+
return 2
|
|
195
|
+
label = rest[1]
|
|
196
|
+
rest = rest[2:]
|
|
197
|
+
if not rest:
|
|
198
|
+
self.stderr.write(
|
|
199
|
+
"Usage: selfping run [--label name] -- <command> [args]\n"
|
|
200
|
+
)
|
|
201
|
+
return 2
|
|
202
|
+
if not load_key(self.env):
|
|
203
|
+
self.stderr.write(NO_KEY_MESSAGE)
|
|
204
|
+
return 1
|
|
205
|
+
name = label or " ".join(rest)[:60]
|
|
206
|
+
started = time.monotonic()
|
|
207
|
+
try:
|
|
208
|
+
code = self.run_command(rest)
|
|
209
|
+
except OSError as err:
|
|
210
|
+
self.stderr.write(f"selfping: could not start {rest[0]}: {err}\n")
|
|
211
|
+
code = 127
|
|
212
|
+
self.send(run_message(name, code, time.monotonic() - started))
|
|
213
|
+
return 128 - code if code < 0 else code
|
|
214
|
+
|
|
215
|
+
def main(self, argv: Sequence[str]) -> int:
|
|
216
|
+
first = argv[0] if argv else None
|
|
217
|
+
rest = list(argv[1:])
|
|
218
|
+
if first in ("-h", "--help", "help"):
|
|
219
|
+
self.stdout.write(HELP)
|
|
220
|
+
return 0
|
|
221
|
+
if first in ("-v", "--version"):
|
|
222
|
+
self.stdout.write(f"{__version__}\n")
|
|
223
|
+
return 0
|
|
224
|
+
if first == "login":
|
|
225
|
+
return self.login()
|
|
226
|
+
if first == "logout":
|
|
227
|
+
return self.logout()
|
|
228
|
+
if first == "run":
|
|
229
|
+
return self.run(rest)
|
|
230
|
+
if first != "--" and first and len(first) > 1 and first.startswith("-"):
|
|
231
|
+
return self.unknown_option(first)
|
|
232
|
+
words = rest if first == "--" else list(argv)
|
|
233
|
+
interactive = self.stdin.isatty()
|
|
234
|
+
if words:
|
|
235
|
+
message = " ".join(words)
|
|
236
|
+
else:
|
|
237
|
+
message = "" if interactive else self.stdin.read()
|
|
238
|
+
if not message.strip():
|
|
239
|
+
self.stdout.write(HELP)
|
|
240
|
+
return 0 if not words and interactive else 2
|
|
241
|
+
return self.send(message)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _run_command(command: Sequence[str]) -> int:
|
|
245
|
+
child = subprocess.Popen(list(command))
|
|
246
|
+
previous = {}
|
|
247
|
+
|
|
248
|
+
def forward(signum: int, _frame: object) -> None:
|
|
249
|
+
child.send_signal(signum)
|
|
250
|
+
|
|
251
|
+
for signum in (signal.SIGINT, signal.SIGTERM):
|
|
252
|
+
previous[signum] = signal.signal(signum, forward)
|
|
253
|
+
try:
|
|
254
|
+
return child.wait()
|
|
255
|
+
finally:
|
|
256
|
+
for signum, handler in previous.items():
|
|
257
|
+
signal.signal(signum, handler)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
261
|
+
return CommandLine().main(sys.argv[1:] if argv is None else argv)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def entry() -> None:
|
|
265
|
+
sys.exit(main())
|
selfping/client.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from email.utils import parsedate_to_datetime
|
|
10
|
+
from typing import Any
|
|
11
|
+
from urllib import error, request
|
|
12
|
+
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
|
|
15
|
+
ENDPOINT = "https://www.selfping.com/api/sms"
|
|
16
|
+
DEFAULT_TIMEOUT = 15.0
|
|
17
|
+
MISSING_KEY = (
|
|
18
|
+
"No API key. Set the SELFPING_API_KEY environment variable or pass api_key. "
|
|
19
|
+
"Get a key at https://www.selfping.com/dashboard"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SelfPingError(Exception):
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
message: str,
|
|
27
|
+
status: int = 0,
|
|
28
|
+
*,
|
|
29
|
+
code: str | None = None,
|
|
30
|
+
hint: str | None = None,
|
|
31
|
+
retry_after: int | None = None,
|
|
32
|
+
) -> None:
|
|
33
|
+
super().__init__(message)
|
|
34
|
+
self.message = message
|
|
35
|
+
self.status = status
|
|
36
|
+
self.code = code
|
|
37
|
+
self.hint = hint
|
|
38
|
+
self.retry_after = retry_after
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class PingResult:
|
|
43
|
+
message: str
|
|
44
|
+
remaining: int | None
|
|
45
|
+
truncated: bool = False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _retry_after(value: str | None) -> int | None:
|
|
49
|
+
if not value:
|
|
50
|
+
return None
|
|
51
|
+
try:
|
|
52
|
+
seconds = float(value)
|
|
53
|
+
except ValueError:
|
|
54
|
+
try:
|
|
55
|
+
at = parsedate_to_datetime(value)
|
|
56
|
+
except (TypeError, ValueError):
|
|
57
|
+
return None
|
|
58
|
+
if at.tzinfo is None:
|
|
59
|
+
at = at.replace(tzinfo=timezone.utc)
|
|
60
|
+
return max(0, math.ceil((at - datetime.now(timezone.utc)).total_seconds()))
|
|
61
|
+
return max(0, round(seconds)) if math.isfinite(seconds) else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _parse(raw: bytes) -> tuple[str, dict[str, Any]]:
|
|
65
|
+
text = raw.decode("utf-8", errors="replace")
|
|
66
|
+
try:
|
|
67
|
+
parsed = json.loads(text)
|
|
68
|
+
except ValueError:
|
|
69
|
+
return text, {}
|
|
70
|
+
return text, parsed if isinstance(parsed, dict) else {}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _is_timeout(reason: object) -> bool:
|
|
74
|
+
return isinstance(reason, (TimeoutError, socket.timeout))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def send_ping(
|
|
78
|
+
message: str,
|
|
79
|
+
*,
|
|
80
|
+
api_key: str | None = None,
|
|
81
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
82
|
+
user_agent: str | None = None,
|
|
83
|
+
) -> PingResult:
|
|
84
|
+
if not isinstance(message, str) or not message.strip():
|
|
85
|
+
raise SelfPingError(
|
|
86
|
+
"message must be a non-empty string", code="missing_message"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
key = api_key or os.environ.get("SELFPING_API_KEY", "").strip()
|
|
90
|
+
if not key:
|
|
91
|
+
raise SelfPingError(MISSING_KEY, code="missing_key")
|
|
92
|
+
|
|
93
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
|
|
94
|
+
raise TypeError("timeout must be a positive number of seconds")
|
|
95
|
+
if not math.isfinite(timeout) or timeout <= 0:
|
|
96
|
+
raise ValueError("timeout must be a positive number of seconds")
|
|
97
|
+
|
|
98
|
+
req = request.Request(
|
|
99
|
+
ENDPOINT,
|
|
100
|
+
data=json.dumps({"message": message}).encode("utf-8"),
|
|
101
|
+
method="POST",
|
|
102
|
+
headers={
|
|
103
|
+
"Content-Type": "application/json",
|
|
104
|
+
"User-Agent": user_agent or f"selfping-python/{__version__}",
|
|
105
|
+
"Authorization": f"Bearer {key}",
|
|
106
|
+
},
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
with request.urlopen(req, timeout=timeout) as response:
|
|
111
|
+
_, body = _parse(response.read())
|
|
112
|
+
except error.HTTPError as err:
|
|
113
|
+
text, body = _parse(err.read())
|
|
114
|
+
details = body.get("error")
|
|
115
|
+
if not isinstance(details, dict):
|
|
116
|
+
details = {}
|
|
117
|
+
raise SelfPingError(
|
|
118
|
+
details.get("message")
|
|
119
|
+
or text
|
|
120
|
+
or f"SelfPing request failed with status {err.code}",
|
|
121
|
+
err.code,
|
|
122
|
+
code=details.get("code"),
|
|
123
|
+
hint=details.get("hint"),
|
|
124
|
+
retry_after=_retry_after(err.headers.get("Retry-After")),
|
|
125
|
+
) from err
|
|
126
|
+
except error.URLError as err:
|
|
127
|
+
if _is_timeout(err.reason):
|
|
128
|
+
raise SelfPingError(
|
|
129
|
+
f"SelfPing did not answer within {timeout:g}s. The text may still arrive.",
|
|
130
|
+
code="timeout",
|
|
131
|
+
) from err
|
|
132
|
+
raise SelfPingError(
|
|
133
|
+
f"Could not reach SelfPing: {err.reason}", code="network_error"
|
|
134
|
+
) from err
|
|
135
|
+
except (TimeoutError, socket.timeout) as err:
|
|
136
|
+
raise SelfPingError(
|
|
137
|
+
f"SelfPing did not answer within {timeout:g}s. The text may still arrive.",
|
|
138
|
+
code="timeout",
|
|
139
|
+
) from err
|
|
140
|
+
except OSError as err:
|
|
141
|
+
raise SelfPingError(
|
|
142
|
+
f"Could not reach SelfPing: {err}", code="network_error"
|
|
143
|
+
) from err
|
|
144
|
+
|
|
145
|
+
remaining = body.get("remaining")
|
|
146
|
+
return PingResult(
|
|
147
|
+
message=str(body.get("message") or ""),
|
|
148
|
+
remaining=remaining
|
|
149
|
+
if isinstance(remaining, int) and not isinstance(remaining, bool)
|
|
150
|
+
else None,
|
|
151
|
+
truncated=bool(body.get("truncated")),
|
|
152
|
+
)
|
selfping/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: selfping
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Text yourself from your code or your terminal. One function, one key, texts go only to your own verified phone number.
|
|
5
|
+
Project-URL: Homepage, https://www.selfping.com
|
|
6
|
+
Project-URL: Documentation, https://www.selfping.com/docs
|
|
7
|
+
Project-URL: Examples, https://github.com/br-schneider/selfping-examples
|
|
8
|
+
Project-URL: Support, https://www.selfping.com/contact
|
|
9
|
+
Author: Brett Schneider
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agent,alert,cli,cron,notification,notify,phone,sms,text
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Environment :: Console
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Topic :: Communications :: Telephony
|
|
20
|
+
Classifier: Topic :: System :: Monitoring
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# selfping
|
|
26
|
+
|
|
27
|
+
Text yourself from your code. One function, one key, and texts can only go to your own verified phone number, so there is no recipient field to get wrong and a leaked key cannot message anyone else.
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install selfping
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from selfping import send_ping
|
|
35
|
+
|
|
36
|
+
send_ping("Deploy finished. 0 errors.")
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
That's it. The key is read from the `SELFPING_API_KEY` environment variable, or pass it directly:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
send_ping("New signup: jane@example.com", api_key=my_key)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`send_ping` returns what the API sent back, so you can see how many texts are left:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
result = send_ping("Backup finished in 4m12s")
|
|
49
|
+
print(result.remaining, result.truncated)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`remaining` is the number of texts left this month, or `None` for a key without a monthly limit. `truncated` is `True` only when a message over 1600 characters was trimmed.
|
|
53
|
+
|
|
54
|
+
Requests time out after 15 seconds. Pass `timeout` in seconds to change that:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
send_ping("Nightly import done", timeout=5)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## From the terminal
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
selfping login # paste your key once
|
|
64
|
+
selfping "Deploy finished" # send a text
|
|
65
|
+
some-job | selfping # send what you pipe in
|
|
66
|
+
selfping run -- pytest # text me when this finishes
|
|
67
|
+
selfping --version # print the version
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`run` texts you "pytest finished in 4m12s" or "pytest FAILED in 38s (exit 1)" and exits with the command's own exit code, so it drops into scripts, cron and CI unchanged. Add `--label deploy` to name it. Without a key, `run` stops before starting the command.
|
|
71
|
+
|
|
72
|
+
To try it without installing anything, use `uvx selfping "Hello"` or `pipx run selfping "Hello"`.
|
|
73
|
+
|
|
74
|
+
Unknown options are rejected rather than sent as text. To send a message that starts with a dash, put `--` first: `selfping -- "-5 degrees and falling"`.
|
|
75
|
+
|
|
76
|
+
`selfping login` saves the key to `~/.config/selfping/credentials`, readable only by you, and `selfping logout` removes it. When `SELFPING_API_KEY` is set it takes priority, which is the better fit for cron, CI and agents. There is deliberately no `--key` flag, so your key never lands in shell history.
|
|
77
|
+
|
|
78
|
+
## Getting a key
|
|
79
|
+
|
|
80
|
+
Sign up at [selfping.com/login](https://www.selfping.com/login) with your phone number, prove you own it with a one-time passcode, and generate a key at [selfping.com/dashboard](https://www.selfping.com/dashboard). Free accounts get 10 texts a month, no credit card.
|
|
81
|
+
|
|
82
|
+
## What people use it for
|
|
83
|
+
|
|
84
|
+
- A text when a training run, migration or long job finishes
|
|
85
|
+
- A text when the nightly cron fails instead of silently dying
|
|
86
|
+
- A text when someone signs up, pays, or fills out your contact form
|
|
87
|
+
- A text from your AI agent when it finishes a long run or needs a decision
|
|
88
|
+
|
|
89
|
+
## Errors
|
|
90
|
+
|
|
91
|
+
`send_ping` raises `SelfPingError` when a text is not sent. It carries:
|
|
92
|
+
|
|
93
|
+
- `message`: what went wrong, in plain language
|
|
94
|
+
- `status`: the HTTP status, or `0` when SelfPing could not be reached or the request timed out
|
|
95
|
+
- `code`: a stable code such as `invalid_key`, `out_of_credits`, `rate_limited` or `delivery_failed`, plus `timeout` and `network_error` for problems on the way
|
|
96
|
+
- `hint`: what to do next
|
|
97
|
+
- `retry_after`: seconds to wait before trying again, when the API says so
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from selfping import SelfPingError, send_ping
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
send_ping("Backup finished in 4m12s")
|
|
104
|
+
except SelfPingError as err:
|
|
105
|
+
if err.code == "out_of_credits":
|
|
106
|
+
print(f"Out of texts. Retry in {err.retry_after} seconds.")
|
|
107
|
+
else:
|
|
108
|
+
print(err.status, err.message, err.hint)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
SelfPing gives the credit back when a send fails with `delivery_failed`. Every error code is listed at [selfping.com/docs#errors](https://www.selfping.com/docs#errors).
|
|
112
|
+
|
|
113
|
+
A notification should not take your job down with it. In a script where the text is a nice-to-have, catch `SelfPingError` and carry on.
|
|
114
|
+
|
|
115
|
+
## One send, one credit
|
|
116
|
+
|
|
117
|
+
Every send costs exactly one credit, long or short. Keep messages under 160 characters anyway: short texts read best on a lock screen. Lead with the outcome, include the numbers that matter, and say whether anything needs you.
|
|
118
|
+
|
|
119
|
+
## Notes
|
|
120
|
+
|
|
121
|
+
- No dependencies. It uses the standard library, on Python 3.9 or newer.
|
|
122
|
+
- `send_ping` blocks until SelfPing answers. In async code, call it with `asyncio.to_thread(send_ping, "message")`.
|
|
123
|
+
- There is no recipient parameter anywhere in SelfPing. A key texts the number that created it, only.
|
|
124
|
+
- Guides: [Python and cron](https://www.selfping.com/recipes/python-cron-alert) and [runnable examples](https://github.com/br-schneider/selfping-examples).
|
|
125
|
+
- Pricing: free 10 texts/month, Hobby $5/month for 100, Business $19/month for 400. [selfping.com/pricing](https://www.selfping.com/pricing)
|
|
126
|
+
- There is a JavaScript package too: [selfping on npm](https://www.npmjs.com/package/selfping).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
selfping/__init__.py,sha256=wOqGuucxxksD_mtHFcuSY234Jce8gnJhVJgUy92AN1M,162
|
|
2
|
+
selfping/__main__.py,sha256=iqL5sqaJteojUO-yluSE4moQ3YYJvhp0lJWkXincvCQ,32
|
|
3
|
+
selfping/_version.py,sha256=J-j-u0itpEFT6irdmWmixQqYMadNl1X91TxUmoiLHMI,22
|
|
4
|
+
selfping/cli.py,sha256=EXCCJBexX6lBLHYJtOjctqFBLeGzNzRcuNXloPce1zE,8870
|
|
5
|
+
selfping/client.py,sha256=OEykHjM81mI_KWv9IrTrH6d4iZMFVjZzbqONYOC2IMY,4673
|
|
6
|
+
selfping/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
selfping-1.0.0.dist-info/METADATA,sha256=I4hfo4KCOqYDmfWXx4uhEkqJdJpXB_gxqjkPDKeyvJs,5774
|
|
8
|
+
selfping-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
9
|
+
selfping-1.0.0.dist-info/entry_points.txt,sha256=OLCUsog1sXHznRbv9bkaU_KusK2m-QMrq0CSGIjYuiw,48
|
|
10
|
+
selfping-1.0.0.dist-info/licenses/LICENSE,sha256=iwwyKmKZNSJQ6HPDocMjoWwulGRj_dPtz4LqDC_3obM,1072
|
|
11
|
+
selfping-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Brett Schneider
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|