-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnaughtify.py
1473 lines (1304 loc) · 57.6 KB
/
naughtify.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, jsonify, request, render_template, redirect, url_for, session, flash, make_response
from flask_cors import CORS
from telegram import Bot, ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters
from dotenv import load_dotenv, set_key
import requests
import traceback
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import threading
import qrcode
import io
import base64
import json
from urllib.parse import urlparse
import re
import uuid
from functools import wraps
# --------------------- Configuration and Setup ---------------------
load_dotenv()
# Essential Environment Variables
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_ID = os.getenv("CHAT_ID")
LNBITS_READONLY_API_KEY = os.getenv("LNBITS_READONLY_API_KEY")
LNBITS_URL = os.getenv("LNBITS_URL")
INSTANCE_NAME = os.getenv("INSTANCE_NAME", "LNbits Instance")
# Optional URLs
OVERWATCH_URL = os.getenv("OVERWATCH_URL")
DONATIONS_URL = os.getenv("DONATIONS_URL")
INFORMATION_URL = os.getenv("INFORMATION_URL")
# LNURLP ID (Required if Donations are enabled)
LNURLP_ID = os.getenv("LNURLP_ID") if DONATIONS_URL else None
# Files
FORBIDDEN_WORDS_FILE = os.getenv("FORBIDDEN_WORDS_FILE", "forbidden_words.txt")
PROCESSED_PAYMENTS_FILE = os.getenv("PROCESSED_PAYMENTS_FILE", "processed_payments.txt")
CURRENT_BALANCE_FILE = os.getenv("CURRENT_BALANCE_FILE", "current-balance.txt")
DONATIONS_FILE = os.getenv("DONATIONS_FILE", "donations.json")
# Thresholds and Intervals
BALANCE_CHANGE_THRESHOLD = int(os.getenv("BALANCE_CHANGE_THRESHOLD", "10"))
HIGHLIGHT_THRESHOLD = int(os.getenv("HIGHLIGHT_THRESHOLD", "2100"))
LATEST_TRANSACTIONS_COUNT = int(os.getenv("LATEST_TRANSACTIONS_COUNT", "21"))
PAYMENTS_FETCH_INTERVAL = int(os.getenv("PAYMENTS_FETCH_INTERVAL", "60")) # in seconds
# Server Configuration
APP_HOST = os.getenv("APP_HOST", "127.0.0.1")
APP_PORT = int(os.getenv("APP_PORT", "5009"))
# Secret Key for Flask Sessions
SECRET_KEY = os.getenv("SECRET_KEY", os.urandom(24))
# Validate Essential Variables
required_vars = {
"TELEGRAM_BOT_TOKEN": TELEGRAM_BOT_TOKEN,
"CHAT_ID": CHAT_ID,
"LNBITS_READONLY_API_KEY": LNBITS_READONLY_API_KEY,
"LNBITS_URL": LNBITS_URL
}
missing_vars = [var for var, value in required_vars.items() if not value]
if missing_vars:
raise EnvironmentError(f"Essential environment variables missing: {', '.join(missing_vars)}")
if DONATIONS_URL and not LNURLP_ID:
raise EnvironmentError("LNURLP_ID must be set when DONATIONS_URL is provided.")
# Define LNBITS_DOMAIN by parsing LNBITS_URL
parsed_url = urlparse(LNBITS_URL)
LNBITS_DOMAIN = parsed_url.netloc
if not LNBITS_DOMAIN:
raise ValueError("Invalid LNBITS_URL provided. Cannot parse domain.")
# Initialize Telegram Bot
bot = Bot(token=TELEGRAM_BOT_TOKEN)
# --------------------- Logging Configuration ---------------------
# Create a custom logger
logger = logging.getLogger("lnbits_logger")
logger.setLevel(logging.DEBUG) # Capture all levels; handlers will filter
# Formatter for log messages
formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s')
# Handler for general logs (INFO and above)
info_handler = RotatingFileHandler("app.log", maxBytes=2 * 1024 * 1024, backupCount=3)
info_handler.setLevel(logging.INFO)
info_handler.setFormatter(formatter)
# Handler for debug logs (DEBUG and above)
debug_handler = RotatingFileHandler("debug.log", maxBytes=5 * 1024 * 1024, backupCount=3)
debug_handler.setLevel(logging.DEBUG)
debug_handler.setFormatter(formatter)
# Handler for console output (INFO and above)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)
# Add handlers to the logger
logger.addHandler(info_handler)
logger.addHandler(debug_handler)
logger.addHandler(console_handler)
# Reduce verbosity for specific modules (e.g., apscheduler)
logging.getLogger('apscheduler').setLevel(logging.WARNING) # Only WARNING and above
# --------------------- Flask App Initialization ---------------------
app = Flask(__name__)
app.secret_key = SECRET_KEY # Secure Secret-Key for Sessions
CORS(app) # Enable CORS
# --------------------- Global Variables ---------------------
processed_payments = set()
donations = []
total_donations = 0
last_update = datetime.utcnow()
latest_balance = {
"balance_sats": None,
"last_change": None,
"memo": None
}
latest_payments = []
# --------------------- Helper Functions ---------------------
def get_main_inline_keyboard():
balance_button = InlineKeyboardButton("💰 Balance", callback_data='balance')
latest_transactions_button = InlineKeyboardButton("📜 Latest Transactions", callback_data='transactions_inline')
if DONATIONS_URL:
live_ticker_button = InlineKeyboardButton("📡 Live Ticker", url=DONATIONS_URL)
else:
live_ticker_button = InlineKeyboardButton("📡 Live Ticker", callback_data='liveticker_inline')
if OVERWATCH_URL:
overwatch_button = InlineKeyboardButton("📊 Overwatch", url=OVERWATCH_URL)
else:
overwatch_button = InlineKeyboardButton("📊 Overwatch", callback_data='overwatch_inline')
if LNBITS_URL:
lnbits_button = InlineKeyboardButton("⚡ LNBits", url=LNBITS_URL)
else:
lnbits_button = InlineKeyboardButton("⚡ LNBits", callback_data='lnbits_inline')
inline_keyboard = [
[balance_button],
[latest_transactions_button, live_ticker_button],
[overwatch_button, lnbits_button]
]
logger.debug("Main inline keyboard created.")
return InlineKeyboardMarkup(inline_keyboard)
def get_main_keyboard():
balance_button = ["💰 Balance"]
main_options_row_1 = ["📊 Overwatch", "📡 Live Ticker"]
main_options_row_2 = ["📜 Latest Transactions", "⚡ LNBits"]
keyboard = [
balance_button,
main_options_row_1,
main_options_row_2
]
logger.debug("Main reply keyboard created.")
return ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=False)
def load_forbidden_words(file_path):
forbidden = set()
try:
with open(file_path, 'r') as f:
for line in f:
word = line.strip()
if word:
forbidden.add(word)
logger.debug(f"{len(forbidden)} forbidden words loaded from {file_path}.")
except FileNotFoundError:
logger.error(f"Forbidden words file not found: {file_path}.")
except Exception as e:
logger.error(f"Error loading forbidden words from {file_path}: {e}")
logger.debug(traceback.format_exc())
return forbidden
FORBIDDEN_WORDS = load_forbidden_words(FORBIDDEN_WORDS_FILE)
def sanitize_memo(memo):
if not memo:
logger.debug("No memo provided to sanitize.")
return "No memo provided."
def replace_match(match):
word = match.group()
logger.debug(f"Sanitizing word: {word}")
return '*' * len(word)
if not FORBIDDEN_WORDS:
logger.debug("No forbidden words to sanitize.")
return memo
pattern = re.compile(r'\b(' + '|'.join(map(re.escape, FORBIDDEN_WORDS)) + r')\b', re.IGNORECASE)
sanitized_memo = pattern.sub(replace_match, memo)
logger.debug(f"Sanitized memo: Original: '{memo}' -> Sanitized: '{sanitized_memo}'")
return sanitized_memo
def load_processed_payments():
processed = set()
if os.path.exists(PROCESSED_PAYMENTS_FILE):
try:
with open(PROCESSED_PAYMENTS_FILE, 'r') as f:
for line in f:
processed.add(line.strip())
logger.debug(f"{len(processed)} processed payment hashes loaded.")
except Exception as e:
logger.error(f"Error loading processed payments: {e}")
logger.debug(traceback.format_exc())
else:
logger.info("Processed payments file does not exist. Starting fresh.")
return processed
def add_processed_payment(payment_hash):
try:
with open(PROCESSED_PAYMENTS_FILE, 'a') as f:
f.write(f"{payment_hash}\n")
logger.debug(f"Payment hash {payment_hash} added to processed list.")
except Exception as e:
logger.error(f"Error adding processed payment: {e}")
logger.debug(traceback.format_exc())
def load_last_balance():
if not os.path.exists(CURRENT_BALANCE_FILE):
logger.info("Balance file does not exist. Initializing with current balance.")
return None
try:
with open(CURRENT_BALANCE_FILE, 'r') as f:
content = f.read().strip()
if not content:
logger.warning("Balance file is empty. Last balance set to 0.")
return 0.0
try:
balance = float(content)
logger.debug(f"Last balance loaded: {balance} sats.")
return balance
except ValueError:
logger.error(f"Invalid balance value in file: {content}. Last balance set to 0.")
return 0.0
except Exception as e:
logger.error(f"Error loading last balance: {e}")
logger.debug(traceback.format_exc())
return 0.0
def load_donations():
global donations, total_donations
if os.path.exists(DONATIONS_FILE) and DONATIONS_URL and LNURLP_ID:
try:
with open(DONATIONS_FILE, 'r') as f:
data = json.load(f)
donations = data.get("donations", [])
total_donations = data.get("total_donations", 0)
for donation in donations:
if "id" not in donation:
donation["id"] = str(uuid.uuid4())
if "likes" not in donation:
donation["likes"] = 0
if "dislikes" not in donation:
donation["dislikes"] = 0
logger.debug(f"{len(donations)} donations loaded from file.")
except Exception as e:
logger.error(f"Error loading donations: {e}")
logger.debug(traceback.format_exc())
else:
logger.info("Donations file does not exist or donations not enabled.")
def save_donations():
if DONATIONS_URL and LNURLP_ID:
try:
with open(DONATIONS_FILE, 'w') as f:
json.dump({
"total_donations": total_donations,
"donations": donations
}, f, indent=4)
logger.debug("Donation data successfully saved.")
except Exception as e:
logger.error(f"Error saving donations: {e}")
logger.debug(traceback.format_exc())
# Initialize processed payments and donations
processed_payments = load_processed_payments()
load_donations()
def sanitize_donations():
global donations
try:
for donation in donations:
donation['memo'] = sanitize_memo(donation.get('memo', ''))
save_donations()
logger.info("Donations sanitized and saved.")
except Exception as e:
logger.error(f"Error sanitizing donations: {e}")
logger.debug(traceback.format_exc())
def handle_ticker_ban(update, context):
chat_id = update.effective_chat.id
if len(context.args) == 0:
bot.send_message(chat_id, text="❌ Please provide at least one word to ban. Example: /ticker_ban badword")
logger.debug("Ticker ban command received without arguments.")
return
words_to_ban = [word.strip() for word in context.args if word.strip()]
if not words_to_ban:
bot.send_message(chat_id, text="❌ No valid words provided.")
logger.debug("Ticker ban command received with no valid words.")
return
added_words = []
duplicate_words = []
try:
with open(FORBIDDEN_WORDS_FILE, 'a') as f:
for word in words_to_ban:
if word.lower() in (fw.lower() for fw in FORBIDDEN_WORDS):
duplicate_words.append(word)
else:
f.write(word + '\n')
FORBIDDEN_WORDS.add(word)
added_words.append(word)
logger.debug(f"Words to ban processed: Added {added_words}, Duplicates {duplicate_words}.")
# After banning, sanitize existing donations
sanitize_donations()
global last_update
last_update = datetime.utcnow() # This triggers automatic refresh in the frontend
if added_words:
if len(added_words) == 1:
success_message = f"✅ Great! I've successfully added the word '{added_words[0]}' to the banned list. The Live Ticker will update shortly!"
else:
words_formatted = "', '".join(added_words)
success_message = f"✅ Great! I've added these words to the banned list: '{words_formatted}'. The Live Ticker will update shortly!"
bot.send_message(chat_id, text=success_message)
logger.info(f"Added forbidden words: {added_words}")
if duplicate_words:
if len(duplicate_words) == 1:
duplicate_message = f"⚠️ The word '{duplicate_words[0]}' was already banned."
else:
words_formatted = "', '".join(duplicate_words)
duplicate_message = f"⚠️ The following words were already banned: '{words_formatted}'."
bot.send_message(chat_id, text=duplicate_message)
logger.info(f"Duplicate forbidden words attempted to add: {duplicate_words}")
except Exception as e:
logger.error(f"Error adding words to forbidden list: {e}")
bot.send_message(chat_id, text="❌ An error occurred while banning words. Please try again.")
logger.debug(traceback.format_exc())
def fetch_api(endpoint):
url = f"{LNBITS_URL}/api/v1/{endpoint}"
headers = {"X-Api-Key": LNBITS_READONLY_API_KEY}
try:
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
logger.debug(f"Data fetched from {endpoint}: {data}")
return data
else:
logger.error(f"Error fetching {endpoint}. Status Code: {response.status_code}")
return None
except Exception as e:
logger.error(f"Error fetching {endpoint}: {e}")
logger.debug(traceback.format_exc())
return None
def fetch_pay_links():
if not DONATIONS_URL or not LNURLP_ID:
logger.debug("Donations not enabled. Skipping fetch_pay_links.")
return None
url = f"{LNBITS_URL}/lnurlp/api/v1/links"
headers = {"X-Api-Key": LNBITS_READONLY_API_KEY}
try:
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
logger.debug(f"Pay Links fetched: {data}")
return data
else:
logger.error(f"Error fetching Pay Links. Status Code: {response.status_code}")
return None
except Exception as e:
logger.error(f"Error fetching Pay Links: {e}")
logger.debug(traceback.format_exc())
return None
def get_lnurlp_info(lnurlp_id):
if not DONATIONS_URL or not LNURLP_ID:
logger.debug("Donations not enabled. Skipping get_lnurlp_info.")
return None
pay_links = fetch_pay_links()
if pay_links is None:
logger.error("Could not fetch Pay Links.")
return None
for pay_link in pay_links:
if pay_link.get("id") == lnurlp_id:
logger.debug(f"Matching Pay Link found: {pay_link}")
return pay_link
logger.error(f"No Pay Link found with ID {lnurlp_id}.")
return None
def fetch_donation_details():
if not DONATIONS_URL or not LNURLP_ID:
logger.debug("Donations not enabled. Returning basic data.")
return {
"total_donations": total_donations,
"donations": donations,
"lightning_address": "Unavailable",
"lnurl": "Unavailable",
"highlight_threshold": HIGHLIGHT_THRESHOLD
}
lnurlp_info = get_lnurlp_info(LNURLP_ID)
if lnurlp_info is None:
logger.error("No LNURLp info found.")
return {
"total_donations": total_donations,
"donations": donations,
"lightning_address": "Unavailable",
"lnurl": "Unavailable",
"highlight_threshold": HIGHLIGHT_THRESHOLD
}
username = lnurlp_info.get('username', 'Unknown')
lightning_address = f"{username}@{LNBITS_DOMAIN}"
lnurl = lnurlp_info.get('lnurl', '')
logger.debug(f"Donation details fetched: Lightning Address: {lightning_address}, LNURL: {lnurl}")
return {
"total_donations": total_donations,
"donations": donations,
"lightning_address": lightning_address,
"lnurl": lnurl,
"highlight_threshold": HIGHLIGHT_THRESHOLD
}
def update_donations_with_details(data):
donation_details = fetch_donation_details()
data.update({
"lightning_address": donation_details.get("lightning_address"),
"lnurl": donation_details.get("lnurl")
})
logger.debug("Donation details updated with additional information.")
return data
def updateDonations(data):
updated_data = update_donations_with_details(data)
if updated_data["donations"]:
latestDonation = updated_data["donations"][-1]
logger.info(f'Latest donation: {latestDonation["amount"]} sats - "{latestDonation["memo"]}"')
else:
logger.info('Latest donation: None yet.')
save_donations()
def notify_transaction(payment, direction):
try:
amount = payment["amount"]
memo = payment["memo"]
date = payment["date"]
emoji = "🟢" if direction == "incoming" else "🔴"
sign = "+" if direction == "incoming" else "-"
transaction_type = "Incoming Payment" if direction == "incoming" else "Outgoing Payment"
message = (
f"{emoji} *{transaction_type}*\n"
f"💰 Amount: {sign}{amount} sats\n"
f"✉️ Memo: {memo}"
)
bot.send_message(
chat_id=CHAT_ID,
text=message,
parse_mode=ParseMode.MARKDOWN
)
logger.info(f"Notification for {transaction_type} sent successfully.")
except Exception as e:
logger.error(f"Error sending transaction notification: {e}")
logger.debug(traceback.format_exc())
def send_latest_payments():
global total_donations, donations, last_update, latest_balance, latest_payments
logger.info("Fetching latest payments...")
payments = fetch_api("payments")
if payments is None:
logger.warning("No payments fetched.")
return
if not isinstance(payments, list):
logger.error("Unexpected data format for payments.")
return
sorted_payments = sorted(payments, key=lambda x: x.get("time", ""), reverse=True)
latest = sorted_payments[:LATEST_TRANSACTIONS_COUNT]
latest_payments = latest.copy() # Update latest_payments for /status route
if not latest:
logger.info("No payments found.")
return
incoming_payments = []
outgoing_payments = []
new_processed_hashes = []
for payment in latest:
payment_hash = payment.get("payment_hash")
if payment_hash in processed_payments:
logger.debug(f"Payment {payment_hash} already processed. Skipping.")
continue
amount_msat = payment.get("amount", 0)
memo = sanitize_memo(payment.get("memo", "No memo provided."))
status = payment.get("status", "completed")
time_str = payment.get("time", None)
date = parse_time(time_str)
formatted_date = date.isoformat() # Use ISO format for consistency
try:
amount_sats = int(abs(amount_msat) / 1000)
except ValueError:
amount_sats = 0
logger.warning(f"Invalid amount_msat value: {amount_msat}")
if status.lower() == "pending":
logger.debug(f"Payment {payment_hash} is pending. Skipping.")
continue
if amount_msat > 0:
incoming_payments.append({"amount": amount_sats, "memo": memo, "date": formatted_date})
elif amount_msat < 0:
outgoing_payments.append({"amount": amount_sats, "memo": memo, "date": formatted_date})
if DONATIONS_URL and LNURLP_ID:
extra_data = payment.get("extra", {})
lnurlp_id_payment = extra_data.get("link")
if lnurlp_id_payment == LNURLP_ID:
donation_memo = sanitize_memo(extra_data.get("comment", "No memo provided."))
try:
donation_amount_msat = int(extra_data.get("extra", 0))
donation_amount_sats = donation_amount_msat / 1000
except (ValueError, TypeError):
donation_amount_sats = amount_sats
logger.warning(f"Invalid donation amount_msat: {extra_data.get('extra', 0)}. Using amount_sats: {amount_sats}")
donation = {
"id": str(uuid.uuid4()),
"date": formatted_date,
"memo": donation_memo,
"amount": donation_amount_sats,
"likes": 0,
"dislikes": 0
}
donations.append(donation)
total_donations += donation_amount_sats
last_update = datetime.utcnow()
logger.info(f"New donation detected: {donation_amount_sats} sats - {donation_memo}")
updateDonations({"total_donations": total_donations, "donations": donations})
processed_payments.add(payment_hash)
new_processed_hashes.append(payment_hash)
add_processed_payment(payment_hash)
logger.debug(f"Payment {payment_hash} processed and added to processed payments.")
# Update latest_balance
wallet_info = fetch_api("wallet")
if wallet_info:
current_balance_msat = wallet_info.get("balance", 0)
current_balance_sats = current_balance_msat / 1000
latest_balance = {
"balance_sats": int(current_balance_sats),
"last_change": datetime.utcnow().isoformat(),
"memo": "Latest balance fetched."
}
logger.debug(f"Updated latest_balance: {latest_balance}")
# Send notifications
for payment in incoming_payments:
notify_transaction(payment, "incoming")
for payment in outgoing_payments:
notify_transaction(payment, "outgoing")
def parse_time(time_input):
if not time_input:
logger.warning("No 'time' field found, using current time.")
return datetime.utcnow()
if isinstance(time_input, str):
try:
date = datetime.strptime(time_input, "%Y-%m-%dT%H:%M:%S.%fZ")
logger.debug(f"Parsed time string: {time_input} -> {date}")
except ValueError:
try:
date = datetime.strptime(time_input, "%Y-%m-%dT%H:%M:%SZ")
logger.debug(f"Parsed time string: {time_input} -> {date}")
except ValueError:
logger.error(f"Unable to parse time string: {time_input}. Using current time.")
date = datetime.utcnow()
elif isinstance(time_input, (int, float)):
try:
date = datetime.fromtimestamp(time_input)
logger.debug(f"Parsed timestamp: {time_input} -> {date}")
except Exception as e:
logger.error(f"Unable to parse timestamp: {time_input}, error: {e}. Using current time.")
date = datetime.utcnow()
else:
logger.error(f"Unsupported time format: {time_input}. Using current time.")
date = datetime.utcnow()
return date
def send_balance_message(chat_id):
logger.info(f"Fetching balance for chat_id: {chat_id}")
wallet_info = fetch_api("wallet")
if wallet_info is None:
bot.send_message(chat_id, text="❌ Unable to fetch balance at the moment. Please try again.")
logger.error("Failed to fetch wallet balance.")
return
current_balance_msat = wallet_info.get("balance", 0)
current_balance_sats = current_balance_msat / 1000
balance_text = f"💰 *Current Balance:* {int(current_balance_sats)} sats"
try:
bot.send_message(
chat_id=chat_id,
text=balance_text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=get_main_keyboard()
)
logger.info(f"Balance message sent to chat_id: {chat_id}")
except Exception as telegram_error:
logger.error(f"Error sending balance message: {telegram_error}")
logger.debug(traceback.format_exc())
def send_transactions_message(chat_id, page=1, message_id=None):
logger.info(f"Fetching transactions for chat_id: {chat_id}, page: {page}")
payments = fetch_api("payments")
if payments is None:
bot.send_message(chat_id, text="❌ Unable to fetch transactions right now.")
logger.error("Failed to fetch transactions.")
return
filtered_payments = [p for p in payments if p.get("status", "").lower() != "pending"]
sorted_payments = sorted(filtered_payments, key=lambda x: x.get("time", ""), reverse=True)
total_transactions = len(sorted_payments)
transactions_per_page = 13
total_pages = (total_transactions + transactions_per_page - 1) // transactions_per_page
if total_pages == 0:
total_pages = 1
if page < 1 or page > total_pages:
bot.send_message(chat_id, text="❌ Invalid page number.")
logger.warning(f"Invalid page number requested: {page}")
return
start_index = (page - 1) * transactions_per_page
end_index = start_index + transactions_per_page
page_transactions = sorted_payments[start_index:end_index]
if not page_transactions:
bot.send_message(chat_id, text="❌ No transactions found on this page.")
logger.info(f"No transactions found on page {page}.")
return
message_lines = [f"📜 *Latest Transactions - Page {page}/{total_pages}* 📜\n"]
for payment in page_transactions:
amount_msat = payment.get("amount", 0)
memo = sanitize_memo(payment.get("memo", "No memo provided."))
time_str = payment.get("time", None)
date = parse_time(time_str)
formatted_date = date.strftime("%b %d, %Y %H:%M")
try:
amount_sats = int(abs(amount_msat) / 1000)
except ValueError:
amount_sats = 0
logger.warning(f"Invalid amount_msat value in transaction: {amount_msat}")
sign = "+" if amount_msat > 0 else "-"
emoji = "🟢" if amount_msat > 0 else "🔴"
message_lines.append(f"{emoji} {formatted_date} {sign}{amount_sats} sats")
message_lines.append(f"✉️ Memo: {memo}")
full_message = "\n".join(message_lines)
inline_keyboard = []
if total_pages > 1:
buttons = []
if page > 1:
buttons.append(InlineKeyboardButton("⬅️ Previous", callback_data=f'prev_{page}'))
if page < total_pages:
buttons.append(InlineKeyboardButton("➡️ Next", callback_data=f'next_{page}'))
inline_keyboard.append(buttons)
inline_reply_markup = InlineKeyboardMarkup(inline_keyboard) if inline_keyboard else None
try:
if message_id:
bot.edit_message_text(
chat_id=chat_id,
message_id=message_id,
text=full_message,
parse_mode=ParseMode.MARKDOWN,
reply_markup=inline_reply_markup
)
logger.info(f"Transactions page {page} edited for chat_id: {chat_id}")
else:
bot.send_message(
chat_id=chat_id,
text=full_message,
parse_mode=ParseMode.MARKDOWN,
reply_markup=inline_reply_markup
)
logger.info(f"Transactions page {page} sent to chat_id: {chat_id}")
except Exception as telegram_error:
logger.error(f"Error sending/editing transactions: {telegram_error}")
logger.debug(traceback.format_exc())
def handle_prev_page(update, context):
query = update.callback_query
if not query:
logger.warning("Callback query not found for previous page.")
return
chat_id = query.message.chat.id
message_id = query.message.message_id
data = query.data
match = re.match(r'prev_(\d+)', data)
if match:
current_page = int(match.group(1))
new_page = current_page - 1
if new_page < 1:
new_page = 1
send_transactions_message(chat_id, page=new_page, message_id=message_id)
logger.debug(f"Navigating to previous page: {new_page}")
query.answer()
def handle_next_page(update, context):
query = update.callback_query
if not query:
logger.warning("Callback query not found for next page.")
return
chat_id = query.message.chat.id
message_id = query.message.message_id
data = query.data
match = re.match(r'next_(\d+)', data)
if match:
current_page = int(match.group(1))
new_page = current_page + 1
send_transactions_message(chat_id, page=new_page, message_id=message_id)
logger.debug(f"Navigating to next page: {new_page}")
query.answer()
def handle_balance_callback(query):
try:
chat_id = query.message.chat.id
send_balance_message(chat_id)
logger.debug("Handled balance callback.")
except Exception as e:
logger.error(f"Error handling balance callback: {e}")
logger.debug(traceback.format_exc())
def handle_transactions_inline_callback(query):
try:
chat_id = query.message.chat.id
send_transactions_message(chat_id, page=1, message_id=query.message.message_id)
logger.debug("Handled transactions_inline callback.")
except Exception as e:
logger.error(f"Error handling transactions_inline callback: {e}")
logger.debug(traceback.format_exc())
def handle_donations_inline_callback(query):
data = query.data
try:
if data == 'overwatch_inline' and OVERWATCH_URL:
bot.send_message(
chat_id=query.message.chat.id,
text="🔗 *Overwatch Details:*",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🔗 Open Overwatch", url=OVERWATCH_URL)]
])
)
logger.debug("Handled overwatch_inline callback.")
elif data == 'liveticker_inline' and DONATIONS_URL:
bot.send_message(
chat_id=query.message.chat.id,
text="🔗 *Live Ticker Details:*",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🔗 Open Live Ticker", url=DONATIONS_URL)]
])
)
logger.debug("Handled liveticker_inline callback.")
elif data == 'lnbits_inline' and LNBITS_URL:
bot.send_message(
chat_id=query.message.chat.id,
text="🔗 *LNBits Details:*",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🔗 Open LNBits", url=LNBITS_URL)]
])
)
logger.debug("Handled lnbits_inline callback.")
else:
bot.send_message(
chat_id=query.message.chat.id,
text="❌ No URL configured."
)
logger.warning("No URL configured for the callback data received.")
except Exception as e:
logger.error(f"Error handling donations_inline callback: {e}")
logger.debug(traceback.format_exc())
def handle_other_inline_callbacks(data, query):
bot.answer_callback_query(callback_query_id=query.id, text="❓ Unknown action.")
logger.warning(f"Unknown callback data received: {data}")
def handle_transactions_callback(update, context):
query = update.callback_query
data = query.data
logger.debug(f"Handling callback data: {data}")
if data == 'balance':
handle_balance_callback(query)
elif data == 'transactions_inline':
handle_transactions_inline_callback(query)
elif data.startswith('prev_'):
handle_prev_page(update, context)
elif data.startswith('next_'):
handle_next_page(update, context)
elif data in ['overwatch_inline', 'liveticker_inline', 'lnbits_inline']:
handle_donations_inline_callback(query)
else:
handle_other_inline_callbacks(data, query)
logger.warning(f"Unhandled callback data: {data}")
query.answer()
def handle_info_command(update, context):
chat_id = update.effective_chat.id
logger.info(f"Handling /info command for chat_id: {chat_id}")
interval_info = (
f"🔔 *Balance Change Threshold:* {BALANCE_CHANGE_THRESHOLD} sats\n"
f"🔔 *Highlight Threshold:* {HIGHLIGHT_THRESHOLD} sats\n"
f"🔄 *Latest Payments Fetch Interval:* Every {PAYMENTS_FETCH_INTERVAL} seconds"
)
info_message = (
f"ℹ️ *{INSTANCE_NAME}* - *Information*\n\n"
f"Here are some current settings:\n\n"
f"{interval_info}\n\n"
f"These settings affect how I notify you and highlight incoming payments."
)
try:
bot.send_message(
chat_id=chat_id,
text=info_message,
parse_mode=ParseMode.MARKDOWN,
reply_markup=get_main_keyboard()
)
logger.info(f"Info message sent to chat_id: {chat_id}")
except Exception as telegram_error:
logger.error(f"Error sending /info message: {telegram_error}")
logger.debug(traceback.format_exc())
def handle_help_command(update, context):
chat_id = update.effective_chat.id
logger.info(f"Handling /help command for chat_id: {chat_id}")
help_message = (
f"ℹ️ *{INSTANCE_NAME}* - *Help*\n\n"
"Hello! Here is what I can do for you:\n\n"
"- /balance - Show your current LNbits wallet balance.\n"
"- /transactions - Show your latest transactions with pagination.\n"
"- /info - Display current settings and thresholds.\n"
"- /help - Display this help message.\n"
"- /ticker_ban words - Add forbidden words that will be censored in the Live Ticker.\n\n"
"You can also use the buttons below to quickly navigate through features!"
)
try:
bot.send_message(
chat_id=chat_id,
text=help_message,
parse_mode=ParseMode.MARKDOWN,
reply_markup=get_main_keyboard()
)
logger.info(f"Help message sent to chat_id: {chat_id}")
except Exception as telegram_error:
logger.error(f"Error sending /help message: {telegram_error}")
logger.debug(traceback.format_exc())
def handle_balance(update, context):
chat_id = update.effective_chat.id
logger.debug(f"Handling balance request for chat_id: {chat_id}")
send_balance_message(chat_id)
def handle_latest_transactions(update, context):
chat_id = update.effective_chat.id
logger.debug(f"Handling latest transactions request for chat_id: {chat_id}")
send_transactions_message(chat_id, page=1)
def handle_live_ticker(update, context):
chat_id = update.effective_chat.id
if DONATIONS_URL:
try:
bot.send_message(
chat_id=chat_id,
text="🔗 *Live Ticker Details:*",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🔗 Open Live Ticker", url=DONATIONS_URL)]
])
)
logger.info(f"Live Ticker message sent to chat_id: {chat_id}")
except Exception as e:
logger.error(f"Error sending Live Ticker message: {e}")
logger.debug(traceback.format_exc())
else:
bot.send_message(chat_id=chat_id, text="❌ Live Ticker URL not configured.")
logger.warning("Live Ticker URL not configured.")
def handle_overwatch(update, context):
chat_id = update.effective_chat.id
if OVERWATCH_URL:
try:
bot.send_message(
chat_id=chat_id,
text="🔗 *Overwatch Details:*",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🔗 Open Overwatch", url=OVERWATCH_URL)]
])
)
logger.info(f"Overwatch message sent to chat_id: {chat_id}")
except Exception as e:
logger.error(f"Error sending Overwatch message: {e}")
logger.debug(traceback.format_exc())
else:
bot.send_message(chat_id=chat_id, text="❌ Overwatch URL not configured.")
logger.warning("Overwatch URL not configured.")
def handle_lnbits(update, context):
chat_id = update.effective_chat.id
if LNBITS_URL:
try:
bot.send_message(
chat_id=chat_id,
text="🔗 *LNBits Details:*",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🔗 Open LNBits", url=LNBITS_URL)]
])
)
logger.info(f"LNBits message sent to chat_id: {chat_id}")
except Exception as e:
logger.error(f"Error sending LNBits message: {e}")
logger.debug(traceback.format_exc())
else:
bot.send_message(chat_id=chat_id, text="❌ LNBits URL not configured.")
logger.warning("LNBits URL not configured.")
def process_update(update):
try:
if 'message' in update:
message = update['message']
chat_id = message['chat']['id']
text = message.get('text', '').strip()
logger.debug(f"Received message from chat_id {chat_id}: {text}")
# Only handle specific buttons/text; other inputs are handled by CommandHandlers
if text == "💰 Balance":
handle_balance(None, None)
logger.debug("Handled 💰 Balance button press.")
elif text == "📜 Latest Transactions":
handle_latest_transactions(None, None)
logger.debug("Handled 📜 Latest Transactions button press.")
elif text == "📡 Live Ticker":
handle_live_ticker(None, None)
logger.debug("Handled 📡 Live Ticker button press.")
elif text == "📊 Overwatch":
handle_overwatch(None, None)
logger.debug("Handled 📊 Overwatch button press.")
elif text == "⚡ LNBits":
handle_lnbits(None, None)
logger.debug("Handled ⚡ LNBits button press.")
else:
# Unknown input
bot.send_message(
chat_id=chat_id,
text="❓ I didn't recognize that command. Use /help to see what I can do."
)
logger.warning(f"Unknown message received from chat_id {chat_id}: {text}")
elif 'callback_query' in update:
# Handled by CallbackQueryHandler