-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
799 lines (646 loc) · 26.2 KB
/
Copy pathmain.py
File metadata and controls
799 lines (646 loc) · 26.2 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
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
import json
from http.client import HTTPSConnection
from flask import Flask, request, jsonify, send_file, render_template, send_from_directory
from flask_cors import CORS
import base64
from Crypto.Cipher import AES
import os
from werkzeug.utils import secure_filename
from datetime import datetime, timezone
import sqlite3
import threading
import time
import requests
KEY = b"1234567890abcdef1234567890abcdef" # 32 Bytes = AES-256 — both users must share this key
db_messages = "./dbs/discord_messages.db"
MODULES_DIR = 'modules'
CONFIG_FILE = 'config.json'
stored_token = None
app = Flask(__name__, static_folder='static')
CORS(app, resources={r"/*": {"origins": "*"}})
def pad(data: bytes) -> bytes:
pad_len = 16 - (len(data) % 16)
return data + bytes([pad_len]) * pad_len
def init_db(db_path=db_messages):
os.makedirs(os.path.dirname(db_path), exist_ok=True)
print("INIT DB:", db_path) # debug
create_new = not os.path.exists(db_path)
conn = sqlite3.connect(db_path)
c = conn.cursor()
if create_new:
c.execute("""
CREATE TABLE messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id TEXT,
channel_id TEXT,
guild_id TEXT,
author_id TEXT,
username TEXT,
content TEXT,
timestamp TEXT,
received_at TEXT,
is_dm INTEGER,
is_server INTEGER,
event_type TEXT DEFAULT 'CREATE',
original_content TEXT,
next_li_id TEXT,
prev_li_id TEXT
)
""")
conn.commit()
else:
# Migrate existing DB — add columns if missing
for col, definition in [
('event_type', 'TEXT DEFAULT "CREATE"'),
('original_content', 'TEXT'),
('next_li_id', 'TEXT'),
('prev_li_id', 'TEXT'),
]:
try:
c.execute(f'ALTER TABLE messages ADD COLUMN {col} {definition}')
conn.commit()
except sqlite3.OperationalError:
pass # column already exists
c.execute("""
CREATE TABLE IF NOT EXISTS edits (
message_id TEXT PRIMARY KEY,
content TEXT
)
""")
c.execute("""
CREATE TABLE IF NOT EXISTS temporary_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id TEXT,
message_id TEXT,
content TEXT,
sent_at TEXT,
link TEXT,
received_at TEXT,
delete_after INTEGER DEFAULT 3600
)
""")
try:
c.execute('ALTER TABLE temporary_messages ADD COLUMN delete_after INTEGER DEFAULT 3600')
conn.commit()
except sqlite3.OperationalError:
pass
c.execute("""
CREATE TABLE IF NOT EXISTS user_notes (
user_id TEXT PRIMARY KEY,
username TEXT,
note TEXT,
updated_at TEXT
)
""")
c.execute("""
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token TEXT UNIQUE,
user_id TEXT,
username TEXT,
discriminator TEXT,
global_name TEXT,
avatar TEXT,
email TEXT,
phone TEXT,
mfa_enabled INTEGER DEFAULT 0,
nitro_type INTEGER DEFAULT 0,
added_at TEXT,
is_active INTEGER DEFAULT 0
)
""")
conn.commit()
conn.close()
init_db()
# Messages you want to send
message = "*** ***"+ '\n'*1986 + '*** ***'
# Send a message
def send_message(channel_id, message_text):
header_data = {
"content-type": "application/json",
"authorization": stored_token,
"host": "discordapp.com",
"referrer": f"https://discord.com/channels/{channel_id}"
}
conn = HTTPSConnection("discordapp.com", 443)
message_data = json.dumps({"content": message_text})
conn.request("POST", f"/api/v6/channels/{channel_id}/messages", message_data, header_data)
resp = conn.getresponse()
print(resp.status, resp.reason)
conn.close()
def clear_channel(channel_id):
send_message(channel_id, message)
def check_and_delete_old_messages():
while True:
time.sleep(10) # Check every 10 seconds
conn = sqlite3.connect(db_messages)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute("SELECT * FROM temporary_messages")
messages = [dict(r) for r in c.fetchall()]
conn.close()
if not messages:
continue
now = datetime.now(timezone.utc)
for msg in messages:
try:
sent_at_str = msg['sent_at']
sent_at = datetime.fromisoformat(sent_at_str.replace('Z', '+00:00'))
delete_after = msg.get('delete_after') or 3600
if now.timestamp() >= sent_at.timestamp() + delete_after:
channel_id = msg['channel_id']
message_id = msg['message_id']
link = msg['link']
delete_url = f"https://discord.com/api/v9/channels/{channel_id}/messages/{message_id}"
headers = {
'authorization': stored_token,
'accept': '*/*',
'accept-language': 'en-US,en;q=0.9',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.delete(delete_url, headers=headers)
if response.status_code == 204:
print(f"\n[DELETED] Message {message_id} in channel {channel_id}")
print(f" Content: {msg['content']}")
print(f" Sent at: {sent_at_str}")
print(f" Link: {link}\n")
conn = sqlite3.connect(db_messages)
conn.execute("DELETE FROM temporary_messages WHERE id = ?", (msg['id'],))
conn.commit()
conn.close()
elif response.status_code == 404:
# Already deleted (e.g. by client-side timer) — remove from DB
conn = sqlite3.connect(db_messages)
conn.execute("DELETE FROM temporary_messages WHERE id = ?", (msg['id'],))
conn.commit()
conn.close()
elif response.status_code == 403:
print(f"[FAILED] No permission to delete {message_id} (not author or too old?)")
elif response.status_code == 401:
print("[ERROR] Invalid Discord token!")
return
else:
print(f"[FAILED] Delete {message_id}: {response.status_code} {response.text}")
except Exception as e:
print(f"[ERROR] Failed to process message: {e}")
@app.route("/send", methods=["POST"])
def send():
data = request.get_json(force=True)
print("Received from client:", data)
#text = data.get("text", "No message provided")
# Use DM channel ID if provided, otherwise server channel ID
channel_id = data.get("dmChannelId") or data.get("channelId")
if not channel_id:
return jsonify({"message": "No channel ID provided"}), 400
clear_channel(channel_id)
return jsonify({"message": f"Message sent to channel {channel_id}"}), 200
@app.route('/silentyping')
def serve_silent_typing():
return send_file('./scripts/toggletyping.js', mimetype='application/javascript')
@app.route('/maini')
def serve_main_script():
return send_file('./scripts/client.js', mimetype='application/javascript')
@app.route('/encrypt', methods=['POST'])
def encrypt():
data = request.json
content = data.get('content', '')
plaintext = content.encode()
try:
iv = os.urandom(16)
cipher = AES.new(KEY, AES.MODE_CBC, iv)
padded = pad(plaintext)
ciphertext = cipher.encrypt(padded)
encoded = base64.b64encode(iv + ciphertext).decode()
return jsonify({"content": f"::::{encoded}"})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route('/decrypt', methods=['POST'])
def decrypt():
data = request.json
content = data.get('content', '')
if content.startswith('::::'):
encoded_part = content[4:].strip()
try:
# Base64-dekodieren und AES-entschlüsseln
raw = base64.b64decode(encoded_part)
iv, ciphertext = raw[:16], raw[16:]
cipher = AES.new(KEY, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(ciphertext)
# Padding (PKCS7) entfernen
pad_len = decrypted[-1]
decrypted = decrypted[:-pad_len].decode('utf-8')
return jsonify({"decrypted": decrypted})
except Exception as e:
return jsonify({"error": str(e)}), 400
return jsonify({"message": "no encrypted content"})
@app.route("/static/<path:filename>")
def static_files(filename):
resp = send_from_directory("static", filename)
resp.headers["Access-Control-Allow-Origin"] = "*"
return resp
@app.route("/test.html")
def test():
# Debug: Print where Flask is looking
print("Static folder:", app.static_folder)
print("Looking for:", os.path.join(app.static_folder, 'test.html'))
print("File exists?", os.path.exists(os.path.join(app.static_folder, 'test.html')))
if not os.path.exists(os.path.join(app.static_folder, 'test.html')):
return "File not found on disk!", 404
response = send_from_directory(app.static_folder, 'test.html')
response.headers['Access-Control-Allow-Origin'] = '*'
return response
@app.route("/mainjs")
def js():
resp = send_from_directory("static", "main.js")
resp.headers["Access-Control-Allow-Origin"] = "*"
resp.headers["Content-Type"] = "text/plain"
return resp
@app.route("/style.css")
def style():
resp = send_from_directory("static", "style.css")
resp.headers["Content-Type"] = "text/css"
resp.headers["Access-Control-Allow-Origin"] = "*"
return resp
@app.route("/")
def index():
return send_from_directory(app.static_folder, "index.html")
@app.route('/token', methods=['POST', 'GET'])
def token():
global stored_token
if request.method == 'POST':
data = request.json
stored_token = data.get('token')
return '', 200
return stored_token or '', 200
# ================= CONFIG =================
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'}
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16 MB max file size
# ==========================================
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/images', methods=['POST'])
def upload_image():
# Check if a file was sent
if 'image' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['image']
# If user does not select file, browser submits an empty part
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if file and allowed_file(file.filename):
# Secure the filename
filename = secure_filename(file.filename)
# Optional: add timestamp to avoid overwrites
name, ext = os.path.splitext(filename)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{name}_{timestamp}{ext}"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
print(f"[Saved] {filepath} ({os.path.getsize(filepath)} bytes)")
return jsonify({
"message": "Image saved successfully",
"filename": filename,
"size": os.path.getsize(filepath)
}), 200
else:
return jsonify({"error": "File type not allowed"}), 400
@app.route('/message', methods=['POST'])
def receive_message():
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
message = data.get("message")
channel_id = data.get("channel_id")
location = data.get("location", {})
received_at = data.get("timestamp")
if not message:
return jsonify({"error": "Missing message object"}), 400
msg_id = message.get("id")
author = message.get("author", {})
author_id = author.get("id")
username = author.get("username") or author.get("global_name")
content = message.get("content", "")
timestamp = message.get("timestamp")
is_dm = 1 if location.get("label","").startswith("DM") else 0
is_server = 1 if location.get("label","").startswith("SERVER") else 0
guild_id = location.get("guild_id")
event_type = data.get("event_type", "CREATE")
original_content = message.get("original_content")
conn = sqlite3.connect(f"{db_messages}")
c = conn.cursor()
c.execute("""
INSERT INTO messages
(message_id, channel_id, guild_id, author_id, username, content, timestamp, received_at, is_dm, is_server, event_type, original_content)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
msg_id, channel_id, guild_id, author_id, username, content,
timestamp, received_at, is_dm, is_server, event_type, original_content
))
conn.commit()
conn.close()
return jsonify({"status": "received"}), 200
@app.route('/messages', methods=['GET'])
def get_messages():
conn = sqlite3.connect(db_messages)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute("""
SELECT message_id, channel_id, guild_id, author_id, username, content,
timestamp, received_at, is_dm, is_server, event_type, original_content,
next_li_id, prev_li_id
FROM messages
WHERE event_type IN ('DELETE', 'UPDATE')
ORDER BY id ASC
""")
rows = [dict(r) for r in c.fetchall()]
conn.close()
result = []
for r in rows:
result.append({
"event_type": r["event_type"],
"channel_id": r["channel_id"],
"next_li_id": r["next_li_id"],
"prev_li_id": r["prev_li_id"],
"original_content": r["original_content"],
"message": {
"id": r["message_id"],
"content": r["content"],
"timestamp": r["timestamp"],
"author": {
"id": r["author_id"],
"username": r["username"],
"global_name": r["username"]
}
}
})
return jsonify(result), 200
@app.route('/message', methods=['PATCH'])
def patch_message():
data = request.get_json()
message_id = data.get("message_id")
next_li_id = data.get("next_li_id")
prev_li_id = data.get("prev_li_id")
if not message_id:
return jsonify({"error": "missing message_id"}), 400
conn = sqlite3.connect(db_messages)
c = conn.cursor()
c.execute("""
UPDATE messages SET next_li_id = ?, prev_li_id = ?
WHERE message_id = ? AND event_type = 'DELETE'
""", (next_li_id, prev_li_id, message_id))
conn.commit()
conn.close()
return jsonify({"status": "updated"}), 200
@app.route('/modules/<name>.js', methods=['GET', 'POST'])
def module_handler(name):
path = os.path.join(MODULES_DIR, f'{name}.js')
if request.method == 'GET':
if os.path.exists(path):
return send_from_directory(MODULES_DIR, f'{name}.js'), 200, {
'Content-Type': 'application/javascript'
}
return 'Not Found', 404
elif request.method == 'POST':
data = request.get_json(silent=True) or {}
print(f'[{name}] ACTIVATED:', data)
# Your module logic here
return jsonify(success=True)
@app.route('/config', methods=['GET', 'POST'])
def config_handler():
if request.method == 'GET':
with open(CONFIG_FILE, 'r') as f:
return jsonify(json.load(f))
elif request.method == 'POST':
new_config = request.get_json(silent=True) or {}
with open(CONFIG_FILE, 'w') as f:
json.dump(new_config, f, indent=2)
print('[Config] Saved:', new_config)
return jsonify(success=True)
@app.route('/edits', methods=['GET'])
def get_edits():
conn = sqlite3.connect(db_messages)
c = conn.cursor()
c.execute("SELECT message_id, content FROM edits")
result = {row[0]: row[1] for row in c.fetchall()}
conn.close()
return jsonify(result)
@app.route('/edit', methods=['POST'])
def save_edit():
data = request.json
message_id = data['message_id']
content = data['content']
conn = sqlite3.connect(db_messages)
c = conn.cursor()
c.execute("INSERT OR REPLACE INTO edits (message_id, content) VALUES (?, ?)", (message_id, content))
conn.commit()
conn.close()
print(f"Saved edit: {message_id}")
return jsonify({"status": "saved"})
@app.route('/temporarymessages', methods=['POST'])
def log_message():
if not request.is_json:
return jsonify({'error': 'Content-Type must be application/json'}), 400
payload = request.get_json()
required_keys = ['channel_id', 'message_id', 'content', 'sent_at', 'link']
if not all(key in payload for key in required_keys):
return jsonify({'error': 'Missing required fields'}), 400
received_at = datetime.utcnow().isoformat() + 'Z'
delete_after = payload.get('delete_after', 3600)
conn = sqlite3.connect(db_messages)
conn.execute(
"INSERT INTO temporary_messages (channel_id, message_id, content, sent_at, link, received_at, delete_after) VALUES (?, ?, ?, ?, ?, ?, ?)",
(payload['channel_id'], payload['message_id'], payload['content'], payload['sent_at'], payload['link'], received_at, delete_after)
)
conn.commit()
conn.close()
return jsonify({'status': 'success'}), 200
@app.route('/notes', methods=['GET'])
def get_notes():
conn = sqlite3.connect(db_messages)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute("SELECT user_id, username, note, updated_at FROM user_notes ORDER BY updated_at DESC")
notes = {r['user_id']: {'username': r['username'], 'note': r['note'], 'updated_at': r['updated_at']} for r in c.fetchall()}
conn.close()
return jsonify(notes)
@app.route('/notes/<user_id>', methods=['GET'])
def get_note(user_id):
conn = sqlite3.connect(db_messages)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute("SELECT note, username FROM user_notes WHERE user_id = ?", (user_id,))
row = c.fetchone()
conn.close()
if row:
return jsonify({'note': row['note'], 'username': row['username']})
return jsonify({'note': '', 'username': ''})
@app.route('/notes/<user_id>', methods=['PUT'])
def save_note(user_id):
data = request.get_json()
note = data.get('note', '')
username = data.get('username', '')
updated_at = datetime.utcnow().isoformat() + 'Z'
conn = sqlite3.connect(db_messages)
if note.strip():
conn.execute(
"INSERT OR REPLACE INTO user_notes (user_id, username, note, updated_at) VALUES (?, ?, ?, ?)",
(user_id, username, note, updated_at)
)
else:
conn.execute("DELETE FROM user_notes WHERE user_id = ?", (user_id,))
conn.commit()
conn.close()
return jsonify({'status': 'saved'})
NOTE_IMAGES_DIR = 'uploads/note_images'
os.makedirs(NOTE_IMAGES_DIR, exist_ok=True)
@app.route('/notes/image', methods=['POST'])
def upload_note_image():
if 'image' not in request.files:
return jsonify({'error': 'No image'}), 400
file = request.files['image']
if not file.filename:
return jsonify({'error': 'Empty filename'}), 400
ext = os.path.splitext(file.filename)[1].lower() or '.png'
if ext not in ('.png', '.jpg', '.jpeg', '.gif', '.webp'):
return jsonify({'error': 'Invalid image type'}), 400
name = f"{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}_{os.urandom(4).hex()}{ext}"
path = os.path.join(NOTE_IMAGES_DIR, name)
file.save(path)
return jsonify({'url': f'http://127.0.0.1:5000/notes/image/{name}'}), 200
@app.route('/notes/image/<filename>', methods=['GET'])
def serve_note_image(filename):
return send_from_directory(NOTE_IMAGES_DIR, filename)
# ================= ACCOUNTS =================
def fetch_discord_user(token):
"""Fetch user info from Discord API using a token."""
try:
r = requests.get('https://discord.com/api/v9/users/@me', headers={'Authorization': token}, timeout=10)
if r.status_code == 200:
return r.json()
return None
except:
return None
@app.route('/accounts', methods=['GET'])
def get_accounts():
conn = sqlite3.connect(db_messages)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute("SELECT id, user_id, username, discriminator, global_name, avatar, email, phone, mfa_enabled, nitro_type, added_at, is_active FROM accounts ORDER BY is_active DESC, added_at DESC")
accounts = [dict(r) for r in c.fetchall()]
conn.close()
return jsonify(accounts)
@app.route('/accounts', methods=['POST'])
def add_account():
global stored_token
data = request.get_json()
token = data.get('token', '').strip()
if not token or len(token) < 50:
return jsonify({'error': 'Invalid token'}), 400
user = fetch_discord_user(token)
if not user:
return jsonify({'error': 'Token is invalid or expired'}), 400
# Determine nitro type from premium_type
nitro_type = user.get('premium_type', 0) or 0
conn = sqlite3.connect(db_messages)
c = conn.cursor()
# Check if token already exists
c.execute("SELECT id FROM accounts WHERE token = ?", (token,))
if c.fetchone():
# Update existing account info
c.execute("""UPDATE accounts SET user_id=?, username=?, discriminator=?, global_name=?, avatar=?, email=?, phone=?, mfa_enabled=?, nitro_type=?
WHERE token=?""",
(user['id'], user['username'], user.get('discriminator','0'), user.get('global_name',''),
user.get('avatar',''), user.get('email',''), user.get('phone',''),
1 if user.get('mfa_enabled') else 0, nitro_type, token))
conn.commit()
conn.close()
return jsonify({'status': 'updated', 'username': user['username']})
added_at = datetime.utcnow().isoformat() + 'Z'
# Deactivate all others, set this one active
c.execute("UPDATE accounts SET is_active = 0")
c.execute("""INSERT INTO accounts (token, user_id, username, discriminator, global_name, avatar, email, phone, mfa_enabled, nitro_type, added_at, is_active)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)""",
(token, user['id'], user['username'], user.get('discriminator','0'), user.get('global_name',''),
user.get('avatar',''), user.get('email',''), user.get('phone',''),
1 if user.get('mfa_enabled') else 0, nitro_type, added_at))
conn.commit()
conn.close()
stored_token = token
return jsonify({'status': 'added', 'username': user['username'], 'user_id': user['id']})
@app.route('/accounts/<int:account_id>/switch', methods=['POST'])
def switch_account(account_id):
global stored_token
conn = sqlite3.connect(db_messages)
c = conn.cursor()
c.execute("SELECT token FROM accounts WHERE id = ?", (account_id,))
row = c.fetchone()
if not row:
conn.close()
return jsonify({'error': 'Account not found'}), 404
c.execute("UPDATE accounts SET is_active = 0")
c.execute("UPDATE accounts SET is_active = 1 WHERE id = ?", (account_id,))
conn.commit()
conn.close()
stored_token = row[0]
return jsonify({'status': 'switched'})
@app.route('/accounts/<int:account_id>', methods=['DELETE'])
def delete_account(account_id):
global stored_token
conn = sqlite3.connect(db_messages)
c = conn.cursor()
c.execute("SELECT token, is_active FROM accounts WHERE id = ?", (account_id,))
row = c.fetchone()
if not row:
conn.close()
return jsonify({'error': 'Account not found'}), 404
was_active = row[1]
c.execute("DELETE FROM accounts WHERE id = ?", (account_id,))
# If deleted account was active, activate next one if available
if was_active:
c.execute("SELECT id, token FROM accounts ORDER BY added_at DESC LIMIT 1")
next_acc = c.fetchone()
if next_acc:
c.execute("UPDATE accounts SET is_active = 1 WHERE id = ?", (next_acc[0],))
stored_token = next_acc[1]
else:
stored_token = None
conn.commit()
conn.close()
return jsonify({'status': 'deleted'})
@app.route('/accounts/<int:account_id>/refresh', methods=['POST'])
def refresh_account(account_id):
conn = sqlite3.connect(db_messages)
c = conn.cursor()
c.execute("SELECT token FROM accounts WHERE id = ?", (account_id,))
row = c.fetchone()
if not row:
conn.close()
return jsonify({'error': 'Account not found'}), 404
user = fetch_discord_user(row[0])
if not user:
conn.close()
return jsonify({'error': 'Token invalid or expired'}), 400
nitro_type = user.get('premium_type', 0) or 0
c.execute("""UPDATE accounts SET user_id=?, username=?, discriminator=?, global_name=?, avatar=?, email=?, phone=?, mfa_enabled=?, nitro_type=?
WHERE id=?""",
(user['id'], user['username'], user.get('discriminator','0'), user.get('global_name',''),
user.get('avatar',''), user.get('email',''), user.get('phone',''),
1 if user.get('mfa_enabled') else 0, nitro_type, account_id))
conn.commit()
conn.close()
return jsonify({'status': 'refreshed'})
TOOLKIT_VERSION = '1.0.0'
@app.route('/version', methods=['GET'])
def get_version():
return jsonify({ 'version': TOOLKIT_VERSION, 'reload': True })
if __name__ == "__main__":
# Start the background checker thread
checker_thread = threading.Thread(target=check_and_delete_old_messages, daemon=True)
checker_thread.start()
app.run(port=5000)