Repository navigation
Expand file tree
/
Copy pathfaucet_stats.py
More file actions
143 lines (122 loc) · 4.43 KB
/
Copy pathfaucet_stats.py
File metadata and controls
143 lines (122 loc) · 4.43 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
#!/usr/bin/env python3
import requests
import sqlite3
from datetime import datetime, timedelta
from collections import defaultdict
from typing import Dict, List, Optional
import json
import os
# SQLite database paths (from config.yaml)
DB_PATH = "data/bot.db" # Main user database
TRANSACTIONS_PATH = "data/transactions.db" # Transactions database
# Headers for API requests
#headers = {
# "X-Api-Key": ADMIN_KEY,
# "Content-type": "application/json"
#}
def get_transactions_from_sqlite() -> List[Dict]:
"""Get all faucet transactions from the local SQLite database"""
if not os.path.exists(TRANSACTIONS_PATH):
print(f"Error: Transactions database not found at {TRANSACTIONS_PATH}")
return []
conn = sqlite3.connect(TRANSACTIONS_PATH)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Get transactions from the last week where type is 'faucet'
twelve_months_ago = int((datetime.now() - timedelta(days=7)).timestamp())
query = """
SELECT
from_user as sender,
to_user as recipient,
amount,
time,
type,
success,
memo
FROM transactions
WHERE type = 'faucet'
AND success = 1
AND time >= datetime(?, 'unixepoch')
"""
try:
cursor.execute(query, (twelve_months_ago,))
rows = cursor.fetchall()
return [dict(row) for row in rows]
except sqlite3.Error as e:
print(f"Error querying SQLite database: {e}")
return []
finally:
conn.close()
def get_user_info_from_sqlite(user_id: str) -> Optional[Dict]:
"""Get user information from the local SQLite database"""
if not os.path.exists(DB_PATH):
print(f"Error: User database not found at {DB_PATH}")
return None
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
cursor.execute("""
SELECT
name,
telegram_username,
wallet_id,
wallet_name,
wallet_balance
FROM users
WHERE name = ? OR telegram_username = ?
""", (user_id, user_id))
row = cursor.fetchone()
return dict(row) if row else None
except sqlite3.Error as e:
print(f"Error querying SQLite database: {e}")
return None
finally:
conn.close()
def analyze_faucet_transactions() -> tuple[Dict[str, int], Dict[str, int], Dict[str, int]]:
"""
Analyze faucet transactions to get:
1. Total amount distributed per user
2. Total amount received per user
Combines data from both SQLite and LNbits API
"""
# Track distributions and receipts
distributions = defaultdict(int) # username -> total amount
receipts = defaultdict(int) # username -> total amount
balance = defaultdict(int) # username -> total amount
# Get transactions from SQLite
transactions = get_transactions_from_sqlite()
for tx in transactions:
# Skip failed transactions
if not tx['success']:
continue
# Get sender and recipient usernames
sender = tx['sender']
recipient = tx['recipient']
amount = tx['amount']
if "faucet" in tx['type'].lower():
distributions[sender] += amount
receipts[recipient] += amount
balance[sender] += amount
balance[recipient] += -amount
return dict(distributions), dict(receipts), dict(balance)
def format_stats(stats: Dict[str, int], title: str) -> str:
"""Format statistics for display"""
result = [f"\n{title}:"]
for username, amount in sorted(stats.items(), key=lambda x: x[1], reverse=True):
# Convert amount from sats to BTC for readability
sats = amount
result.append(f" {username}: {sats:,.0f} sats")
return "\n".join(result)
def main():
print("Fetching faucet statistics...")
# Analyze transactions from both sources
distributions, receipts, balance = analyze_faucet_transactions()
# Display results
print("\nFaucet Statistics for the Last 7 Days:")
print("-" * 50)
print(format_stats(distributions, "Total Amount Distributed per User of last 7 days"))
print(format_stats(receipts, "Total Amount Received per User of last 7 days"))
print(format_stats(balance, "Balance of Faucets per User of last 7 days (negative = lurker)"))
# Run
main()