-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsmsru.py
249 lines (201 loc) · 7.69 KB
/
smsru.py
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
240
241
242
243
244
245
246
247
248
249
# encoding=utf-8
"""An sms.ru client.
Provides a class that lets you use the sms.ru API to send messages and verify
their status. Supports digest authentication.
Configuration is looked for in files ~/.config/smsru.conf and /etc/smsru.conf,
whichever is found first. Example config for simple auth:
key=00000000-0000-0000-0000-000000000000
sender=MyName
Example config for enhanced auth:
key=00000000-0000-0000-0000-000000000000
sender=MyName
login=alice
password=secret
To use in a python program:
import smsru
cli = smsru.Client()
cli.send("+79112223344", u"привет лунатикам")
To use with CLI:
python smsru.py send "+79112223344" "привет лунатикам"
"""
import hashlib
import os
import time
import urllib
import urllib2
CONFIG_FILES = ("~/.config/smsru.conf", "/etc/smsru.conf")
SEND_STATUS = {
100: "Message accepted",
201: "Out of money",
202: "Bad recipient",
203: "Message text not specified",
204: "Bad sender (unapproved)",
205: "Message too long",
206: "Day message limit reached",
207: "Can't send messages to that number",
208: "Wrong time",
209: "Blacklisted recipient",
}
STATUS_STATUS = {
-1: "Message not found",
100: "Message is in the queue",
101: "Message is on the way to the operator",
102: "Message is on the way to the recipient",
103: "Message delivered",
104: "Message failed: out of time",
105: "Message failed: cancelled by the operator",
106: "Message failed: phone malfunction",
107: "Message failed, reason unknown",
108: "Message declined",
}
COST_STATUS = {
100: "Success"
}
__author__ = "Justin Forest"
__email__ = "[email protected]"
__license__ = "GPL"
__all__ = ["Client"]
class NotConfigured(Exception):
pass
class WrongKey(Exception):
pass
class InternalError(Exception):
pass
class Unavailable(Exception):
pass
class Client(object):
def __init__(self):
self.config = self._load_config()
if self.config is None:
raise NotConfigured("Config file not found, options: " + " ".join(CONFIG_FILES))
if "key" not in self.config:
raise NotConfigured("API key not set.")
self._token = None
self._token_ts = 0
def _load_config(self):
for fn in CONFIG_FILES:
fn = os.path.expanduser(fn)
if os.path.exists(fn):
raw = file(fn, "rb").read().strip().decode("utf-8")
items = [[x.strip() for x in line.split("=", 1)] for line in raw.split("\n")]
return dict(items)
return None
def _call(self, method, args):
"""Calls a remote method."""
if not isinstance(args, dict):
raise ValueError("args must be a dictionary")
args["api_id"] = self.config["key"]
if method in ("sms/send", "sms/cost"):
login = self.config.get("login", "").lstrip("+")
password = self.config.get("password")
if login and password:
args["login"] = login
args["token"] = self._get_token()
args["sig"] = hashlib.md5(password + args["token"]).hexdigest()
del args["api_id"]
url = "http://sms.ru/%s?%s" % (method, urllib.urlencode(args))
# print url
res = urllib2.urlopen(url).read().strip().split("\n")
if res[0] == "200":
raise WrongKey("The supplied API key is wrong")
elif res[0] == "210":
raise InternalError("GET used when POST must have been")
elif res[0] == "211":
raise InternalError("Unknown method")
elif res[0] == "220":
raise Unavailable("The service is temporarily unavailable")
elif res[0] == "301":
raise NotConfigured("Wrong password")
return res
def _get_token(self):
"""Returns a token. Refreshes it if necessary."""
if self._token_ts < time.time() - 500:
self._token = None
if self._token is None:
self._token = self.token()
self._token_ts = time.time()
return self._token
def send(self, to, message, express=False, test=False):
"""Sends the message to the specified recipient. Returns a numeric
status code, its text description and, if the message was successfully
accepted, its reference number."""
if not isinstance(message, unicode):
raise ValueError("message must be a unicode")
args = {"to": to, "text": message.encode("utf-8")}
if "sender" in self.config:
args["from"] = self.config["sender"]
if express:
args["express"] = "1"
if test:
args["test"] = "1"
res = self._call("sms/send", args)
if res[0] != "100":
res.append(None)
return int(res[0]), SEND_STATUS.get(int(res[0]), "Unknown status"), res[1]
def status(self, msgid):
"""Returns message status."""
res = self._call("sms/status", {"id": msgid})
code = int(res[0])
text = STATUS_STATUS.get(code, "Unknown status")
return code, text
def cost(self, to, message):
"""Prints the cost of the message."""
res = self._call("sms/cost", {"to": to, "text": message.encode("utf-8")})
if res[0] != "100":
res.extend([None, None])
return int(res[0]), COST_STATUS.get(int(res[0]), "Unknown status"), res[1], res[2]
def balance(self):
"""Returns your current balance."""
res = self._call("my/balance", {})
if res[0] == "100":
return float(res[1])
raise Exception(res[0])
def limit(self):
"""Returns the remaining message limit."""
res = self._call("my/limit", {})
if res[0] == "100":
return int(res[1])
raise Exception(res[0])
def token(self):
"""Returns a token."""
return self._call("auth/get_token", {})[0]
if __name__ == "__main__":
import sys
try:
if len(sys.argv) == 4 and sys.argv[1] == "send":
print Client().send(sys.argv[2], sys.argv[3].decode("utf-8"))
exit(0)
if len(sys.argv) == 4 and sys.argv[1] == "send-test":
print Client().send(sys.argv[2], sys.argv[3].decode("utf-8"), test=True)
exit(0)
elif len(sys.argv) > 2 and sys.argv[1] == "status":
cli = Client()
for msgid in sys.argv[2:]:
status = cli.status(msgid)
print "%s = %s" % (msgid, status)
exit(0)
elif len(sys.argv) == 4 and sys.argv[1] == "cost":
res = Client().cost(sys.argv[2], sys.argv[3].decode("utf-8"))
print "Status=%s (%s), cost=%s, length=%s" % res
exit(0)
elif len(sys.argv) == 2 and sys.argv[1] == "balance":
print Client().balance()
exit(0)
elif len(sys.argv) == 2 and sys.argv[1] == "limit":
print Client().limit()
exit(0)
elif len(sys.argv) == 2 and sys.argv[1] == "token":
print Client().token()
exit(0)
except Exception, e:
print "ERROR: %s." % e
exit(1)
print "Usage:"
print " %s balance -- show current balance" % sys.argv[0]
print " %s cost number message -- show message cost" % sys.argv[0]
print " %s limit -- show remaining daily message limit" % sys.argv[0]
print " %s send number message -- send a message" % sys.argv[0]
print " %s send-test number message -- test sending a message" % sys.argv[0]
print " %s status msgid... -- check message status" % sys.argv[0]
print " %s token -- prints a token" % sys.argv[0]
exit(1)