Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
3146 lines (2873 loc) · 124 KB
/
Copy pathmain.py
File metadata and controls
3146 lines (2873 loc) · 124 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
import logging
import asyncio
from discord.ext import commands, tasks
from discord import app_commands, ui
from typing import Optional
import discord
import re
import os
from dotenv import load_dotenv
import itertools
import aiosqlite
import sqlite3
import time
import ast
from collections import deque
from dataclasses import dataclass, replace
from translations import get_text, LANGUAGE_NAMES, TRANSLATION_LANGUAGE_NAMES, TRANSLATIONS
from link_utils import build_automatic_url, build_fixembed_url, chunk_lines, extract_supported_links
from instagram_embed import fetch_instagram_delivery
from twitter_embed import build_twitter_layout, fetch_twitter_payload
from reddit_embed import (
fetch_reddit_layout,
keeps_native_reddit_og_on_failure,
)
from threads_embed import fetch_threads_layout
from bluesky_embed import fetch_bluesky_layout
from pixiv_embed import fetch_pixiv_layout
from pixiv_relay import start_pixiv_relay
from bilibili_embed import fetch_bilibili_layout
from youtube_embed import fetch_youtube_community_layout
from pinterest_embed import fetch_pinterest_layout
from tiktok_embed import fetch_tiktok_layout
from tumblr_embed import fetch_tumblr_layout
from twitch_embed import fetch_twitch_layout
from deviantart_embed import fetch_deviantart_layout
from embed_footer import FooterBranding, escape_component_text
from card_preferences import preferences_from_settings
from content_visibility import (
channel_visibility_override,
init_content_visibility,
is_nsfw_channel,
load_channel_visibility_overrides,
resolve_content_visibility,
set_channel_visibility_override,
)
from premium_controls import (
fetch_analytics_summary,
init_premium_controls,
load_premium_controls,
record_processing_outcome,
resolve_translation_language,
save_premium_controls,
should_skip_automatic,
)
from premium_activation import (
evaluate_activation_checklist,
checklist_settings_targets,
format_checklist_row,
)
from message_context import format_tagged_users, no_mentions, sender_allowed_mentions
from command_components import render_command_layout, render_settings_layout
from install_links import build_install_controls
from onboarding import send_onboarding_dm
from settings_migrations import (
migrate_new_social_services_default,
migrate_pinterest_service_default,
migrate_youtube_service_default,
)
from reliability import (
ReliabilityClient,
ReliabilityReport,
format_reliability_status,
probe_deviantart_bot_health,
)
from conversion_telemetry import (
ConversionTelemetry,
format_local_conversion_health,
new_request_id,
)
from delivery_telemetry import (
DeliveryTelemetry,
deliver_with_fallback,
format_delivery_health,
)
from delivery_policy import (
apply_source_message_action,
format_delivery_mode_status,
resolve_delivery_mode,
should_apply_source_message_action,
)
from premium_cache import (
PREMIUM_CHECK_TIMEOUT_SECONDS,
PremiumStatusCache,
record_guild_premium,
resolve_guild_premium_status,
)
from premium_roles import (
entitlement_is_active,
reconcile_supporter_roles,
sync_supporter_role,
sync_supporter_role_for_member,
)
# Version number
VERSION = "1.6.0"
@dataclass(frozen=True)
class ComponentsV2Delivery:
view: discord.ui.LayoutView
fallback_url: str
files: tuple[discord.File, ...] = ()
# Service configuration for link processing
# All services now use the unified FixEmbed service at fixembed.app
SERVICES = {
"Twitter": {
"patterns": [r"twitter\.com/(\w+)/status/(\d+)", r"x\.com/(\w+)/status/(\d+)"],
"base_url": "fixembed.app",
"display_format": "Twitter • {0}"
},
"Instagram": {
"patterns": [r"instagram\.com/(?:p|reels?)/([\w-]+)"],
"base_url": "fixembed.app",
"display_format": "Instagram • {0}"
},
"Reddit": {
"patterns": [r"(?:old\.)?reddit\.com/r/(\w+)/(?:s|comments)/\w+"],
"base_url": "fixembed.app",
"display_format": "Reddit • r/{0}"
},
"Threads": {
"patterns": [r"threads\.net/@([^/]+)/post/([\w-]+)"],
"base_url": "fixembed.app",
"display_format": "Threads • @{0}"
},
"Pixiv": {
"patterns": [r"pixiv\.net/(?:en/)?artworks/(\d+)"],
"base_url": "fixembed.app",
"display_format": "Pixiv • {0}"
},
"Bluesky": {
"patterns": [r"bskyx?\.app/profile/([^/]+)/post/([\w-]+)"],
"base_url": "fixembed.app",
"display_format": "Bluesky • {0}"
},
"Bilibili": {
"patterns": [r"bilibili\.com/video/([\w]+)", r"b23\.tv/([\w]+)"],
"base_url": "fixembed.app",
"display_format": "Bilibili • {0}"
},
"YouTube": {
"patterns": [r"youtube\.com/post/([\w-]+)"],
"base_url": "fixembed.app",
"display_format": "YouTube • Community Post"
},
"Pinterest": {
"patterns": [r"pinterest\.com/pin/[\w-]+", r"pin\.it/[\w-]+"],
"base_url": "fixembed.app",
"display_format": "Pinterest • {0}"
},
"TikTok": {
"patterns": [
r"tiktok\.com/@[\w.-]+/video/\d+",
r"(?:vm|vt)\.tiktok\.com/[\w-]+",
],
"base_url": "fixembed.app",
"display_format": "TikTok • {0}"
},
"Tumblr": {
"patterns": [
r"[\w-]+\.tumblr\.com/post/\d+",
r"tumblr\.com/[\w-]+/\d+",
],
"base_url": "fixembed.app",
"display_format": "Tumblr • {0}"
},
"Twitch": {
"patterns": [
r"(?:clips\.twitch\.tv/[\w-]+|twitch\.tv/[\w-]+/clip/[\w-]+)",
r"twitch\.tv/videos/\d+",
r"twitch\.tv/[\w-]+",
],
"base_url": "fixembed.app",
"display_format": "Twitch • {0}"
},
"DeviantArt": {
"patterns": [
r"deviantart\.com/[\w-]+/art/[\w-]+",
r"sta\.sh/[\w-]+",
],
"base_url": "fixembed.app",
"display_format": "DeviantArt • {0}",
},
}
SERVICE_NAMES = list(SERVICES.keys())
DEFAULT_ENABLED_SERVICES = SERVICE_NAMES.copy()
SERVICE_EMOJI_FALLBACKS = {
"Twitter": "🐦",
"Instagram": "📷",
"Reddit": "👽",
"Threads": "🧵",
"Pixiv": "🎨",
"Bluesky": "🦋",
"Bilibili": "📺",
"YouTube": "▶️",
"Pinterest": "📌",
"TikTok": "🎵",
"Tumblr": "🅣",
"Twitch": "🟣",
"DeviantArt": "🎨",
}
SERVICE_EMOJI_IDS = {
"YouTube": 1526267390592290926,
"Pixiv": 1526268469920792577,
"Threads": 1526267848924725399,
"Reddit": 1526267589808881684,
"Instagram": 1526267158793949435,
"Twitter": 1526268173589155921,
"Bluesky": 1526269663334502544,
"Bilibili": 1526271150739423304,
"Pinterest": 1526398381415731240,
"TikTok": 1527868616215629954,
"Tumblr": 1527868615393546400,
"Twitch": 1527868614269468852,
"DeviantArt": 1528150711089500180,
}
LANGUAGE_FLAG_EMOJIS = {
"en": "🇺🇸",
"es": "🇪🇸",
"pt": "🇧🇷",
"fr": "🇫🇷",
"de": "🇩🇪",
"ja": "🇯🇵",
"ko": "🇰🇷",
"zh": "🇨🇳",
}
def get_custom_service_emoji(guild: Optional[discord.Guild], service: str):
"""Return a custom emoji for a service (guild/client/id lookup), if available."""
candidates = (service.lower(), service.replace(" ", "").lower())
if guild is not None:
for candidate in candidates:
emoji = discord.utils.get(guild.emojis, name=candidate)
if emoji:
return emoji
# Fallback by hardcoded emoji IDs (supports cases where emojis are not in guild.emojis)
emoji_id = SERVICE_EMOJI_IDS.get(service)
if emoji_id:
if guild is not None:
emoji = guild.get_emoji(emoji_id)
if emoji:
return emoji
emoji = client.get_emoji(emoji_id)
if emoji:
return emoji
candidate_name = service.lower()
return discord.PartialEmoji(name=candidate_name, id=emoji_id)
return None
def get_service_select_emoji(guild: Optional[discord.Guild], service: str):
"""Emoji object/char for select options with fallback when custom emojis are missing."""
custom = get_custom_service_emoji(guild, service)
return custom or SERVICE_EMOJI_FALLBACKS.get(service, "🔗")
def get_service_display_icon(guild: Optional[discord.Guild], service: str) -> str:
"""String icon for embeds/text with fallback when custom emojis are missing."""
custom = get_custom_service_emoji(guild, service)
return str(custom) if custom else SERVICE_EMOJI_FALLBACKS.get(service, "🔗")
# Initialize logging
logging.basicConfig(level=logging.INFO)
# Bot configuration
intents = discord.Intents.default()
intents.message_content = True
client = commands.AutoShardedBot(
command_prefix=commands.when_mentioned,
intents=intents,
shard_count=10,
# Cards and link text carry third-party content (comment bodies, titles,
# captions, author names). Nothing the bot posts may ping by default.
allowed_mentions=no_mentions(),
)
# In-memory storage for channel states and settings
channel_states = {}
bot_settings = {}
channel_service_rules = {}
channel_visibility_overrides = {}
# Rate-limiting configuration
MESSAGE_LIMIT = 5
TIME_WINDOW = 1 # Time window in seconds
message_timestamps = deque()
SEND_QUEUE = asyncio.Queue()
processed_link_cache = {}
DEDUP_WINDOW_SECONDS = 10
reliability_client = ReliabilityClient(
local_checks=(probe_deviantart_bot_health,),
)
conversion_telemetry = ConversionTelemetry(supported_services=SERVICE_NAMES)
delivery_telemetry = DeliveryTelemetry()
async def rate_limited_send(
channel,
content=None,
embed=None,
files=None,
allowed_mentions=no_mentions(),
view=None,
fallback_content=None,
):
ticket = delivery_telemetry.queued("card" if view is not None else "link")
completion = asyncio.get_running_loop().create_future()
await SEND_QUEUE.put(
(
ticket,
completion,
channel,
content,
embed,
files,
allowed_mentions,
view,
fallback_content,
)
)
return await asyncio.shield(completion)
async def send_worker():
while True:
(
ticket,
completion,
channel,
content,
embed,
files,
allowed_mentions,
view,
fallback_content,
) = await SEND_QUEUE.get()
try:
current_time = time.time()
while message_timestamps and current_time - message_timestamps[0] >= TIME_WINDOW:
message_timestamps.popleft()
while len(message_timestamps) >= MESSAGE_LIMIT:
await asyncio.sleep(0.1)
current_time = time.time()
while message_timestamps and current_time - message_timestamps[0] >= TIME_WINDOW:
message_timestamps.popleft()
message_timestamps.append(time.time())
async def primary_send():
send_options = {
"content": content,
"embed": embed,
"allowed_mentions": allowed_mentions,
"view": view,
"silent": True,
}
if files:
send_options["files"] = list(files)
return await channel.send(**send_options)
async def fallback_send():
return await channel.send(
content=fallback_content,
allowed_mentions=allowed_mentions,
silent=True,
)
outcome = await deliver_with_fallback(
ticket,
telemetry=delivery_telemetry,
primary_send=primary_send,
fallback_send=fallback_send if fallback_content else None,
)
if not completion.done():
completion.set_result(outcome)
except asyncio.CancelledError:
if not completion.done():
completion.cancel()
raise
except Exception as error:
delivery_telemetry.failed(ticket, error)
if not completion.done():
completion.set_result("failed")
finally:
SEND_QUEUE.task_done()
# Premium SKU ID (loaded from .env at bottom of file)
PREMIUM_SKU_ID = None
SUPPORT_GUILD_ID = 1195810157112852540
SUPPORTER_ROLE_ID = 1195810157112852547
def get_guild_lang(guild_id):
"""Get the language setting for a guild, defaulting to English."""
if guild_id is None:
return "en"
return bot_settings.get(guild_id, {}).get("language", "en")
# Premium status per guild id, for every guild whether or not it has a
# bot_settings row. Entries use the premium_cache TTL helpers; bounded LRU.
premium_status_cache = PremiumStatusCache()
async def guild_premium_status(guild_id):
"""``active``, ``inactive``, or ``unconfirmed`` when Discord couldn't be
checked and nothing is cached. Only /premium and the settings screens use
the third answer (#101); message handling uses ``is_guild_premium``."""
if not PREMIUM_SKU_ID:
return "inactive"
async def fetch_entitlements():
guild = client.get_guild(guild_id)
if guild is None:
return None
return [e async for e in client.entitlements(guild=guild, skus=[discord.Object(id=int(PREMIUM_SKU_ID))])]
# Fresh cache hit (premium or not) skips Discord. Otherwise one lookup capped
# at PREMIUM_CHECK_TIMEOUT_SECONDS, falling back to the last cached value.
return await resolve_guild_premium_status(
premium_status_cache,
guild_id,
fetch_entitlements,
timeout=PREMIUM_CHECK_TIMEOUT_SECONDS,
)
async def is_guild_premium(guild_id):
"""Check if a guild has an active premium subscription."""
return await guild_premium_status(guild_id) == "active"
def get_footer_branding(guild, settings, premium):
"""Resolve persisted Premium branding against the current guild."""
if not premium or not settings.get("footer_branding_enabled", False):
return None
emoji = ""
emoji_id = settings.get("footer_emoji_id")
if emoji_id:
try:
guild_emoji = discord.utils.get(guild.emojis, id=int(emoji_id))
except (TypeError, ValueError):
guild_emoji = None
if guild_emoji is not None:
emoji = str(guild_emoji)
return FooterBranding(name=guild.name, emoji=emoji)
def get_premium_color(guild_id):
"""Get custom embed color for a premium guild, or None."""
color_hex = bot_settings.get(guild_id, {}).get("embed_color")
if color_hex:
try:
return discord.Color(int(color_hex.lstrip('#'), 16))
except (ValueError, AttributeError):
pass
return None
def get_guild_color(guild_id, default=None):
"""Get the guild's custom color if premium, otherwise return default."""
custom = get_premium_color(guild_id)
return custom if custom else (default or discord.Color.blurple())
def effective_content_visibility(guild_settings, channel):
"""Resolve the visibility policy for one Discord channel."""
override = channel_visibility_override(
channel_visibility_overrides,
channel,
)
return resolve_content_visibility(
guild_settings,
override,
channel_is_nsfw=is_nsfw_channel(channel),
)
class CommandInfoView(ui.LayoutView):
"""Static Components V2 card for public informational commands."""
def __init__(self, *, title, description, sections, accent_color, footer, controls=()):
super().__init__(timeout=180)
render_command_layout(
self,
title=title,
description=description,
sections=sections,
controls=controls,
accent_color=accent_color,
footer=footer,
)
async def init_db():
db = await aiosqlite.connect('fixembed_data.db')
await db.execute('''CREATE TABLE IF NOT EXISTS channel_states (channel_id INTEGER PRIMARY KEY, state BOOLEAN)''')
await db.commit()
await db.execute('''CREATE TABLE IF NOT EXISTS guild_settings (guild_id INTEGER PRIMARY KEY, enabled_services TEXT, mention_users BOOLEAN, delete_original BOOLEAN DEFAULT TRUE, language TEXT DEFAULT 'en', embed_color TEXT DEFAULT NULL, delivery_mode TEXT DEFAULT 'suppress', media_quality TEXT DEFAULT 'balanced', footer_branding_enabled BOOLEAN DEFAULT FALSE, footer_emoji_id INTEGER DEFAULT NULL, show_nsfw BOOLEAN DEFAULT FALSE, show_spoilers BOOLEAN DEFAULT FALSE)''')
await db.commit()
await db.execute('''CREATE TABLE IF NOT EXISTS channel_service_rules (guild_id INTEGER, channel_id INTEGER, service TEXT, action TEXT, PRIMARY KEY (guild_id, channel_id, service))''')
await db.commit()
try:
await db.execute('ALTER TABLE guild_settings ADD COLUMN mention_users BOOLEAN DEFAULT TRUE')
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute('ALTER TABLE guild_settings ADD COLUMN delete_original BOOLEAN DEFAULT TRUE')
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute("ALTER TABLE guild_settings ADD COLUMN language TEXT DEFAULT 'en'")
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute('ALTER TABLE guild_settings ADD COLUMN embed_color TEXT DEFAULT NULL')
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute("ALTER TABLE guild_settings ADD COLUMN delivery_mode TEXT DEFAULT 'suppress'")
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute("ALTER TABLE guild_settings ADD COLUMN media_quality TEXT DEFAULT 'balanced'")
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute("ALTER TABLE guild_settings ADD COLUMN footer_branding_enabled BOOLEAN DEFAULT FALSE")
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute("ALTER TABLE guild_settings ADD COLUMN footer_emoji_id INTEGER DEFAULT NULL")
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute("ALTER TABLE guild_settings ADD COLUMN show_nsfw BOOLEAN DEFAULT FALSE")
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
try:
await db.execute("ALTER TABLE guild_settings ADD COLUMN show_spoilers BOOLEAN DEFAULT FALSE")
await db.commit()
except sqlite3.OperationalError as e:
if 'duplicate column name' in str(e):
pass
else:
raise
return db
async def load_channel_states(db):
async with db.execute('SELECT channel_id, state FROM channel_states') as cursor:
async for row in cursor:
channel_states[row[0]] = row[1]
for guild in client.guilds:
for channel in guild.text_channels:
if channel.id not in channel_states:
channel_states[channel.id] = True
async def load_settings(db):
async with db.execute('SELECT guild_id, enabled_services, mention_users, delete_original, language, embed_color, delivery_mode, media_quality, footer_branding_enabled, footer_emoji_id, show_nsfw, show_spoilers FROM guild_settings') as cursor:
async for row in cursor:
guild_id = row[0]
enabled_services = row[1]
mention_users = row[2]
delete_original = row[3]
language = row[4] if len(row) > 4 else "en"
embed_color = row[5] if len(row) > 5 else None
delivery_mode = row[6] if len(row) > 6 else "suppress"
media_quality = row[7] if len(row) > 7 else "balanced"
footer_branding_enabled = row[8] if len(row) > 8 else False
footer_emoji_id = row[9] if len(row) > 9 else None
show_nsfw = row[10] if len(row) > 10 else False
show_spoilers = row[11] if len(row) > 11 else False
enabled_services_list = ast.literal_eval(enabled_services) if enabled_services else DEFAULT_ENABLED_SERVICES
bot_settings[guild_id] = {
"enabled_services": enabled_services_list,
"mention_users": mention_users if mention_users is not None else True,
"delete_original": delete_original if delete_original is not None else True,
"language": language if language else "en",
"embed_color": embed_color,
"delivery_mode": delivery_mode if delivery_mode else "suppress",
"media_quality": media_quality if media_quality else "balanced",
"footer_branding_enabled": bool(footer_branding_enabled),
"footer_emoji_id": footer_emoji_id,
"show_nsfw": bool(show_nsfw),
"show_spoilers": bool(show_spoilers),
}
async def update_channel_state(db, channel_id, state):
retries = 5
for i in range(retries):
try:
await db.execute('INSERT OR REPLACE INTO channel_states (channel_id, state) VALUES (?, ?)', (channel_id, state))
await db.commit()
break
except sqlite3.OperationalError as e:
if 'locked' in str(e):
await asyncio.sleep(0.1)
else:
raise
async def update_setting(
db,
guild_id,
enabled_services,
mention_users,
delete_original,
language="en",
embed_color=None,
delivery_mode="suppress",
media_quality="balanced",
footer_branding_enabled=False,
footer_emoji_id=None,
show_nsfw=False,
show_spoilers=False,
):
retries = 5
for i in range(retries):
try:
await db.execute(
'INSERT OR REPLACE INTO guild_settings (guild_id, enabled_services, mention_users, delete_original, language, embed_color, delivery_mode, media_quality, footer_branding_enabled, footer_emoji_id, show_nsfw, show_spoilers) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
(
guild_id,
repr(enabled_services),
mention_users,
delete_original,
language,
embed_color,
delivery_mode,
media_quality,
footer_branding_enabled,
footer_emoji_id,
show_nsfw,
show_spoilers,
),
)
await db.commit()
break
except sqlite3.OperationalError as e:
if 'locked' in str(e):
await asyncio.sleep(0.1)
else:
raise
async def load_channel_service_rules(db):
async with db.execute('SELECT guild_id, channel_id, service, action FROM channel_service_rules') as cursor:
async for guild_id, channel_id, service, action in cursor:
channel_service_rules[(guild_id, channel_id, service)] = action
async def set_channel_service_rule(db, guild_id, channel_id, service, action):
await db.execute('INSERT OR REPLACE INTO channel_service_rules (guild_id, channel_id, service, action) VALUES (?, ?, ?, ?)', (guild_id, channel_id, service, action))
await db.commit()
channel_service_rules[(guild_id, channel_id, service)] = action
def get_service_rule(guild_id, channel_id, service, default_enabled=True):
rule = channel_service_rules.get((guild_id, channel_id, service))
if rule == "on":
return True
if rule == "off":
return False
return default_enabled
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
logging.info(f'Logged in as {client.user}')
if (
os.getenv("PIXIV_RELAY_ENABLED") == "1"
and getattr(client, "pixiv_relay_runner", None) is None
):
try:
client.pixiv_relay_runner = await start_pixiv_relay()
except Exception as error:
logging.exception("Pixiv relay startup failed: %s", error)
client.db = await init_db()
await init_content_visibility(client.db)
await init_premium_controls(client.db)
await migrate_youtube_service_default(client.db)
await migrate_pinterest_service_default(client.db)
await migrate_new_social_services_default(client.db)
await load_channel_states(client.db)
await load_settings(client.db)
for guild_id, controls in (await load_premium_controls(client.db)).items():
bot_settings.setdefault(
guild_id,
{
"enabled_services": DEFAULT_ENABLED_SERVICES.copy(),
"mention_users": True,
"delete_original": True,
"language": "en",
"delivery_mode": "suppress",
"media_quality": "balanced",
},
).update(controls)
await load_channel_service_rules(client.db)
channel_visibility_overrides.update(
await load_channel_visibility_overrides(client.db)
)
if PREMIUM_SKU_ID:
try:
await reconcile_supporter_roles(
client,
int(PREMIUM_SKU_ID),
SUPPORT_GUILD_ID,
SUPPORTER_ROLE_ID,
)
except Exception as error:
logging.exception("Premium supporter role reconciliation failed: %s", error)
change_status.start()
client.loop.create_task(send_worker())
try:
synced = await client.tree.sync()
print(f'Synced {len(synced)} command(s)')
except Exception as e:
print(f'Failed to sync commands: {e}')
client.launch_time = discord.utils.utcnow()
statuses = itertools.cycle([
"for Twitter links", "for Reddit links", "for Instagram links", "for Threads links", "for Pixiv links", "for Bluesky links", "for Bilibili links", "for YouTube links", "for Pinterest links", "for TikTok links", "for Tumblr links", "for Twitch links"
])
@tasks.loop(seconds=60)
async def change_status():
current_status = next(statuses)
try:
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=current_status))
except discord.errors.HTTPException as e:
logging.error(f"Failed to change status: {e}")
async def build_components_v2_link(
item,
guild_settings,
footer_branding,
card_preferences,
*,
premium=False,
):
"""Build the same Components V2 card for automatic and command entry points."""
media_quality = guild_settings.get("media_quality", "balanced")
translated_item = with_translation_language(item, guild_settings)
translation_language = translated_item.language
automatic_url = build_automatic_url(
translated_item,
media_quality,
os.getenv("AUTO_TWITTER_PROVIDER", "fixembed"),
)
request_id = new_request_id()
files: tuple[discord.File, ...] = ()
async with conversion_telemetry.observe(item.service, request_id):
if item.service == "Instagram":
instagram_delivery = await fetch_instagram_delivery(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
layout = instagram_delivery.layout
files = instagram_delivery.files
elif item.service == "Twitter":
fixed_url = build_fixembed_url(translated_item, media_quality)
payload = await fetch_twitter_payload(
item.canonical_url,
translation_language,
item.mode,
)
layout = build_twitter_layout(
payload,
fixed_url,
footer_branding,
card_preferences,
)
elif item.service == "Reddit":
layout = await fetch_reddit_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "Threads":
layout = await fetch_threads_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "Pixiv":
layout = await fetch_pixiv_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "Bluesky":
layout = await fetch_bluesky_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "Bilibili":
layout = await fetch_bilibili_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "YouTube":
layout = await fetch_youtube_community_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "Pinterest":
layout = await fetch_pinterest_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "TikTok":
layout = await fetch_tiktok_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "Tumblr":
layout = await fetch_tumblr_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "Twitch":
layout = await fetch_twitch_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
elif item.service == "DeviantArt":
layout = await fetch_deviantart_layout(
item.canonical_url,
automatic_url,
footer_branding,
card_preferences,
translation_language=translation_language,
)
else:
raise ValueError("unsupported rich-card service")
return ComponentsV2Delivery(
view=layout,
fallback_url=automatic_url,
files=files,
)
def with_translation_language(item, guild_settings):
"""Apply an explicit or guild-default translation to every delivery path."""
return replace(
item,
language=resolve_translation_language(item.language, guild_settings),
)
async def send_components_v2_links(interaction, links):
"""Respond to a user command with modern cards and safe URL fallbacks."""
guild_id = interaction.guild.id if interaction.guild else None
guild_settings = bot_settings.get(
guild_id,
{
"enabled_services": DEFAULT_ENABLED_SERVICES,
"mention_users": True,
"delete_original": True,
"delivery_mode": "suppress",
"media_quality": "balanced",
},
)
premium = await is_guild_premium(guild_id) if guild_id is not None else False
footer_branding = get_footer_branding(interaction.guild, guild_settings, premium)
content_visibility = effective_content_visibility(
guild_settings,
interaction.channel,
)
card_preferences = preferences_from_settings(
guild_settings,
premium=premium,
content_visibility=content_visibility,
)
await interaction.response.defer()
for item in links:
translated_item = with_translation_language(item, guild_settings)
fallback_url = build_automatic_url(
translated_item,
guild_settings.get("media_quality", "balanced"),
os.getenv("AUTO_TWITTER_PROVIDER", "fixembed"),
)
try:
delivery = await build_components_v2_link(
item,
guild_settings,
footer_branding,
card_preferences,
premium=premium,
)
except Exception as error:
logging.warning(
"Components V2 command card failed for %s: %s",
item.service,
type(error).__name__,
)
# Real Reddit comment deletions arrive as a success:true tombstone
# payload and render above. An exception here means Reddit was
# unreachable, so fall back to the plain link like other services.
if keeps_native_reddit_og_on_failure(item.service, item.canonical_url):
logging.info(
"Reddit comment metadata unavailable; sending plain link (#71)"
)
await interaction.followup.send(fallback_url, allowed_mentions=no_mentions())
continue
try:
send_options = {"view": delivery.view, "allowed_mentions": no_mentions()}
if delivery.files:
send_options["files"] = list(delivery.files)
await interaction.followup.send(**send_options)
except discord.HTTPException as error: