-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
588 lines (485 loc) · 19.8 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
from telegram import Update, KeyboardButton, WebAppInfo, ReplyKeyboardMarkup
from telegram.ext import (
CommandHandler,
MessageHandler,
filters,
CallbackContext,
ApplicationBuilder,
CallbackQueryHandler,
ConversationHandler,
)
from nordigen import NordigenClient
from dotenv import load_dotenv
from datetime import datetime
from functools import wraps
from random import randint
from loguru import logger
from uuid import uuid4
import database as db
import requests
import os
load_dotenv()
class BankBot:
AWAITING_MESSAGE = 0
def __init__(self, bot_token):
self.bot_token = bot_token
self.application = None
self.client = None
self.init_token = None
@staticmethod
def log_info(func):
@wraps(func)
async def wrapper(
self, update: Update, context: CallbackContext, *args, **kwargs
):
logger.info(
f"User {update.message.from_user.id} wrote {func.__name__} at {datetime.now().strftime('%d.%m.%Y %H:%M')}"
)
result = await func(self, update, context, *args, **kwargs)
return result
return wrapper
async def refresh_token(self) -> None:
logger.warning("Tokens are expired, getting new tokens...")
self.init_token = self.client.generate_token()
@log_info
async def on_start(self, update: Update, callback: CallbackContext) -> None:
user_id = update.message.from_user.id
if db.user_exists(user_id):
if db.is_authorized(user_id):
try:
await self.authenticated(update, callback)
if db.get_tx_notify(user_id)[0]:
self.remove_job_if_exists(f"tx_checker_{user_id}", callback)
callback.job_queue.run_repeating(
self.new_tx_trigger,
randint(60, 120),
chat_id=user_id,
name=f"tx_checker_{user_id}",
data=callback,
)
return
except requests.HTTPError:
await self.refresh_token()
await self.authenticated(update, callback)
return
login_keyboard = [
[
KeyboardButton(
"💠 Login",
)
]
]
await update.message.reply_text(
f"👨 Hello {update.message.from_user.first_name}! You are not authorized in your bank, please do that to continue using bot",
reply_markup=ReplyKeyboardMarkup(login_keyboard, resize_keyboard=True),
)
return
else:
db.insert_user(user_id)
await update.message.reply_text(
f"👨 Hello {update.message.from_user.first_name}! Welcome to Nordea Bank Checker, please authenticate in your bank."
)
try:
await self.bank_init(update, callback)
except requests.HTTPError:
await self.refresh_token()
await self.bank_init(update, callback)
return
@log_info
async def bank_init(self, update: Update, context: CallbackContext) -> None:
logger.info("INITIALIZING A SESSION")
user_id = update.message.from_user.id
init = self.client.initialize_session(
institution_id=self.institution_id,
redirect_uri=os.getenv("WEB_APP_URL"),
reference_id=str(uuid4()),
)
auth_link = init.link
requisition_id = init.requisition_id
db.insert_auth_link(user_id, auth_link)
db.insert_requisition_id(user_id, requisition_id)
keyboard = [
[
KeyboardButton(
"👨💻 Authenticate Bank",
web_app=WebAppInfo(auth_link),
)
]
]
await update.message.reply_text(
"🧭 Bank session created, please authenticate",
reply_markup=ReplyKeyboardMarkup(keyboard, resize_keyboard=True),
)
@log_info
async def authenticated(self, update: Update, context: CallbackContext) -> None:
user_id = update.message.from_user.id
account_id = self.client.requisition.get_requisition_by_id(
requisition_id=db.get_requisition_id(user_id)
)["accounts"][0]
db.insert_account_id(user_id, account_id)
if not db.is_authorized(user_id):
db.insert_is_authorized(user_id, 1)
await update.message.reply_text("✅ Authentication Successful! ✅")
await update.message.reply_text("♻️ Getting Account details...")
account = self.client.account_api(id=db.get_account_id(user_id))
account_details = account.get_details()
await update.message.reply_text(
f"✅ Account Connected! ✅\nWelcome!\n\n🙎♂️ Account Owner: {account_details['account']['ownerName']}\n💳Account Name: {account_details['account']['product']} "
)
main_keyboard = [
[
KeyboardButton(
"📇 Get Transactions",
),
KeyboardButton(
"💳 Get Balance",
),
]
]
if str(user_id) == os.getenv("ADMIN_ID"):
main_keyboard.append(
[
KeyboardButton("🔊 Notify Everyone"),
KeyboardButton("⚙️ Settings"),
]
)
else:
main_keyboard.extend([[KeyboardButton("⚙️ Settings")]])
await update.message.reply_text(
"🏫 Choose an option:",
reply_markup=ReplyKeyboardMarkup(main_keyboard, resize_keyboard=True),
)
@log_info
async def get_balance(self, update: Update, context: CallbackContext) -> None:
await update.message.reply_text("♻️ Getting balance...")
url = f"https://bankaccountdata.gocardless.com/api/v2/accounts/{db.get_account_id(update.message.from_user.id)}/balances/"
response = requests.get(
url,
headers={
"accept": "application/json",
"Authorization": f"Bearer {self.init_token['access']}",
},
)
if response.status_code == 401:
logger.error(
f"User {update.message.from_user.id} tried to make a request but request was unsuccessful.\nRequest failed with code {response.status_code} and message {response.text}"
)
await self.refresh_token()
response = requests.get(
url,
headers={
"accept": "application/json",
"Authorization": f"Bearer {self.init_token['access']}",
},
)
balance = next(
(
balance["balanceAmount"]["amount"]
for balance in response.json().get("balances", [])
if balance.get("balanceType") == "interimAvailable"
),
None,
)
await update.message.reply_text(
f"💸 Account Balance is {balance} SEK",
)
async def get_transactions_logic(self, user_id) -> str:
url = f"https://bankaccountdata.gocardless.com/api/v2/accounts/{db.get_account_id(user_id)}/transactions/"
response = requests.get(
url,
headers={
"accept": "application/json",
"Authorization": f"Bearer {self.init_token['access']}",
},
)
if response.status_code == 401:
logger.error(
f"User {user_id} tried to make a request but request was unsuccessful.\nRequest failed with code {response.status_code} and message {response.text}"
)
await self.refresh_token()
response = requests.get(
url,
headers={
"accept": "application/json",
"Authorization": f"Bearer {self.init_token['access']}",
},
)
return response
def format_transactons(self, response: str) -> list:
def format_message(tx_dict: dict) -> None:
transaction_summ = float(tx_dict["transactionAmount"]["amount"])
transaction_amount = f"{transaction_summ} SEK"
transaction_type = tx_dict["remittanceInformationUnstructured"].strip("*")
if transaction_summ < 0:
inverted_summ = transaction_summ * -1
transaction_amount = f"**{inverted_summ}** SEK"
if "Överföring" in transaction_type:
if transaction_summ < 0:
transaction_type = (
f"🔄 #Transfer to {transaction_type.strip('Överföring')}"
)
else:
transaction_type = (
f"🔄 #Transfer from {transaction_type.strip('Överföring')}"
)
elif "Kortköp" in transaction_type:
transaction_type = f"💳 #CardPayment to {transaction_type.strip('Kortköp')[7:]}".replace(
"*", ""
)
elif "Lön" in transaction_type:
transaction_type = "💰 #MonthlySalary"
elif "" in transaction_type:
transaction_type = (
f"🏦 #ServicePayment to {transaction_type.strip('Betalning')}"
)
transaction_date = datetime.strptime(
tx_dict["transactionId"], "%Y-%m-%d-%H.%M.%S.%f"
).strftime("%d.%m.%Y ⌛ %H:%M")
data_message = f"{transaction_type}\n\n💵 Amount: {transaction_amount}\n\n🗓️ Date: {transaction_date}"
characters_to_escape = [".", "-", "(", ")", "#"]
data_message = "".join(
[
"\\" + char if char in characters_to_escape else char
for char in data_message
]
)
return data_message, datetime.strptime(
tx_dict["transactionId"], "%Y-%m-%d-%H.%M.%S.%f"
)
booked_dict = {}
pending_dict = {}
for transaction in response.json()["transactions"]["booked"][:10]:
message, date = format_message(transaction)
booked_dict[date] = message
for transaction in response.json()["transactions"]["pending"]:
message, date = format_message(transaction)
pending_dict[date] = message
transactions_dict = booked_dict | pending_dict
sorted_tx_dict = dict(
sorted(transactions_dict.items(), key=lambda item: item[0])
)
transactions_list = [tx for tx in sorted_tx_dict.values()]
final_list = transactions_list[-10:]
return final_list
@log_info
async def get_transactions(self, update: Update, context: CallbackContext) -> None:
logger.info(
f"User {update.message.from_user.id} pressed Get Transactions at {datetime.now().strftime('%d.%m.%Y %H:%M')}"
)
await update.message.reply_text("♻️ Getting transactions...")
response = await self.get_transactions_logic(update.message.from_user.id)
messages_list = self.format_transactons(response)
last_tx = messages_list[-1]
db.set_last_tx(update.message.from_user.id, last_tx)
for final_message in messages_list:
await update.message.reply_text(final_message, parse_mode="MarkdownV2")
async def notification_keyboard(
self, update: Update, context: CallbackContext
) -> None:
if db.get_tx_notify(update.message.from_user.id)[0]:
settings_keyboard = [
[
KeyboardButton(
"⬅️ Back",
),
KeyboardButton(
"❌ Disable Notificatons",
),
]
]
await update.message.reply_text(
"🏫 Choose an option:",
reply_markup=ReplyKeyboardMarkup(
settings_keyboard, resize_keyboard=True
),
)
else:
settings_keyboard = [
[
KeyboardButton(
"⬅️ Back",
),
KeyboardButton(
"✅ Enable Notifications",
),
]
]
await update.message.reply_text(
"🏫 Choose an option:",
reply_markup=ReplyKeyboardMarkup(
settings_keyboard, resize_keyboard=True
),
)
@log_info
async def settings(self, update: Update, context: CallbackContext) -> None:
await self.notification_keyboard(update, context)
@log_info
async def back_button_handler(self, update: Update, context: CallbackContext):
main_keyboard = [
[
KeyboardButton(
"📇 Get Transactions",
),
KeyboardButton(
"💳 Get Balance",
),
]
]
if str(update.message.from_user.id) == os.getenv("ADMIN_ID"):
main_keyboard.append(
[
KeyboardButton("🔊 Notify Everyone"),
KeyboardButton("⚙️ Settings"),
]
)
else:
main_keyboard.extend([[KeyboardButton("⚙️ Settings")]])
await update.message.reply_text(
"🏫 Choose an option:",
reply_markup=ReplyKeyboardMarkup(main_keyboard, resize_keyboard=True),
)
@log_info
async def notify_everyone(self, update: Update, context: CallbackContext):
await update.message.reply_text("🗣 Enter notification:")
return self.AWAITING_MESSAGE
@log_info
async def handle_notification(
self, update: Update, context: CallbackContext
) -> int:
for telegram_id in db.get_telegram_ids():
if db.is_authorized(telegram_id):
await context.bot.send_message(
chat_id=telegram_id,
text=f"⚠️ NOTIFICATION FOR ALL USERS!⚠️\n\n{update.message.text}",
)
await update.message.reply_text("🟢 Notifications successfully sent!")
return ConversationHandler.END
async def new_tx_trigger(self, context: CallbackContext) -> None:
job = context.job
chat_id = job.chat_id
logger.info(f"DOING JOB FOR {chat_id}")
current_last_tx = self.format_transactons(
await self.get_transactions_logic(chat_id)
)
current_last_tx = current_last_tx[-1]
last_tx = db.get_last_tx(chat_id)
if last_tx[0] != current_last_tx:
db.set_last_tx(chat_id, current_last_tx)
await context.bot.send_message(
chat_id=chat_id,
text=f"💸 NEW TRANSACTION CONFIRMED 💸\n\n{current_last_tx}",
parse_mode="MarkdownV2",
)
def remove_job_if_exists(self, name: str, context: CallbackContext) -> bool:
"""Remove job with given name. Returns whether job was removed."""
current_jobs = context.job_queue.get_jobs_by_name(name)
if not current_jobs:
return False
for job in current_jobs:
job.schedule_removal()
return True
async def enable_notificatons(
self, update: Update, context: CallbackContext
) -> None:
user_id = update.message.from_user.id
db.set_tx_notify(user_id, True)
context.job_queue.run_repeating(
self.new_tx_trigger,
randint(60, 120),
chat_id=user_id,
name=f"tx_checker_{user_id}",
data=context,
)
response = await self.get_transactions_logic(user_id)
messages_list = self.format_transactons(response)
last_tx = db.get_last_tx(user_id)
current_last_tx = messages_list[-1:]
if last_tx[0] != current_last_tx[0]:
db.set_last_tx(user_id, current_last_tx[0])
await update.message.reply_text("🔈 Transactions notifications enabled.")
await self.notification_keyboard(update, context)
async def disable_notifications(
self, update: Update, context: CallbackContext
) -> None:
user_id = update.message.from_user.id
job_removed = self.remove_job_if_exists(f"tx_checker_{user_id}", context)
if job_removed:
db.set_tx_notify(update.message.from_user.id, False)
await update.message.reply_text("🔇 Transactions notifications disabled.")
await self.notification_keyboard(update, context)
else:
await update.message.reply_text(
"📟 Transactions notifications are not changed."
)
def run_bot(self) -> None:
db.db_init()
logger.success(
f"Database initialized at {datetime.now().strftime('%d.%m.%Y %H:%M')}"
)
self.client = NordigenClient(
secret_id=os.getenv("SECRET_ID"), secret_key=os.getenv("SECRET_KEY")
)
logger.success(f"Client created at {datetime.now().strftime('%d.%m.%Y %H:%M')}")
self.init_token = self.client.generate_token()
self.institution_id = self.client.institution.get_institution_id_by_name(
country="SE", institution="Nordea Personal"
)
logger.success(
f"Bank data received at {datetime.now().strftime('%d.%m.%Y %H:%M')}"
)
self.application = ApplicationBuilder().token(self.bot_token).build()
self.application.add_handler(CommandHandler("start", self.on_start))
self.application.add_handler(
MessageHandler(filters.Text("💠 Login"), self.bank_init)
)
self.application.add_handler(
MessageHandler(filters.Text("💳 Get Balance"), self.get_balance)
)
self.application.add_handler(
MessageHandler(filters.Text("📇 Get Transactions"), self.get_transactions)
)
self.application.add_handler(
MessageHandler(filters.Text("⬅️ Back"), self.back_button_handler)
)
self.application.add_handler(
MessageHandler(filters.Text("⚙️ Settings"), self.settings)
)
self.application.add_handler(
MessageHandler(
filters.Text("❌ Disable Notificatons"), self.disable_notifications
)
)
self.application.add_handler(
MessageHandler(
filters.Text("✅ Enable Notifications"), self.enable_notificatons
)
)
self.application.add_handler(
MessageHandler(filters.StatusUpdate.WEB_APP_DATA, self.authenticated)
)
conv_handler = ConversationHandler(
entry_points=[
MessageHandler(filters.Text("🔊 Notify Everyone"), self.notify_everyone)
],
states={
self.AWAITING_MESSAGE: [
MessageHandler(filters.Text(), self.handle_notification)
],
},
fallbacks=[],
)
self.application.add_handler(conv_handler)
self.application.add_handler(
CallbackQueryHandler(
self.handle_notification, pattern="🗣 Enter notification:"
)
)
logger.success(
f"Bot initialized successfully at {datetime.now().strftime('%d.%m.%Y %H:%M')}"
)
self.application.run_webhook(
listen="0.0.0.0", port=8443, webhook_url=os.getenv("WEBHOOK_URL")
)
if __name__ == "__main__":
bot = BankBot(os.getenv("BOT_TOKEN"))
bot.run_bot()