-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbridge.py
More file actions
1241 lines (1017 loc) · 54 KB
/
bridge.py
File metadata and controls
1241 lines (1017 loc) · 54 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
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
#!/usr/bin/env python3
"""
Discord / Stoat Bridge (Bidirectional & One-Way)
██╗ ███╗ ███╗ ██████╗
██║ ████╗ ████║ ██╔════╝
██║ ██╔████╔██║ ██║ ███╗
██ ██║ ██║╚██╔╝██║ ██║ ██║
╚█████╔╝ ██║ ╚═╝ ██║ ╚██████╔╝
╚════╝ ╚═╝ ╚═╝ ╚═════╝
Thank you for downloading!
Please refer to readme.md for more info.
GitHub: https://github.com/JMGstudios/DiscordStoatBridgeBot
Support stoat server: https://stt.gg/FH10z8eP
Support discord server: https://discord.gg/QTVRxUDSMq
"""
import asyncio
import io
import json
import logging
import os
import re
import sys
from collections import OrderedDict
from pathlib import Path
from types import SimpleNamespace
import aiohttp
import discord
from discord.ext import commands
from dotenv import load_dotenv, set_key, dotenv_values
import stoat
# ──────────────────────────────────────────────────────────────────────────────
# INTERACTIVE .env SETUP
# ──────────────────────────────────────────────────────────────────────────────
ENV_FILE = Path(".env")
def _prompt(label: str, secret: bool = False, allow_empty: bool = False) -> str:
"""Prompt the user on the terminal until a non-empty value is entered."""
import getpass
while True:
try:
if secret:
print(f" {label}:")
print(" ⌨ Typing is hidden for security – this is normal, just type and press Enter.")
value = getpass.getpass(" > ").strip()
else:
value = input(f" {label}: ").strip()
except (EOFError, KeyboardInterrupt):
print("\nSetup aborted.")
raise SystemExit(1)
if value or allow_empty:
return value
print(" ⚠ Value cannot be empty, please try again.")
def _prompt_channel_pairs() -> tuple[str, str, str]:
print(" You will now link Discord channels to Stoat channels one pair at a time.")
print(" Each pair bridges one Discord channel with one Stoat channel.\n")
discord_ids: list[str] = []
stoat_ids: list[str] = []
directions: list[str] = []
pair_num = 1
_DIR_LABELS = {"bi": "↔ Bidirectional", "discord": "→ Discord → Stoat only", "stoat": "← Stoat → Discord only"}
while True:
print(f" ── Pair {pair_num} {'(first pair)' if pair_num == 1 else ''} ──")
d_id = _prompt(f" Discord Channel ID for pair {pair_num}")
s_id = _prompt(f" Stoat Channel ID for pair {pair_num}")
discord_ids.append(d_id.strip())
stoat_ids.append(s_id.strip())
# ── Direction prompt ──────────────────────────────────────────────────
print(f"\n Bridge direction for pair {pair_num}:")
print(f"\n Choose wether your bridge should be bidirectional or only transfer messages in one direction")
print(" [1] Bidirectional (Discord ↔ Stoat)")
print(" [2] Discord → Stoat only")
print(" [3] Stoat → Discord only")
while True:
try:
dir_choice = input(" Choice [1/2/3]: ").strip()
except (EOFError, KeyboardInterrupt):
print("\nSetup aborted.")
raise SystemExit(1)
if dir_choice == "1":
direction = "bi"
break
elif dir_choice == "2":
direction = "discord"
break
elif dir_choice == "3":
direction = "stoat"
break
print(" ⚠ Please enter 1, 2, or 3.")
directions.append(direction)
print(f"\n ✔ Pair {pair_num} saved: Discord {d_id.strip()} {_DIR_LABELS[direction]} Stoat {s_id.strip()}")
if pair_num >= 2:
print(f"\n Current pairs:")
for i, (d, s, dr) in enumerate(zip(discord_ids, stoat_ids, directions), 1):
print(f" {i}. Discord {d} {_DIR_LABELS[dr]} Stoat {s}")
print()
try:
again = input(" Add another channel pair? [y/n]: ").strip().lower()
except (EOFError, KeyboardInterrupt):
print("\nSetup aborted.")
raise SystemExit(1)
if again in ("y", "yes"):
pair_num += 1
else:
break
return ",".join(discord_ids), ",".join(stoat_ids), ",".join(directions)
def _validate_channel_pairs(discord_raw: str, stoat_raw: str) -> bool:
d = [x.strip() for x in discord_raw.split(",") if x.strip()]
s = [x.strip() for x in stoat_raw.split(",") if x.strip()]
return bool(d) and bool(s) and len(d) == len(s)
def interactive_env_setup() -> None:
"""
- .env does not exist → create it from scratch via prompts
- .env exists but is corrupted / unparseable → prompt for all values
- .env exists but specific keys are missing or empty → prompt only for those
- .env exists but DISCORD_CHANNEL_IDS / STOAT_CHANNEL_IDS are mismatched → re-prompt for both
"""
existing: dict[str, str] = {}
if ENV_FILE.exists():
try:
existing = {k: (v or "") for k, v in dotenv_values(ENV_FILE).items()}
except Exception as exc:
print(f"⚠ Could not parse {ENV_FILE}: {exc}")
print(" Starting fresh – you will be asked for all values.\n")
needs_discord_token = not existing.get("DISCORD_BOT_TOKEN", "").strip()
needs_stoat_token = not existing.get("STOAT_BOT_TOKEN", "").strip()
discord_raw = existing.get("DISCORD_CHANNEL_IDS", "")
stoat_raw = existing.get("STOAT_CHANNEL_IDS", "")
needs_channels = not _validate_channel_pairs(discord_raw, stoat_raw)
# Directions must exist and match pair count; if not, re-prompt channels too.
_dir_raw = existing.get("CHANNEL_DIRECTIONS", "")
_dir_list = [x.strip() for x in _dir_raw.split(",") if x.strip()]
_pair_count = len([x for x in discord_raw.split(",") if x.strip()])
_valid_dirs = {"bi", "discord", "stoat"}
if not needs_channels and (
len(_dir_list) != _pair_count
or any(d not in _valid_dirs for d in _dir_list)
):
needs_channels = True # re-prompt pairs + directions together
needs_revolt_url = (
not existing.get("REVOLT_API_URL", "").strip()
or not existing.get("REVOLT_WS_URL", "").strip()
or not existing.get("REVOLT_CDN_URL", "").strip()
)
anything_missing = any([
needs_discord_token, needs_stoat_token, needs_channels, needs_revolt_url,
])
if not anything_missing:
load_dotenv(ENV_FILE)
print(f"Config loaded from: {ENV_FILE.resolve()}")
return # All set, setup isnt needed
banner = "=" * 60
print(f"\n{banner}")
print(" Stoat ↔ Discord Bridge – First-Time / Repair Setup")
print(banner)
if not ENV_FILE.exists():
print(" ℹ No .env file found – let's create one.")
else:
missing_keys = []
if needs_discord_token: missing_keys.append("DISCORD_BOT_TOKEN")
if needs_stoat_token: missing_keys.append("STOAT_BOT_TOKEN")
if needs_channels: missing_keys.append("DISCORD_CHANNEL_IDS / STOAT_CHANNEL_IDS / CHANNEL_DIRECTIONS")
if needs_revolt_url: missing_keys.append("REVOLT_API_URL / REVOLT_WS_URL / REVOLT_CDN_URL")
print(f" ⚠ Missing or invalid keys: {', '.join(missing_keys)}")
print(" Press Ctrl-C at any time to abort.\n")
# Discord bot token
if needs_discord_token:
print("› Discord Bot Token")
print(" Get it at: https://discord.com/developers/applications")
existing["DISCORD_BOT_TOKEN"] = _prompt("Discord Bot Token", secret=True)
print()
# Stoat bot token
if needs_stoat_token:
print("› Stoat Bot Token")
print(" Get it in your Stoat server's bot settings.")
existing["STOAT_BOT_TOKEN"] = _prompt("Stoat Bot Token", secret=True)
print()
# Channel pairs – collected one pair at a time
if needs_channels:
print("› Channel Pairs")
d_raw, s_raw, dir_raw = _prompt_channel_pairs()
existing["DISCORD_CHANNEL_IDS"] = d_raw
existing["STOAT_CHANNEL_IDS"] = s_raw
existing["CHANNEL_DIRECTIONS"] = dir_raw
print()
# Revolt API URL + WebSocket URL (both optional – sensible defaults)
if needs_revolt_url:
print("› Revolt / Stoat API URL (HTTP)")
print(" Press Enter to accept the default!")
print(" Only change this if you are using a self-hosted instance.")
url = _prompt("API URL [https://api.revolt.chat]", allow_empty=True)
existing["REVOLT_API_URL"] = url or "https://api.revolt.chat"
print()
print()
print("› Revolt / Stoat WebSocket URL")
print(" Press Enter to accept the default!")
print(" Only change this if you are using a self-hosted instance.")
ws_url = _prompt("WS URL [wss://ws.revolt.chat]", allow_empty=True)
existing["REVOLT_WS_URL"] = ws_url or "wss://ws.revolt.chat"
print()
print("› Revolt / Stoat CDN URL (for avatars & attachments)")
print(" Press Enter to accept the default!")
print(" Only change this if you are using a self-hosted instance.")
print(" This is the URL of your Autumn (file server) instance.")
cdn_url = _prompt("CDN URL [https://autumn.revolt.chat]", allow_empty=True)
existing["REVOLT_CDN_URL"] = cdn_url or "https://autumn.revolt.chat"
print()
# ── 4. Write / update the .env file ─────────────────────────────────────
ENV_FILE.touch(exist_ok=True)
for key, value in existing.items():
set_key(str(ENV_FILE), key, value)
print(f" ✔ Configuration saved to {ENV_FILE.resolve()}")
print(f"{banner}\n")
# ── 5. Re-load so os.getenv() picks up the freshly written values ────────
load_dotenv(ENV_FILE, override=True)
interactive_env_setup()
# ──────────────────────────────────────────────────────────────────────────────
# CONFIGURATION
# ──────────────────────────────────────────────────────────────────────────────
DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN", "")
STOAT_BOT_TOKEN = os.getenv("STOAT_BOT_TOKEN", "")
_discord_raw = os.getenv("DISCORD_CHANNEL_IDS", "")
_stoat_raw = os.getenv("STOAT_CHANNEL_IDS", "")
DISCORD_CHANNEL_IDS: list[int] = [int(x.strip()) for x in _discord_raw.split(",") if x.strip()]
STOAT_CHANNEL_IDS: list[str] = [x.strip() for x in _stoat_raw.split(",") if x.strip()]
REVOLT_API_URL = os.getenv("REVOLT_API_URL", "https://api.revolt.chat").rstrip("/")
REVOLT_WS_URL = os.getenv("REVOLT_WS_URL", "wss://ws.revolt.chat").rstrip("/")
REVOLT_CDN_URL = os.getenv("REVOLT_CDN_URL", "https://autumn.revolt.chat").rstrip("/")
if len(DISCORD_CHANNEL_IDS) != len(STOAT_CHANNEL_IDS):
raise RuntimeError(
f"Channel list length mismatch: "
f"{len(DISCORD_CHANNEL_IDS)} Discord IDs vs {len(STOAT_CHANNEL_IDS)} Stoat IDs."
)
PAIR_COUNT = len(DISCORD_CHANNEL_IDS)
# ── Per-pair bridge direction ─────────────────────────────────────────────────
# "bi" → bidirectional (default)
# "discord" → Discord → Stoat only
# "stoat" → Stoat → Discord only
_directions_raw = os.getenv("CHANNEL_DIRECTIONS", "")
CHANNEL_DIRECTIONS: list[str] = [x.strip() for x in _directions_raw.split(",") if x.strip()]
if len(CHANNEL_DIRECTIONS) != PAIR_COUNT:
# Backward-compat: if key is missing, treat every pair as bidirectional.
CHANNEL_DIRECTIONS = ["bi"] * PAIR_COUNT
STOAT_TO_DISCORD: dict[str, int] = {
s: d
for d, s, dir_ in zip(DISCORD_CHANNEL_IDS, STOAT_CHANNEL_IDS, CHANNEL_DIRECTIONS)
if dir_ in ("bi", "stoat")
}
DISCORD_TO_STOAT: dict[int, str] = {
d: s
for d, s, dir_ in zip(DISCORD_CHANNEL_IDS, STOAT_CHANNEL_IDS, CHANNEL_DIRECTIONS)
if dir_ in ("bi", "discord")
}
# ──────────────────────────────────────────────────────────────────────────────
# WELCOME DM TOGGLE
# ──────────────────────────────────────────────────────────────────────────────
SEND_WELCOME_DMS = True # Set to False to disable welcome DMs on both Discord and Stoat.
# 25MB file size limit due to discord's restrictions
MAX_FILE_SIZE = 25 * 1024 * 1024
# The amount of messages that are being stored in cache for reply support
MSG_CACHE_SIZE = 500
# ──────────────────────────────────────────────────────────────────────────────
# LOGGING - SET YOUR LOGGING LEVEL HERE
# ──────────────────────────────────────────────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("bridge")
# ──────────────────────────────────────────────────────────────────────────────
# FIRST-TIME USER NOTIFICATION (persisted to JSON)
# ──────────────────────────────────────────────────────────────────────────────
NOTIFIED_USERS_FILE = ENV_FILE.parent / "notified_users.json"
_notified_users: dict[str, list[str]] = {"discord": [], "stoat": []}
def _load_notified_users() -> None:
global _notified_users
if NOTIFIED_USERS_FILE.exists():
try:
with NOTIFIED_USERS_FILE.open("r", encoding="utf-8") as f:
data = json.load(f)
_notified_users["discord"] = list(data.get("discord", []))
_notified_users["stoat"] = list(data.get("stoat", []))
logger.info(
f"Loaded {len(_notified_users['discord'])} Discord "
f"and {len(_notified_users['stoat'])} Stoat notified users."
)
except Exception as exc:
logger.error(f"Could not load {NOTIFIED_USERS_FILE}: {exc}")
def _save_notified_users() -> None:
try:
with NOTIFIED_USERS_FILE.open("w", encoding="utf-8") as f:
json.dump(_notified_users, f, indent=2)
except Exception as exc:
logger.error(f"Could not save {NOTIFIED_USERS_FILE}: {exc}")
def _is_notified(platform: str, uid: str) -> bool:
return uid in _notified_users[platform]
def _mark_notified(platform: str, uid: str) -> None:
if uid not in _notified_users[platform]:
_notified_users[platform].append(uid)
_save_notified_users()
# DM texts ─────────────────────────────────────────────────────────────────────
DISCORD_WELCOME_DM = """\
👋 **Hey! You just used the Stoat↔Discord Bridge Bot.**
This bot connects a Discord channel to a channel on **Stoat** (https://stoat.chat), \
forwarding messages between both platforms in real time.
**What happens to your messages?**
• Your **display name** and **profile picture** are shown on the other platform.
• The **content** of your messages (text and attachments) is transferred to the other platform.
• Attachments are briefly buffered in the bot's memory for forwarding and discarded immediately afterwards.
• **No** messages are stored permanently on the bot's server.
**Deletion:**
If you delete a message, it will automatically be deleted on the other platform as well.
If you don't want to use the bridge / your messages to be transfered, simply stop writing in the bridged channel — \
your messages will not be forwarded.
"""
STOAT_WELCOME_DM = """\
👋 **Hey! You just used the Stoat↔Discord Bridge Bot.**
This bot connects a Stoat channel to a channel on **Discord** (https://discord.gg), \
forwarding messages between both platforms in real time.
**What happens to your messages?**
• Your **display name** and **profile picture** are shown on the other platform.
• The **content** of your messages (text and attachments) is transferred to the other platform.
• Attachments are briefly buffered in the bot's memory for forwarding and discarded immediately afterwards.
• **No** messages are stored permanently on the bot's server.
**Deletion:**
If you delete a message, it will automatically be deleted on the other platform as well.
If you don't want to use the bridge / your messages to be transfered, simply stop writing in the bridged channel — \
your messages will not be forwarded.
"""
# ──────────────────────────────────────────────────────────────────────────────
# SHARED STATE
# ──────────────────────────────────────────────────────────────────────────────
discord_webhooks: dict[int, discord.Webhook] = {}
stoat_channels: dict[str, object] = {}
_d2s: OrderedDict[int, str] = OrderedDict() # discord_msg_id → stoat_msg_id
_s2d: OrderedDict[str, int] = OrderedDict() # stoat_msg_id → discord_msg_id
# Used in on_message_delete to choose the right deletion method.
_webhook_discord_ids: set[int] = set()
# used to break deletion loops.
_discord_deleting: set[int] = set() # discord msg IDs
_stoat_deleting: set[str] = set() # stoat msg IDs
def _cache_pair(discord_id: int, stoat_id: str, *, from_webhook: bool = False) -> None:
for cache, key, val in ((_d2s, discord_id, stoat_id), (_s2d, stoat_id, discord_id)):
if key in cache:
cache.move_to_end(key)
cache[key] = val
if len(cache) > MSG_CACHE_SIZE:
cache.popitem(last=False)
if from_webhook:
_webhook_discord_ids.add(discord_id)
def _extract_id(obj) -> str | None:
"""Pull an ID string from a raw dict, object, or plain string."""
if obj is None:
return None
if isinstance(obj, str):
return obj or None
if isinstance(obj, dict):
v = obj.get("_id") or obj.get("id")
return str(v) if v else None
v = getattr(obj, "_id", None) or getattr(obj, "id", None)
return str(v) if v else None
def _stoat_asset_url(asset) -> str | None:
if asset is None:
return None
asset_id = getattr(asset, "_id", None) or getattr(asset, "id", None)
tag = getattr(asset, "tag", None)
if asset_id and tag:
return f"{REVOLT_CDN_URL}/{tag}/{asset_id}"
# Fallback: use whatever the library returns
url_attr = getattr(asset, "url", None)
try:
return url_attr() if callable(url_attr) else str(url_attr)
except Exception:
return None
# ──────────────────────────────────────────────────────────────────────────────
# FILE HELPERS (Stoat → Discord direction only)
# ──────────────────────────────────────────────────────────────────────────────
async def fetch_bytes(session: aiohttp.ClientSession, url: str) -> tuple[bytes, str] | None:
"""Download url into RAM. Returns (data, filename) or None on any error."""
try:
async with session.get(url) as resp:
if resp.status != 200:
logger.warning(f"File fetch {url} -> HTTP {resp.status}")
return None
cl = resp.headers.get("Content-Length")
if cl and int(cl) > MAX_FILE_SIZE:
logger.warning(f"Skipping oversized file ({cl} B): {url}")
return None
data = await resp.read()
if len(data) > MAX_FILE_SIZE:
logger.warning(f"Skipping oversized file ({len(data)} B) after download")
return None
filename = url.split("?")[0].rstrip("/").rsplit("/", 1)[-1] or "file"
return data, filename
except Exception as exc:
logger.error(f"File fetch error for {url}: {exc}")
return None
# ──────────────────────────────────────────────────────────────────────────────
# REVOLT MESSAGE FETCH (for reply quotes)
# ──────────────────────────────────────────────────────────────────────────────
async def fetch_stoat_message(
channel_id: str,
message_id: str,
stoat_client: "StoatBot",
) -> SimpleNamespace | None:
def _build(raw: dict) -> SimpleNamespace:
masquerade = raw.get("masquerade") or {}
display_name = (
masquerade.get("name")
or _nested_get(raw, "author", "display_name")
or _nested_get(raw, "author", "username")
or "unknown"
)
return SimpleNamespace(
content=raw.get("content") or "",
author=SimpleNamespace(display_name=display_name),
)
def _nested_get(d, *keys):
cur = d
for k in keys:
if not isinstance(cur, dict):
return None
cur = cur.get(k)
return cur
ch = stoat_channels.get(channel_id)
if ch is not None:
for attr in ("fetch_message", "get_message"):
method = getattr(ch, attr, None)
if not method:
continue
try:
result = await method(message_id)
if result is None:
continue
if not isinstance(result, dict):
masq = getattr(result, "masquerade", None)
masq_name = (
masq.get("name") if isinstance(masq, dict)
else getattr(masq, "name", None)
) if masq else None
author = getattr(result, "author", None)
display_name = (
masq_name
or getattr(author, "display_name", None)
or getattr(author, "name", None)
or "unknown"
)
return SimpleNamespace(
content=getattr(result, "content", "") or "",
author=SimpleNamespace(display_name=display_name),
)
return _build(result)
except Exception as exc:
logger.debug(f"fetch_stoat_message via ch.{attr}: {exc}")
http = getattr(stoat_client, "http", None)
if http is not None:
request_fn = getattr(http, "request", None)
if request_fn:
try:
data = await request_fn("GET", f"/channels/{channel_id}/messages/{message_id}")
if isinstance(data, dict):
return _build(data)
except Exception as exc:
logger.debug(f"fetch_stoat_message via http.request: {exc}")
logger.warning(f"fetch_stoat_message: could not fetch {channel_id}/{message_id}")
return None
# ──────────────────────────────────────────────────────────────────────────────
# STOAT MESSAGE DELETION HELPER
# ──────────────────────────────────────────────────────────────────────────────
async def delete_stoat_message(channel_id: str, message_id: str, stoat_client: "StoatBot") -> bool:
"""Delete a message on Stoat via direct REST call with the bot token."""
session = stoat_client._http_session
if session is None:
logger.warning("delete_stoat_message: HTTP session not ready")
return False
try:
async with session.delete(
f"{REVOLT_API_URL}/channels/{channel_id}/messages/{message_id}",
headers={"x-bot-token": STOAT_BOT_TOKEN},
) as resp:
if resp.status in (200, 204):
return True
body = await resp.text()
logger.warning(
f"delete_stoat_message: HTTP {resp.status} for "
f"{channel_id}/{message_id} – {body[:200]}"
)
return False
except Exception as exc:
logger.error(f"delete_stoat_message: {channel_id}/{message_id}: {exc}")
return False
# ──────────────────────────────────────────────────────────────────────────────
# MENTION / EMOJI HELPERS
# ──────────────────────────────────────────────────────────────────────────────
_RE_DISCORD_USER = re.compile(r"<@!?(\d+)>")
_RE_DISCORD_CHANNEL = re.compile(r"<#(\d+)>")
_RE_DISCORD_ROLE = re.compile(r"<@&(\d+)>")
_RE_DISCORD_EMOJI = re.compile(r"<a?:([A-Za-z0-9_]+):\d+>")
_RE_REVOLT_USER = re.compile(r"<@([A-Z0-9]{26})>")
_RE_REVOLT_CUSTOM_EMO = re.compile(r":([A-Z0-9]{26}):")
_emoji_name_cache: dict[str, str] = {}
async def resolve_revolt_emoji(emoji_id: str, session: aiohttp.ClientSession, token: str) -> str:
if emoji_id in _emoji_name_cache:
return _emoji_name_cache[emoji_id]
try:
async with session.get(
f"{REVOLT_API_URL}/custom/emoji/{emoji_id}",
headers={"x-bot-token": token},
) as resp:
if resp.status == 200:
data = await resp.json()
name = data.get("name") or emoji_id
_emoji_name_cache[emoji_id] = name
return name
except Exception as exc:
logger.debug(f"Could not resolve Stoat emoji {emoji_id}: {exc}")
return emoji_id
async def clean_discord_content(content: str, message: discord.Message) -> str:
"""Resolve Discord markup to plain text before forwarding to Stoat."""
guild = message.guild
result = content
for m in reversed(list(_RE_DISCORD_USER.finditer(result))):
uid = int(m.group(1))
name = f"@user{uid}"
if guild:
member = guild.get_member(uid)
if member is None:
try:
member = await guild.fetch_member(uid)
except Exception:
member = None
if member:
name = f"@{member.display_name}"
result = result[: m.start()] + name + result[m.end() :]
def _channel(m: re.Match) -> str:
ch = guild.get_channel(int(m.group(1))) if guild else None
return f"#{ch.name}" if ch else "#channel"
result = _RE_DISCORD_CHANNEL.sub(_channel, result)
def _role(m: re.Match) -> str:
role = guild.get_role(int(m.group(1))) if guild else None
return f"@{role.name}" if role else "@role"
result = _RE_DISCORD_ROLE.sub(_role, result)
result = _RE_DISCORD_EMOJI.sub(lambda m: f":{m.group(1)}:", result)
return result
async def clean_stoat_content(
content: str,
session: aiohttp.ClientSession,
token: str,
) -> str:
"""Resolve Stoat markup to plain text before forwarding to Discord."""
result = content
for m in reversed(list(_RE_REVOLT_USER.finditer(result))):
uid = m.group(1)
name = "@user"
try:
async with session.get(
f"{REVOLT_API_URL}/users/{uid}",
headers={"x-bot-token": token},
) as resp:
if resp.status == 200:
data = await resp.json()
name = "@" + (data.get("display_name") or data.get("username") or uid)
except Exception as exc:
logger.debug(f"Could not resolve Revolt user {uid}: {exc}")
result = result[: m.start()] + name + result[m.end() :]
matches = list(_RE_REVOLT_CUSTOM_EMO.finditer(result))
if matches:
names = await asyncio.gather(
*[resolve_revolt_emoji(m.group(1), session, token) for m in matches]
)
for m, name in zip(reversed(matches), reversed(names)):
result = result[: m.start()] + f":{name}:" + result[m.end() :]
return result
# ──────────────────────────────────────────────────────────────────────────────
# STOAT BOT
# ──────────────────────────────────────────────────────────────────────────────
class StoatBot(stoat.Client):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._http_session: aiohttp.ClientSession | None = None
self._discord_bot: "DiscordBot | None" = None # set in main()
self._healthpulse: bool = False
self._health_msg_id: str | None = None
async def on_ready(self, event, /):
if self._http_session and not self._http_session.closed:
await self._http_session.close()
self._http_session = aiohttp.ClientSession()
logger.info(f"Stoat: on_ready fired as {self.me} – running health check…")
stoat_channels.clear()
for stoat_id in STOAT_CHANNEL_IDS:
try:
ch = await self.fetch_channel(stoat_id)
stoat_channels[stoat_id] = ch
except Exception as exc:
logger.error(f"Stoat: could not fetch channel {stoat_id} - {exc}")
await self._run_health_check()
async def _run_health_check(self) -> None:
"""
This is due to problems in stoat's API
Send a message into stoat channel
If on_message triggers: Succesfull, message deleted again
If on_message doesnt trigger: Not successfull, restart and message deleted
"""
if not STOAT_CHANNEL_IDS:
logger.warning("Stoat: health check skipped – no channels configured")
self._log_channels_ready()
return
first_id = STOAT_CHANNEL_IDS[0]
ch = stoat_channels.get(first_id)
if ch is None:
logger.warning("Stoat: health check skipped – channel not fetched")
return
self._healthpulse = False
self._health_msg_id = None
try:
sent = await ch.send(content="🔧")
self._health_msg_id = _extract_id(sent)
logger.info("Stoat: health check message sent, waiting 5s…")
except Exception as exc:
logger.error(f"Stoat: health check send failed: {exc} - restarting")
self._do_restart()
return
await asyncio.sleep(5)
# Always delete the test message — regardless of outcome
if self._health_msg_id:
await self._delete_health_message(first_id, self._health_msg_id)
self._health_msg_id = None
if self._healthpulse:
logger.info("Stoat: ✓ health check passed")
self._log_channels_ready()
else:
logger.error(
"Stoat: ✗ health check FAILED"
"Restarting process…"
)
self._do_restart()
async def _delete_health_message(self, channel_id: str, message_id: str) -> None:
if self._http_session is None or self._http_session.closed:
return
try:
async with self._http_session.delete(
f"{REVOLT_API_URL}/channels/{channel_id}/messages/{message_id}",
headers={"x-bot-token": STOAT_BOT_TOKEN},
) as resp:
if resp.status in (200, 204):
logger.debug("Stoat: health check message deleted")
else:
logger.debug(f"Stoat: health message delete returned HTTP {resp.status}")
except Exception as exc:
logger.debug(f"Stoat: could not delete health message: {exc}")
def _log_channels_ready(self) -> None:
for stoat_id, ch in stoat_channels.items():
logger.info(f"Stoat: ✓ listening in #{ch.name} (id={stoat_id})")
def _do_restart(self) -> None:
logger.warning("Stoat: performing full process restart…")
os.execv(sys.executable, [sys.executable] + sys.argv)
async def on_error(self, event, /):
logger.error(f"Stoat: ⚠ Error event from gateway: {event!r}")
# ── Send a DM on Stoat ────────────────────────────────────────────────────
async def _try_send_stoat_dm(self, user_id: str) -> None:
"""Send a welcome DM to a Stoat user."""
session = self._http_session
if session is None:
return
try:
# Open (or fetch existing) DM channel with the user
async with session.get(
f"{REVOLT_API_URL}/users/{user_id}/dm",
headers={"x-bot-token": STOAT_BOT_TOKEN},
) as resp:
if resp.status != 200:
logger.debug(f"Stoat: open DM channel failed for {user_id}: HTTP {resp.status}")
return
dm_data = await resp.json()
dm_channel_id = dm_data.get("_id") or dm_data.get("id")
if not dm_channel_id:
logger.debug(f"Stoat: no channel ID in DM response for {user_id}")
return
# Send the welcome message into the DM channel
async with session.post(
f"{REVOLT_API_URL}/channels/{dm_channel_id}/messages",
headers={"x-bot-token": STOAT_BOT_TOKEN},
json={"content": STOAT_WELCOME_DM[:2000]},
) as resp:
if resp.status in (200, 201):
logger.info(f"Stoat: sent welcome DM to user {user_id}")
else:
body = await resp.text()
logger.debug(f"Stoat: DM send failed for {user_id}: HTTP {resp.status} – {body[:200]}")
except Exception as exc:
logger.debug(f"Stoat: could not DM user {user_id}: {exc}")
async def on_message_create(self, event: stoat.MessageCreateEvent, /):
msg = event.message
if msg.author_id == self.me.id:
self._healthpulse = True # health check: own message received
return
stoat_id = msg.channel.id
if stoat_id not in STOAT_TO_DISCORD:
return
# ── First-time DM ─────────────────────────────────────────────────────
uid = str(msg.author_id)
if SEND_WELCOME_DMS and not _is_notified("stoat", uid):
_mark_notified("stoat", uid)
asyncio.create_task(self._try_send_stoat_dm(uid))
discord_id = STOAT_TO_DISCORD[stoat_id]
webhook = discord_webhooks.get(discord_id)
if webhook is None:
logger.warning(f"Stoat -> Discord: webhook for {discord_id} not ready, dropped")
return
# ── Clean content ─────────────────────────────────────────────────────
content = await clean_stoat_content(
msg.content or "", self._http_session, STOAT_BOT_TOKEN
)
# ── Reply → quote fallback ────────────────────────────────────────────
replies_raw = getattr(msg, "replies", None) or []
reply_id: str | None = None
if replies_raw:
first = replies_raw[0]
reply_id = _extract_id(first) or (str(first) if isinstance(first, str) else None)
if reply_id:
orig = await fetch_stoat_message(stoat_id, reply_id, self)
if orig is not None:
orig_author = orig.author.display_name[:50]
orig_snippet = (orig.content or "")[:80].replace("\n", " ")
content = f"-# ↩ **{orig_author}**: *{orig_snippet}*\n{content}"
else:
logger.warning(f"Stoat -> Discord: could not fetch reply target '{reply_id}'")
# ── Attachments ───────────────────────────────────────────────────────
discord_files: list[discord.File] = []
for att in getattr(msg, "attachments", None) or []:
url = _stoat_asset_url(att)
filename = getattr(att, "filename", None) or "file"
if not url:
continue
result = await fetch_bytes(self._http_session, url)
if result is None:
content += f"\n{url}"
continue
data, fname = result
discord_files.append(discord.File(io.BytesIO(data), filename=filename or fname))
del data
if not content.strip() and not discord_files:
return
author_name = (
getattr(msg.author, "display_name", None)
or getattr(msg.author, "name", None)
or "unknown"
)[:80]
avatar_url = _stoat_asset_url(getattr(msg.author, "avatar", None))
try:
sent = await webhook.send(
content = content[:2000] if content.strip() else discord.utils.MISSING,
username = author_name,
avatar_url = avatar_url,
files = discord_files or discord.utils.MISSING,
wait = True,
)
_cache_pair(sent.id, str(msg.id), from_webhook=True)
logger.debug(f"Stoat -> Discord: ✓ forwarded message from {author_name}")
except Exception as exc:
logger.error(f"Stoat -> Discord (channel {discord_id}): {exc}")
finally:
for f in discord_files:
f.fp.close()
# ── Message deletion: Stoat → delete on Discord ───────────────────────────
async def on_message_delete(self, event, /):
"""When a Stoat message is deleted, remove the mirrored Discord message."""
try:
msg_id = _extract_id(getattr(event, "message_id", None) or getattr(event, "id", None))
channel_id = _extract_id(getattr(event, "channel_id", None))
if msg_id is None:
# Some library versions give us the full message object
msg_obj = getattr(event, "message", None)
msg_id = _extract_id(msg_obj)
channel_id = channel_id or _extract_id(getattr(msg_obj, "channel", None))
if msg_id is None:
return
# Loop-break: if we triggered this deletion ourselves, ignore it.
if msg_id in _stoat_deleting:
_stoat_deleting.discard(msg_id)
return
discord_msg_id = _s2d.get(str(msg_id))
if discord_msg_id is None:
return # Not a bridged message
# Resolve the Discord channel ID
stoat_ch_id = channel_id or next(
(s for s, d in STOAT_TO_DISCORD.items() if d in discord_webhooks), None
)
discord_ch_id = STOAT_TO_DISCORD.get(stoat_ch_id) if stoat_ch_id else None
_discord_deleting.add(discord_msg_id)
# ── Case 1: message was originally sent via webhook (Stoat→Discord) ──
if discord_msg_id in _webhook_discord_ids:
webhook = discord_webhooks.get(discord_ch_id) if discord_ch_id else None
if webhook is None:
# Fall back: try every webhook
for _, wh in discord_webhooks.items():
try:
await wh.delete_message(discord_msg_id)
_webhook_discord_ids.discard(discord_msg_id)
return
except discord.NotFound:
_discord_deleting.discard(discord_msg_id)
return
except Exception:
pass
_discord_deleting.discard(discord_msg_id)
return
try:
await webhook.delete_message(discord_msg_id)
_webhook_discord_ids.discard(discord_msg_id)
except discord.NotFound:
_discord_deleting.discard(discord_msg_id)
logger.debug(f"Discord webhook message {discord_msg_id} already gone")
except Exception as exc:
_discord_deleting.discard(discord_msg_id)
logger.error(f"Stoat -> Discord: could not delete webhook msg {discord_msg_id}: {exc}")
# ── Case 2: message was originally sent by a Discord user (Discord→Stoat) ──
else:
if self._discord_bot is None or discord_ch_id is None:
logger.warning(
"Stoat -> Discord: cannot delete user message – "
"discord_bot reference or channel ID missing"