forked from goelakash/Bank-Through-Twitter
/
bot.py
294 lines (230 loc) · 10.2 KB
/
bot.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
from __future__ import print_function
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy import API
from tweepy.streaming import StreamListener
import json
import re
import geocoder
consumer_key = "agjequxG75iT0dHxn7jCd1uLW"
consumer_secret = "HxwaAwLisDBiZqBTqLt4AVDHMcba0ZRRyJobwjZ2ubMdgRhVXo"
access_token_key = "2450454258-64KnS3q2NcT2Ti3gjQa8UDq0rMIXVRfnXQRWB4U"
access_token_secret = "KRG6K0y6KaJr56qqSADwSdmUSOuxbyUvKV8RRR8oQd9B5"
headers = {
# Request headers
'Ocp-Apim-Subscription-Key': '91282cc98ef2479b90d4e83d3d808b79',
'bearer':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjdXN0b21lcklkIjoiNTcyZGJjYzlmZDNlNWQ2MDI1MTgwYTBlIiwicm9sZSI6InVzZXIiLCJwcmltYXJ5U3Vic2NyaWJlcktleSI6IjkxMjgyY2M5OGVmMjQ3OWI5MGQ0ZTgzZDNkODA4Yjc5IiwiaWF0IjoxNDYyNjIwMzA4fQ.BrM6NP7N3FFAIu3CKfBat-ZnS8Qvupz9Q8QWz7GBbuE'
}
customer_id = "572dbcc9fd3e5d6025180a0e"
acc_id = ['572dbccafd3e5d6025180a10', #0 balance
'572dbcc9fd3e5d6025180a0f'] #14389.1
handle_to_customerid= {
'_goelakash' : "572dbcc9fd3e5d6025180a0e"
}
EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
class Listener( StreamListener ):
def __init__( self ):
self.mesgCount = 0
self.conn = httplib.HTTPSConnection('bluebank.azure-api.net')
def str_list_to_json( self, response):
response = response.split("}")
response = response[:-1]
for i in range(len(response)):
response[i] = response[i][1:] #[{...}, {...}, {...}]
response[i] = response[i]+'}'
for i in range(len(response)):
response[i] = json.loads(response[i])
# print(response[i])
return response
def get_accounts(self, cust_id):
conn = self.conn
conn.request("GET", "/api/v0.6.3/customers/"+cust_id+"/accounts", "", headers)
data = str_list_to_json(conn.getresponse().read())
accounts = []
for x in data:
accounts.append(x)
return accounts
def on_status(self, status):
print("Status text!!")
print(status.text)
def on_connect( self ):
print("Connection established!!")
def on_disconnect( self, notice ):
print("Connection lost!! : ", notice)
def on_data( self, status ):
print("Entered on_data()")
jstr = json.loads(status)
if "friends" not in jstr:
mesg = jstr["direct_message"]
self.mesgCount += 1
text = mesg["text"]
print("\nNew message: ",self.mesgCount)
# print("\nSender Name: ",mesg["sender"]["name"])
print("Sender screen name: ",mesg["sender_screen_name"])
print("Text received: ",mesg["text"])
print("Sent at: ",mesg["created_at"])
text = text.lower().split(" ")
if text[0] == "help":
# list all the commands
'''
1. Account info
'''
elif text[0] == "account" and text[1] == "info":
try:
accounts = self.get_accounts(customer_id)
for k,acc in zip(range(len(data)),data):
print(k+1,".")
print("Acc no: ",acc["accountNumber"])
print("Acc type: ",acc["accountType"])
print("Acc balance: ",acc["accountBalance"] + " "+ acc["accountCurrency"])
except e:
print("Exception: ",e)
'''
2. Transaction history
'''
elif text[0] == "transaction" and text[1] == "history":
limit = 5
try:
if text[2]:
if text[2].isdigit():
limit = int(text[2])
else:
raise ValueError('Illegal value!')
accounts = self.get_accounts(customer_id)
print("Description | Amount | DateTime | Balance")
for acc in accounts:
print("for account no: ",acc["accountNumber"],")")
self.conn.request("GET", "/api/v0.6.3/accounts/"+acc["accountNumber"]+"/transactions?limit="+limit,"",headers)
response = conn.getresponse()
data = str_list_to_json(response.read())
for i in range(len(data)):
print(i+1,". ",data[i]["transactionDescription"]," | ",data[i]["transactionAmount"]," | ",
data[i]["transactionDateTime"]," | ",data[i]["accountBalance"])
except e:
print("An exception happened: ",e)
'''
3. User info
'''
elif text[0] == "my" and text[1]=="info":
try:
if text[2] == "display":
self.conn.request("GET", "/api/v0.6.3/customers/"+customer_id,"",headers)
response = conn.getresponse()
data = json.loads(response().read())[0]
for x in data:
print(x+": "+data[x])
elif text[2] == "update":
if text[3] and text[4]:
if text[3] == "email":
if not EMAIL_REGEX.match(text[4]):
raise ValueError('Invalid email address!')
body = {
'emailID':text[4]
}
self.conn.request("PATCH","/api/v0.6.3/customers/"+customer_id,json.dumps(body), headers)
elif text[3] == "mobile":
if not text[4].isdigit() or not len(text[4])==10:
raise ValueError('Invalid mobile number!')
body = {
'mobilePhone':text[4]
}
self.conn.request("PATCH","/api/v0.6.3/customers/"+customer_id,json.dumps(body), headers)
else:
raise ValueError('Invalid arguments')
else:
raise IOError('Invalid arguments for update!')
except e:
print("Exception occured: ",e)
'''
4. Payment (to account)
'''
elif text[0] == "pay" and text[1] and text[2]:
try:
if len(text[1])==7 and text[1].isdigit():
try:
amount = float(text[2])
except ValueError:
"Not a float"
accounts = self.get_accounts(customer_id)
body = {
"toAccountNumber":text[1],
"toSortCode":"839999",
"paymentReference":"string",
"paymentAmount": amount
}
flag = 0
for acc in accounts:
conn.request("POST", "/api/v0.6.3/accounts/"+acc["id"]+"/payments", json.dumps(body), headers)
response = conn.getresponse()
if str(response.status) == "200":
flag = 1
break
if flag==0:
raise SystemError('Cannot complete transaction!')
except e:
print("Exception occured: ",e)
#all atms
'''
5. Branches nearby
'''
elif text[0] == "branch" and text[1]=="near":
try:
g = geocoder.google(text[2:])
lat, lng = g.latlng
params = urllib.urlencode({
'lat':lat,
'lng':lng,
'radius':"10000"
})
conn = httplib.HTTPSConnection('bluebank.azure-api.net')
conn.request("GET", "/api/v0.6.3/branches/near?%s" % params,"",headers)
repsonse = conn.getresponse()
data = json.loads(response.read())
for i in range(len(data)):
print("i+1"+data[i].branchName+", "+data[i].streetAddress+", "+data[i].city)
except e:
print("Exception occured: ",e)
# ask for lat and long or extract location from twitter
'''
6. ATMs nearby
'''
elif text[0] == "atm" and text[1]=="near":
try:
g = geocoder.google(text[2:])
lat, lng = g.latlng
params = urllib.urlencode({
'lat':lat,
'lng':lng,
'radius':"10000"
})
conn = httplib.HTTPSConnection('bluebank.azure-api.net')
conn.request("GET", "/api/v0.6.3/atms/near?%s" % params,"",headers)
repsonse = conn.getresponse()
data = json.loads(response.read())
for i in range(len(data)):
print("i+1"+data[i].atmName+", "+data[i].streetAddress+", "+data[i].city)
except e:
print("Exception occured: ",e)
'''
Invalid
'''
else:
print("Unknown commands, please try again.")
return True
def on_error( self, status ):
print(status)
def main():
try:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token_key, access_token_secret)
api = API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
stream = Stream(auth, Listener())
stream.userstream()
except BaseException as e:
print("Error in main()", e)
if __name__ == '__main__':
main()