Alibrown commited on
Commit
d118094
·
verified ·
1 Parent(s): 2c942f7

Create bank.py

Browse files
Files changed (1) hide show
  1. bank.py +335 -0
bank.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # bank.py
2
+ # Core banking logic for Discord Bank Bot
3
+ # Handles accounts, transactions, daily rewards, and balance management
4
+ # Designed for async operation and persistence via Neocities API
5
+ # Author: V. Kücükbudak, 2025
6
+ # License: See LICENSE file for usage restrictions
7
+ import asyncio
8
+ import httpx
9
+ import json
10
+ import logging
11
+ import os
12
+ import random
13
+ import aiofiles
14
+ import aiofiles.os as async_os
15
+ from datetime import datetime, timedelta
16
+
17
+ # Logging konfigurieren
18
+ logger = logging.getLogger(__name__)
19
+
20
+ NEOCITIES_BANK_DATA_URL = "https://koeniglichepost.neocities.org/bank_data.json"
21
+ # Korrigierter Pfad: Verwende /tmp für Schreibzugriff
22
+ LOCAL_BANK_DATA_FILE = '/tmp/local_bank_data.json'
23
+
24
+ DAILY_REWARD_MIN = 50
25
+ DAILY_REWARD_MAX = 150
26
+
27
+ class TransactionError(Exception):
28
+ """Benutzerdefinierte Exception für Transaktionsfehler"""
29
+ def __init__(self, message, error_type="TRANSACTION_ERROR"):
30
+ self.message = message
31
+ self.error_type = error_type
32
+ super().__init__(self.message)
33
+
34
+ class BankAccount:
35
+ def __init__(self, user_id, balance=0.0):
36
+ if not isinstance(user_id, (int, str)):
37
+ raise ValueError("user_id muss eine Zahl oder String sein")
38
+ if balance < 0:
39
+ raise ValueError("Startguthaben kann nicht negativ sein")
40
+
41
+ self.user_id = str(user_id)
42
+ self.balance = float(balance)
43
+
44
+ def to_json_serializable(self):
45
+ return {
46
+ "user_id": self.user_id,
47
+ "balance": round(self.balance, 2),
48
+ }
49
+
50
+ def deposit(self, amount):
51
+ if not isinstance(amount, (int, float)) or amount <= 0:
52
+ raise TransactionError("Einzahlungsbetrag muss eine positive Zahl sein.", "INVALID_DEPOSIT_AMOUNT")
53
+ self.balance += amount
54
+ logger.info(f"Konto {self.user_id}: Einzahlung von {amount:.2f} Credits. Neuer Saldo: {self.balance:.2f}")
55
+ return self.balance
56
+
57
+ def withdraw(self, amount):
58
+ if not isinstance(amount, (int, float)) or amount <= 0:
59
+ raise TransactionError("Abhebungsbetrag muss eine positive Zahl sein.", "INVALID_WITHDRAW_AMOUNT")
60
+ if amount > self.balance:
61
+ raise TransactionError("Nicht genügend Geld auf dem Konto.", "INSUFFICIENT_FUNDS")
62
+ self.balance -= amount
63
+ logger.info(f"Konto {self.user_id}: Abhebung von {amount:.2f} Credits. Neuer Saldo: {self.balance:.2f}")
64
+ return self.balance
65
+
66
+ def get_balance(self):
67
+ return self.balance
68
+
69
+ def format_balance(self):
70
+ return f"{self.balance:,.2f} Credits"
71
+
72
+ class BankSystem:
73
+ def __init__(self):
74
+ self.accounts = {}
75
+ self.raw_full_bank_data = {}
76
+ self._asyncio_loop = None
77
+ self.data_loaded = False
78
+
79
+ async def ensure_data_loaded(self):
80
+ """Stellt sicher, dass Daten geladen sind"""
81
+ if not self.data_loaded:
82
+ await self.load_bank_data()
83
+ self.data_loaded = True
84
+
85
+ async def load_bank_data(self):
86
+ logger.debug("load_bank_data: Starte Ladevorgang...")
87
+ loaded_full_data = {}
88
+ try:
89
+ # Versuche immer zuerst von Neocities zu laden
90
+ loaded_full_data = await self._fetch_from_neocities(NEOCITIES_BANK_DATA_URL, LOCAL_BANK_DATA_FILE)
91
+ except TransactionError as e:
92
+ logger.warning(f"Neocities-Ladefehler, versuche lokalen Fallback: {e}")
93
+
94
+ # Fallback: Lokale Datei in /tmp laden
95
+ if await async_os.path.exists(LOCAL_BANK_DATA_FILE):
96
+ try:
97
+ async with aiofiles.open(LOCAL_BANK_DATA_FILE, 'r', encoding='utf-8') as f:
98
+ content = await f.read()
99
+ loaded_full_data = json.loads(content)
100
+ logger.info("Bankdaten aus lokalem Fallback geladen.")
101
+ except Exception as e:
102
+ logger.error(f"Fehler beim Laden lokaler Daten: {e}")
103
+ loaded_full_data = self._create_empty_bank_data()
104
+ else:
105
+ loaded_full_data = self._create_empty_bank_data()
106
+
107
+ self.raw_full_bank_data = loaded_full_data
108
+ self.accounts = {}
109
+
110
+ bank_accounts_data = self.raw_full_bank_data.get("bank_accounts", {})
111
+ for user_id, data_entry in bank_accounts_data.items():
112
+ if user_id and isinstance(data_entry, dict):
113
+ balance = data_entry.get('balance', 0.0)
114
+ self.accounts[user_id] = BankAccount(user_id, balance=balance)
115
+
116
+ logger.info(f"Insgesamt {len(self.accounts)} Konten geladen.")
117
+
118
+ def _create_empty_bank_data(self):
119
+ """Erstellt leere Bankdaten-Struktur"""
120
+ return {
121
+ "last_bank_update": datetime.utcnow().isoformat(),
122
+ "bank_accounts": {},
123
+ "bank_transactions_log": []
124
+ }
125
+
126
+ async def _fetch_from_neocities(self, url: str, save_path: str):
127
+ logger.debug(f"_fetch_from_neocities: Abrufen von {url}...")
128
+ try:
129
+ async with httpx.AsyncClient(timeout=10.0) as client:
130
+ response = await client.get(url)
131
+ response.raise_for_status()
132
+ data = response.json()
133
+ logger.info("Bankdaten erfolgreich von Neocities geladen.")
134
+
135
+ # Speichere die Daten in /tmp
136
+ async with aiofiles.open(save_path, 'w', encoding='utf-8') as f:
137
+ await f.write(json.dumps(data, indent=4))
138
+ logger.info(f"Bankdaten in {save_path} gespeichert.")
139
+ return data
140
+ except Exception as e:
141
+ logger.error(f"Fehler beim Laden von Neocities: {e}")
142
+ raise TransactionError(f"Neocities-Fehler: {str(e)}", "NEOCITIES_FETCH_ERROR")
143
+
144
+ async def save_bank_data_to_temp(self):
145
+ logger.debug("save_bank_data_to_temp: Starte Speichervorgang...")
146
+ try:
147
+ updated_bank_accounts = {}
148
+ for user_id, account_obj in self.accounts.items():
149
+ account_data = {
150
+ "user_id": user_id,
151
+ "balance": round(account_obj.balance, 2),
152
+ # Behalte vorhandene Felder bei
153
+ "username": self.raw_full_bank_data.get("bank_accounts", {}).get(user_id, {}).get("username", "Unbekannt"),
154
+ "interest_rate": self.raw_full_bank_data.get("bank_accounts", {}).get(user_id, {}).get("interest_rate", 0.0),
155
+ "last_daily_claim": self.raw_full_bank_data.get("bank_accounts", {}).get(user_id, {}).get("last_daily_claim", None),
156
+ # ... andere Felder hier
157
+ }
158
+ updated_bank_accounts[user_id] = account_data
159
+
160
+ self.raw_full_bank_data["bank_accounts"] = updated_bank_accounts
161
+ self.raw_full_bank_data["last_bank_update"] = datetime.utcnow().isoformat()
162
+
163
+ async with aiofiles.open(LOCAL_BANK_DATA_FILE, 'w', encoding='utf-8') as f:
164
+ await f.write(json.dumps(self.raw_full_bank_data, indent=4))
165
+ logger.info(f"Bankdaten gespeichert: {LOCAL_BANK_DATA_FILE}")
166
+ except Exception as e:
167
+ logger.error(f"Fehler beim Speichern der Bankdaten: {e}", exc_info=True)
168
+
169
+ async def get_account(self, user_id):
170
+ user_id_str = str(user_id)
171
+
172
+ if user_id_str not in self.accounts:
173
+ # Erstelle neues Konto, falls nicht vorhanden
174
+ new_account = BankAccount(user_id_str, balance=0.0)
175
+ self.accounts[user_id_str] = new_account
176
+
177
+ # Füge zum Hauptdatensatz hinzu
178
+ if "bank_accounts" not in self.raw_full_bank_data:
179
+ self.raw_full_bank_data["bank_accounts"] = {}
180
+
181
+ self.raw_full_bank_data["bank_accounts"][user_id_str] = {
182
+ "user_id": user_id_str,
183
+ "balance": 0.0,
184
+ "username": "Unbekannt",
185
+ "last_daily_claim": None,
186
+ # ... andere Standardwerte
187
+ }
188
+ logger.info(f"Neues Konto erstellt: {user_id_str}")
189
+
190
+ return self.accounts[user_id_str]
191
+
192
+ async def get_user_data_raw(self, user_id):
193
+ user_id_str = str(user_id)
194
+ await self.get_account(user_id_str)
195
+ return self.raw_full_bank_data.get("bank_accounts", {}).get(user_id_str)
196
+
197
+ async def update_user_data_raw(self, user_id, data: dict):
198
+ user_id_str = str(user_id)
199
+ if user_id_str not in self.raw_full_bank_data.get("bank_accounts", {}):
200
+ await self.get_account(user_id_str)
201
+
202
+ # Aktualisiere nur die angegebenen Felder
203
+ current_data = self.raw_full_bank_data["bank_accounts"][user_id_str]
204
+ current_data.update(data)
205
+
206
+ await self.save_bank_data_to_temp()
207
+
208
+ async def transfer_credits(self, from_user_id, to_user_id, amount):
209
+ from_user_id_str = str(from_user_id)
210
+ to_user_id_str = str(to_user_id)
211
+
212
+ if from_user_id_str == to_user_id_str:
213
+ raise TransactionError("Selbstüberweisung ist nicht erlaubt!", "SELF_TRANSFER_NOT_ALLOWED")
214
+ if amount <= 0:
215
+ raise TransactionError("Der Betrag muss positiv sein.", "INVALID_AMOUNT")
216
+
217
+ from_account = await self.get_account(from_user_id_str)
218
+ to_account = await self.get_account(to_user_id_str)
219
+
220
+ if from_account.get_balance() < amount:
221
+ raise TransactionError("Nicht genügend Geld auf dem Konto.", "INSUFFICIENT_FUNDS")
222
+
223
+ from_account.withdraw(amount)
224
+ to_account.deposit(amount)
225
+
226
+ # Aktualisiere die Kontostände in den Rohdaten
227
+ await self.update_user_data_raw(from_user_id_str, {"balance": from_account.balance})
228
+ await self.update_user_data_raw(to_user_id_str, {"balance": to_account.balance})
229
+
230
+ return True
231
+
232
+ async def get_daily_reward(self, user_id):
233
+ user_id_str = str(user_id)
234
+ user_data = await self.get_user_data_raw(user_id_str)
235
+
236
+ # Cooldown-Überprüfung
237
+ last_claimed = user_data.get('last_daily_claim')
238
+ if last_claimed:
239
+ try:
240
+ # Konvertiere den String in ein datetime-Objekt
241
+ last_claimed = datetime.fromisoformat(last_claimed.replace('Z', '+00:00'))
242
+ now_utc = datetime.utcnow()
243
+
244
+ # Überprüfe, ob seit dem letzten Claim weniger als 24 Stunden vergangen sind
245
+ if (now_utc - last_claimed) < timedelta(hours=24):
246
+ next_claim_time = last_claimed + timedelta(hours=24)
247
+ return {
248
+ "success": False,
249
+ "message": f"❌ Du hast deine tägliche Belohnung bereits erhalten! Nächste Belohnung verfügbar ab: "
250
+ f"{next_claim_time.strftime('%Y-%m-%d %H:%M:%S UTC')}"
251
+ }
252
+ except Exception as e:
253
+ logger.error(f"Fehler bei der Verarbeitung des letzten Claims: {e}")
254
+
255
+ # Berechne die Belohnung
256
+ reward_amount = random.randint(DAILY_REWARD_MIN, DAILY_REWARD_MAX)
257
+ account = self.accounts[user_id_str]
258
+ account.deposit(reward_amount)
259
+
260
+ # Aktualisiere den letzten Claim-Zeitpunkt
261
+ new_last_claim = datetime.utcnow().isoformat() + 'Z'
262
+ await self.update_user_data_raw(user_id_str, {
263
+ "balance": account.balance,
264
+ "last_daily_claim": new_last_claim
265
+ })
266
+
267
+ return {
268
+ "success": True,
269
+ "amount": reward_amount,
270
+ "new_balance": account.balance
271
+ }
272
+
273
+ async def get_balance(self, user_id):
274
+ await self.ensure_data_loaded()
275
+ account = await self.get_account(user_id)
276
+ return account.get_balance()
277
+
278
+ def _generate_transaction_id(self):
279
+ timestamp_str = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3]
280
+ random_suffix = ''.join(random.choices('0123456789ABCDEF', k=6))
281
+ return f"TRX-{timestamp_str}-{random_suffix}"
282
+
283
+ # --- Initialisierung des Bank-Systems ---
284
+ bank_system_instance = None
285
+ bank_task_queue = asyncio.Queue()
286
+
287
+ async def initialize_bank_system_and_run_tasks():
288
+ global bank_system_instance
289
+ if bank_system_instance is None:
290
+ logger.info("Bank-System wird gestartet...")
291
+ bank_system_instance = BankSystem()
292
+ await bank_system_instance.ensure_data_loaded()
293
+ logger.info("Bank-System erfolgreich initialisiert.")
294
+
295
+ logger.info("Bank-System ist bereit für Aufgaben.")
296
+ while True:
297
+ task_data = await bank_task_queue.get()
298
+ command_name = task_data['command_name']
299
+ user_id = task_data['user_id']
300
+ future = task_data['future']
301
+
302
+ try:
303
+ if command_name == "balance":
304
+ balance = await bank_system_instance.get_balance(user_id)
305
+ content = f"Dein aktuelles Guthaben beträgt: **{balance:,.2f} Credits**."
306
+ future.set_result({'content': content, 'flags': 0})
307
+
308
+ elif command_name == "daily":
309
+ result = await bank_system_instance.get_daily_reward(user_id)
310
+ if result["success"]:
311
+ content = f"Du hast {result['amount']} Credits als tägliche Belohnung erhalten! Dein neues Guthaben: **{result['new_balance']:,.2f} Credits**."
312
+ else:
313
+ content = result["message"]
314
+ future.set_result({'content': content, 'flags': 0})
315
+
316
+ elif command_name == "transfer":
317
+ recipient_id = None
318
+ amount_to_transfer = 0.0
319
+ for opt in task_data.get('options', []):
320
+ if opt["name"] == "recipient":
321
+ recipient_id = opt["value"]
322
+ elif opt["name"] == "amount":
323
+ amount_to_transfer = float(opt["value"])
324
+
325
+ await bank_system_instance.transfer_credits(user_id, recipient_id, amount_to_transfer)
326
+ content = f"✅ Erfolgreich **{amount_to_transfer:,.2f} Credits** an <@{recipient_id}> überwiesen."
327
+ future.set_result({'content': content, 'flags': 0})
328
+
329
+ except TransactionError as e:
330
+ future.set_result({'content': f"❌ Fehler: {e.message}", 'flags': 64})
331
+ except Exception as e:
332
+ logger.error(f"Kritischer Fehler: {e}", exc_info=True)
333
+ future.set_result({'content': f"❌ Systemfehler: {str(e)}", 'flags': 64})
334
+
335
+ bank_task_queue.task_done()