-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaspsms.py
More file actions
executable file
·170 lines (136 loc) · 4.59 KB
/
aspsms.py
File metadata and controls
executable file
·170 lines (136 loc) · 4.59 KB
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
#!/usr/bin/env python
#
# aspsms.py - console based SMS client for ASPSMS
# API reference: https://json.aspsms.com/
#
# Author: https://github.com/roger-dodger/
import sys
import os
import requests
import json
import argparse
import textwrap
class Error(Exception):
'''Base exception class for aspsms module.'''
class ConnectionError(Error):
'''Error to use when the connection to ASPSMS fails.'''
class SmsClient(object):
# Base settings
BASE_URL = 'https://json.aspsms.com'
CALLS = {
'CHECK_CREDITS': '/CheckCredits',
'SEND_TEXT_SMS': '/SendSimpleTextSMS',
}
CONTENT_TYPE = 'application/json'
def __init__(self, conf):
self._config = conf
def _make_request(self, method, body=None):
'''Make HTTP request and return response
Args:
method:
body:
Returns:
Raises:
ConnectionError: Connection to ASPSMS failed.
'''
# Append credentials
if not body:
body = dict()
body['UserName'] = self._config['USERKEY']
body['Password'] = self._config['PASSWORD']
try:
r = requests.post(self.BASE_URL + self.CALLS[method],
headers={'Content-Type': self.CONTENT_TYPE},
data=json.dumps(body))
except requests.exceptions.RequestException as e:
raise ConnectionError(e)
response = r.json()
if response['StatusCode'] == '1':
return response
raise ConnectionError(response['StatusInfo'])
def check_credits(self):
'''Check your credits.
Returns:
Raises:
ConnectionError: Connection to ASPSMS failed.
'''
return self._make_request('CHECK_CREDITS')['Credits']
def send_text_sms(self, recipient, message, originator):
'''Send single or multipart text messages in GSM 7-bit or Unicode.
Args:
receipient: Message receipient
message: Message text
originator: Message originator
Raises:
ConnectionError: Connection to ASPSMS failed.
'''
data = dict()
data['Originator'] = originator
data['Recipients'] = recipient
data['MessageText'] = message
self._make_request('SEND_TEXT_SMS', data)
def main():
'''
Main function
'''
# Read config file
CONF = 'aspsms.conf'
script_directory = os.path.dirname(os.path.realpath(__file__))
config_file = os.path.join(script_directory, CONF)
if not os.path.isfile(config_file):
sys.exit('Config file {} not found'.format(CONF))
with open(config_file) as config_handler:
conf = json.load(config_handler)
parser = argparse.ArgumentParser(
description='ASPSMS console client',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
'command',
choices=['send', 'credits'],
nargs='?',
default='send',
help=textwrap.dedent('''\
send - send a new message (default)
credits - check credit balance'''))
parser.add_argument(
'--recipient', '-r',
nargs='+',
help='message recipient(s)')
parser.add_argument(
'--originator', '-o',
default=conf['ORIGINATOR'],
help='originator for message')
parser.add_argument(
'--message', '-m',
help='message to be sent')
parser.add_argument('--version', action='version', version='%(prog)s 0.1')
args = parser.parse_args()
sc = SmsClient(conf)
if args.command == 'send':
# Override originator from configuration if given
if args.originator:
originator = args.originator
# Define emtpy message
message = str()
# Test if message was given with argument
if args.message:
message = args.message
# Test if message was given in stdin
elif not sys.stdin.isatty():
message = sys.stdin.readline().strip()
# No message was given - terminate
if not message:
sys.exit('Message cannot be emtpy')
# Send message
try:
sc.send_text_sms(args.recipient, message, originator)
print 'Message has been sent!'
except ConnectionError as e:
print 'Unable to send message: {}'.format(e)
elif args.command == 'credits':
try:
print 'Remaining credits: {}'.format(sc.check_credits())
except ConnectionError as e:
print 'Unable to check credits: {}'.format(e)
if __name__ == "__main__":
main()