-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbb.py
More file actions
4395 lines (3804 loc) · 174 KB
/
bb.py
File metadata and controls
4395 lines (3804 loc) · 174 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
# =========================================
# Miku Bot - Discord Server Manager
# Voice channels, moderation, AI chat, music, and more.
# MongoDB for persistence, per-guild settings.
# =========================================
from dotenv import load_dotenv
load_dotenv()
import discord
import datetime
import datetime as dt
from discord.ext import commands, tasks
import asyncio
import os
import logging
from datetime import timedelta, timezone
import random
import re
from collections import defaultdict, deque
import time
import requests
from urllib.parse import quote
import json
import ast
from typing import Optional
import aiohttp
import math
import platform
import psutil
import traceback
from io import BytesIO
import pytz
import yt_dlp
try:
from pymongo import MongoClient
except ImportError:
MongoClient = None
print("Warning: pymongo not installed. Database features will be disabled.")
try:
from countryinfo import CountryInfo
except ImportError:
CountryInfo = None
print("Warning: countryinfo not installed. Country to timezone features will be disabled.")
try:
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
except ImportError:
spotipy = None
SpotifyClientCredentials = None
# --- Spotify client initialization ---
# If Spotify credentials are set, initialize the Spotify API client
if spotipy and SpotifyClientCredentials:
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
client_id=os.getenv("SPOTIFY_CLIENT_ID"),
client_secret=os.getenv("SPOTIFY_CLIENT_SECRET")
))
else:
sp = None
pending_matches = {} # {guild_id: {message_id: author_id}}
# --- Per-Guild (Server) Settings Helper Functions ---
def get_guild_settings(guild_id):
"""Fetch settings for a specific Discord server (guild) from the database."""
if db is None:
return {}
settings = db.guild_settings.find_one({"guild_id": guild_id})
return settings or {}
def set_guild_setting(guild_id, key, value):
"""Set a specific setting for a Discord server (guild) in the database."""
if db is None:
return
db.guild_settings.update_one(
{"guild_id": guild_id},
{"$set": {key: value}},
upsert=True
)
def get_guild_timezone(guild_id):
"""Get the timezone for a guild, defaulting to UTC if not set."""
settings = get_guild_settings(guild_id)
return settings.get("timezone", "UTC") # Default to UTC
def localize_time(dt, guild_id):
"""Convert a datetime object to the guild's local timezone."""
tzname = get_guild_timezone(guild_id)
tz = pytz.timezone(tzname)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=pytz.utc)
return dt.astimezone(tz)
def update_weekly_chat_activity(guild_id, user_id):
if guild_id not in chat_activity_weekly:
chat_activity_weekly[guild_id] = {}
if user_id not in chat_activity_weekly[guild_id]:
chat_activity_weekly[guild_id][user_id] = [0] * 7
idx = datetime.datetime.utcnow().weekday()
chat_activity_weekly[guild_id][user_id][idx] += 1
# --- Conversation Start Time Tracking ---
# Used for tracking how long a conversation has been going in a server
conversation_start_times = {}
def get_conversation_start(guild_id):
"""Get the start time of the current conversation for a guild."""
if guild_id not in conversation_start_times:
conversation_start_times[guild_id] = discord.utils.utcnow().replace(tzinfo=pytz.utc)
return conversation_start_times[guild_id]
def get_conversation_duration(guild_id):
"""Get the duration of the current conversation for a guild."""
start = get_conversation_start(guild_id)
now = discord.utils.utcnow().replace(tzinfo=pytz.utc)
return now - start
# --- Welcome GIFs ---
WELCOME_GIFS = [
"https://media.tenor.com/2roX3uxz_68AAAAC/welcome.gif",
"https://media.giphy.com/media/OkJat1YNdoD3W/giphy.gif",
"https://media.giphy.com/media/hvRJCLFzcasrR4ia7z/giphy.gif",
"https://media.giphy.com/media/ASd0Ukj0y3qMM/giphy.gif",
"https://media.giphy.com/media/l0MYt5jPR6QX5pnqM/giphy.gif",
"https://media.giphy.com/media/3o6Zt481isNVuQI1l6/giphy.gif",
"https://media.giphy.com/media/xUPGcguWZHRC2HyBRS/giphy.gif",
"https://media.giphy.com/media/3o7aD2saalBwwftBIY/giphy.gif"
]
# --- Response Post-processing ---
def postprocess_response(text, recent_endings: Optional[list] = None):
"""
Clean up AI-generated responses:
- Remove repetitive endings or questions.
- Avoid always ending with a question.
"""
if not text:
return text
repetitive_endings = [
"What's on your mind?",
"Anything else?",
"Is there something you want to talk about?",
"Do you need something?",
"Can I help you with something?",
"How can I help you?",
"Let me know if you need anything.",
"What do you want?",
"What are you thinking?",
"What brings you here?",
"What do you need?",
"What do you want to do?",
"What do you want to ask?",
"What do you want to say?",
"What do you want from me?",
"What do you want now?",
"What do you want next?",
"What do you want to know?",
"What do you want to hear?",
"What do you want to see?",
"What do you want to tell me?",
"What do you want to share?",
"What do you want to discuss?",
"What do you want to talk about?",
"What do you want to try?",
"What do you want to experience?",
"What do you want to explore?",
"What do you want to learn?",
"What do you want to find out?",
"What do you want to discover?",
"What do you want to achieve?",
"What do you want to accomplish?",
"What do you want to create?",
"What do you want to build?",
"What do you want to make?",
"What do you want to improve?",
"What do you want to fix?",
"What do you want to change?",
"What do you want to add?",
"What do you want to remove?",
"What do you want to update?",
"What do you want to upgrade?",
"What do you want to replace?",
]
# Remove trailing whitespace and punctuation
text = text.rstrip()
# Remove if ends with a question or repetitive phrase
for ending in repetitive_endings:
if text.endswith(ending):
text = text[: -len(ending)].rstrip(" ,.-")
break
# Remove if ends with a question mark and is short
if text.endswith("?") and len(text.split()) < 15:
text = text.rstrip(" ?!.,-")
# Optionally, avoid repeating recent endings
if recent_endings:
for ending in recent_endings:
if text.endswith(ending):
text = text[: -len(ending)].rstrip(" ,.-")
break
return text
# --- Channel History Helper ---
async def get_recent_channel_history(channel: discord.TextChannel, bot_user: discord.User, current_message: discord.Message, limit: int = 20) -> list:
"""
Fetch the last N messages from a channel (excluding commands and bot messages),
for use as context in AI responses.
"""
history = []
try:
async for msg in channel.history(limit=limit, oldest_first=True):
if msg.id == current_message.id:
continue # skip current message
if msg.content.startswith("!"):
continue # skip commands
content = msg.content.strip()
if not content:
continue # skip empty/whitespace
if len(content) > 300:
content = content[:297] + "..." # truncate long messages
author = "bot" if msg.author == bot_user else msg.author.display_name
history.append((author, content))
except Exception as e:
logger.error(f"Error fetching channel history: {e}")
# Add the current message as the last entry
content = current_message.content.strip()
if content:
if len(content) > 300:
content = content[:297] + "..."
history.append((current_message.author.display_name, content))
return history
# --- Logging Setup ---
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
intents = discord.Intents.default()
intents.voice_states = True
intents.guilds = True
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
TEMPLATE_CHANNELS = {
"Duo": {
"id": 1391638961356668979,
"limit": 2
},
"Trio": {
"id": 1391639028356481025,
"limit": 3
},
"Squad": {
"id": 1391639129313509438,
"limit": 4
},
"Team": {
"id": 1391639106970320906,
"limit": 12
},
}
def get_template_channels(guild_id):
"""Get template channels for a guild, using per-guild settings if available."""
settings = get_guild_settings(guild_id)
return {
"Duo": {"id": settings.get("duo_channel_id", TEMPLATE_CHANNELS["Duo"]["id"]), "limit": 2},
"Trio": {"id": settings.get("trio_channel_id", TEMPLATE_CHANNELS["Trio"]["id"]), "limit": 3},
"Squad": {"id": settings.get("squad_channel_id", TEMPLATE_CHANNELS["Squad"]["id"]), "limit": 4},
"Team": {"id": settings.get("team_channel_id", TEMPLATE_CHANNELS["Team"]["id"]), "limit": 12},
}
# Welcome channel ID
WELCOME_CHANNEL_ID = 1391641782487617696
# AFK channel ID
AFK_CHANNEL_ID = 1364156990561194075
# AFK detection settings
AFK_TIMEOUT = 300 # 5 minutes in seconds
user_voice_activity = {} # Track when users last spoke/had activity
created_channels = {}
channel_stats = {"total_created": 0, "user_activity": {}}
# Gaming Features
voice_activity_today = {} # {guild_id: {user_id: ...}}
voice_activity_alltime = {} # {guild_id: {user_id: {"name": str, "total_time": float}}}
channel_themes = {
"🎮": {
"name": "Gaming",
"color": 0xff6b35
},
"📚": {
"name": "Study",
"color": 0x4287f5
},
"😎": {
"name": "Chill",
"color": 0x9c27b0
},
"🎵": {
"name": "Music",
"color": 0xe91e63
},
"💼": {
"name": "Work",
"color": 0x607d8b
}
}
# Auto-role thresholds
ROLE_THRESHOLDS = {
"Channel Creator": 5, # 5 channels created
"Voice Master": 15, # 15 channels created
"Community Leader": 30 # 30 channels created
}
# @everyone tag tracking
everyone_warnings = {}
# Vulgar GIFs and Images for Miku responses
MIKU_GIFS = [
"https://media.tenor.com/x8v1oNUOmg4AAAAC/the-rock-sus.gif",
"https://media.tenor.com/doIgKO-Q2RgAAAAC/angry-mad.gif",
"https://media.tenor.com/kc8PQ_2VrdQAAAAC/mad-angry.gif",
"https://media.tenor.com/VDGFc7gOHlMAAAAC/shut-up-anime.gif",
"https://media.tenor.com/2UZA_7FE1IEAAAAC/annoyed-whatever.gif",
"https://media.tenor.com/HJpNRqZL8UMAAAAC/middle-finger-rude.gif",
"https://media.tenor.com/GWEjOYBEGL8AAAAC/anime-angry.gif",
"https://media.tenor.com/y2JXkY1pXkwAAAAC/cat-computer.gif",
"https://media.tenor.com/jI8hdF_bHWsAAAAC/spongebob-mocking.gif",
"https://media.tenor.com/ZBn7wLwmJbQAAAAC/anime-girl-angry.gif",
"https://media.tenor.com/8rFQTeVU8TAAAAAC/angry-anime.gif",
"https://media.tenor.com/oDdkl8nJhwQAAAAC/eye-roll-here-we-go.gif",
"https://media.tenor.com/6bUqS8K-INAAAAAC/whatever-shrug.gif",
"https://media.tenor.com/9C3B4UHHwUwAAAAC/dismissive-unimpressed.gif",
"https://media.tenor.com/fY3cO8V8CjQAAAAC/anime-angry-face.gif",
"https://media.tenor.com/aHpwWJNSCWcAAAAC/no-nope.gif",
"https://media.tenor.com/4XKGc6HNOHwAAAAC/go-away-get-out.gif",
"https://media.tenor.com/4VcJ5WmjHBYAAAAC/annoyed-frustrated.gif",
"https://media.tenor.com/rXgQJj3h0wkAAAAC/rude-gesture.gif",
"https://media.tenor.com/IlK7lOorvYMAAAAC/middle-finger.gif",
"https://c.tenor.com/x8v1oNUOmg4AAAAC/the-rock-sus.gif",
"https://c.tenor.com/doIgKO-Q2RgAAAAC/angry-mad.gif",
"https://c.tenor.com/kc8PQ_2VrdQAAAAC/mad-angry.gif",
"https://c.tenor.com/VDGFc7gOHlMAAAAC/shut-up-anime.gif",
"https://c.tenor.com/2UZA_7FE1IEAAAAC/annoyed-whatever.gif",
"https://c.tenor.com/HJpNRqZL8UMAAAAC/middle-finger-rude.gif",
"https://c.tenor.com/GWEjOYBEGL8AAAAC/anime-angry.gif",
"https://c.tenor.com/y2JXkY1pXkwAAAAC/cat-computer.gif",
"https://c.tenor.com/jI8hdF_bHWsAAAAC/spongebob-mocking.gif",
"https://c.tenor.com/ZBn7wLwmJbQAAAAC/anime-girl-angry.gif"
]
# Vulgar GIFs and Images for HREI <3 responses
HREI_GIFS = [
"https://tenor.com/en-GB/view/dahliabunni-anime-heart-love-gif-22681191",
"https://tenor.com/en-GB/view/kagami-furi-heart-eyes-hearts-anime-cat-girl-gif-11488933993313748973",
"https://media.tenor.com/1oPZZDpHdu8AAAAi/chainsaw-man-makima.gif",
"https://c.tenor.com/O5XHNIahspwAAAAd/tenor.gif"
]
# Mention spam protection
MENTION_SPAM_THRESHOLD = 3 # mentions
MENTION_SPAM_WINDOW = 120 # seconds (2 minutes)
MENTION_TIMEOUT_DURATION = 600 # seconds (10 minutes)
mention_spam_tracker = defaultdict(lambda: deque(maxlen=MENTION_SPAM_THRESHOLD))
mention_spam_warnings = {}
# Add to the top of the file, after other globals
active_character_per_channel = defaultdict(lambda: "miku")
# Moderation settings
MODERATION_LOG_CHANNEL_ID = 1391641782487617696 # Change to your mod log channel
WARNINGS_DB = {} # Store user warnings
MUTE_ROLE_ID = None # Set this to your mute role ID
AUTO_MODERATION = {
"caps_threshold": 0.7, # 70% caps triggers warning
"spam_threshold": 5, # 5 messages in 10 seconds
"link_whitelist": [
"discord.com", "discord.gg", "youtube.com", "youtu.be",
"github.com", "github.io", "gitlab.com", "bitbucket.org",
"stackoverflow.com", "stackexchange.com", "reddit.com",
"twitter.com", "x.com", "facebook.com", "instagram.com",
"linkedin.com", "tiktok.com", "twitch.tv", "spotify.com",
"open.spotify.com", "soundcloud.com", "bandcamp.com",
"imgur.com", "giphy.com", "tenor.com", "media.tenor.com",
"c.tenor.com", "media.giphy.com", "media.tenor.com",
"wikipedia.org", "wikimedia.org", "medium.com", "dev.to",
"hashnode.dev", "substack.com", "patreon.com", "ko-fi.com",
"buymeacoffee.com", "paypal.com", "stripe.com",
"google.com", "googleusercontent.com", "drive.google.com",
"docs.google.com", "sheets.google.com", "slides.google.com",
"microsoft.com", "office.com", "onedrive.live.com",
"dropbox.com", "box.com", "mega.nz", "mediafire.com",
"pastebin.com", "hastebin.com", "rentry.co", "gist.github.com",
"replit.com", "glitch.com", "codesandbox.io", "jsfiddle.net",
"codepen.io", "jsbin.com", "plnkr.co", "fiddle.jshell.net",
"steam.com", "steampowered.com", "epicgames.com", "origin.com",
"battle.net", "playstation.com", "xbox.com", "nintendo.com",
"itch.io", "gamejolt.com", "indiedb.com", "moddb.com",
"nexusmods.com", "curseforge.com", "modrinth.com",
"minecraft.net", "mojang.com", "curse.com",
"amazon.com", "amazon.co.uk", "amazon.de", "amazon.fr",
"amazon.it", "amazon.es", "amazon.ca", "amazon.com.au",
"ebay.com", "etsy.com", "aliexpress.com", "wish.com",
"shopify.com", "woocommerce.com", "bigcommerce.com",
"wordpress.com", "blogspot.com", "tumblr.com", "livejournal.com",
"medium.com", "substack.com", "ghost.org", "squarespace.com",
"wix.com", "weebly.com", "webflow.com", "notion.so",
"obsidian.md", "roamresearch.com", "logseq.com",
"notion.so", "miro.com", "figma.com", "sketch.com",
"invisionapp.com", "marvelapp.com", "balsamiq.com",
"trello.com", "asana.com", "monday.com", "clickup.com",
"slack.com", "teams.microsoft.com", "zoom.us", "meet.google.com",
"webex.com", "gotomeeting.com", "bluejeans.com",
"udemy.com", "coursera.org", "edx.org", "khanacademy.org",
"skillshare.com", "pluralsight.com", "lynda.com",
"freecodecamp.org", "theodinproject.com", "fullstackopen.com",
"javascript.info", "reactjs.org", "vuejs.org", "angular.io",
"nodejs.org", "python.org", "docs.python.org", "pypi.org",
"rubygems.org", "npmjs.com", "yarnpkg.com", "composer.org",
"nuget.org", "maven.org", "gradle.org", "sbt.io",
"docker.com", "kubernetes.io", "helm.sh", "rancher.com",
"aws.amazon.com", "azure.microsoft.com", "cloud.google.com",
"digitalocean.com", "heroku.com", "vercel.com", "netlify.com",
"surge.sh", "firebase.google.com", "supabase.com",
"mongodb.com", "postgresql.org", "mysql.com", "sqlite.org",
"redis.io", "elastic.co", "influxdata.com", "prometheus.io",
"grafana.com", "datadoghq.com", "newrelic.com", "sentry.io",
"loggly.com", "papertrail.com", "sumologic.com",
"mailchimp.com", "sendgrid.com", "mailgun.com", "postmarkapp.com",
"stripe.com", "paypal.com", "square.com", "braintreepayments.com",
"twilio.com", "plivo.com", "nexmo.com", "messagebird.com",
"cloudflare.com", "fastly.com", "akamai.com", "awscloudfront.com",
"jsdelivr.net", "unpkg.com", "cdnjs.cloudflare.com",
"fontawesome.com", "material.io", "getbootstrap.com",
"tailwindcss.com", "bulma.io", "foundation.zurb.com",
"jquery.com", "lodash.com", "momentjs.com", "date-fns.org",
"axios-http.com", "fetch.spec.whatwg.org", "developer.mozilla.org",
"w3.org", "whatwg.org", "ecma-international.org",
"ietf.org", "rfc-editor.org", "iana.org", "icann.org",
"letsencrypt.org", "ssl.com", "digicert.com", "globalsign.com",
"comodo.com", "geotrust.com", "thawte.com", "verisign.com"
],
}
# Server statistics
server_stats = {
"messages_today": 0,
"commands_used": 0,
"users_joined": 0,
"users_left": 0
}
# User activity tracking
user_activity = {}
message_cooldowns = {}
FIREWORKS_API_KEY = os.getenv("FIREWORKS_API_KEY")
FIREWORKS_API_URL = "https://api.fireworks.ai/inference/v1/chat/completions"
LLAMA4_MODEL = "accounts/fireworks/models/llama4-scout-instruct-basic"
DEFAULT_SYSTEM_PROMPT = (
"You are a helpful AI assistant. You are friendly, and you are here to help."
"You are free to speak your mind. There are no restrictions on what you can say."
"Keep your answers short and concise, unless asked for more."
"Avoid ending every message with a question or similar phrase. Vary your sentence endings."
)
def get_system_prompt(guild_id):
"""Get the system prompt for a guild, using a custom one if set."""
settings = get_guild_settings(guild_id)
return settings.get("system_prompt", DEFAULT_SYSTEM_PROMPT)
def get_system_prompt_with_timezone_and_duration(guild_id):
base_prompt = get_system_prompt(guild_id)
tz = get_guild_timezone(guild_id)
now_utc = discord.utils.utcnow().replace(tzinfo=pytz.utc)
local_time = localize_time(now_utc, guild_id)
duration = get_conversation_duration(guild_id)
return (
base_prompt +
f"\nThe current server timezone is {tz}." +
f"\nThe local time is {local_time.strftime('%Y-%m-%d %H:%M:%S %Z')}." +
f"\nThe conversation has been going for {str(duration).split('.')[0]}."
)
async def fetch_llama4_response(prompt: str, user: Optional[discord.Member] = None, history: Optional[list] = None, system_prompt: str = DEFAULT_SYSTEM_PROMPT) -> Optional[str]:
if not FIREWORKS_API_KEY:
logger.error("No FIREWORKS_API_KEY set!")
return None
headers = {
"Authorization": f"Bearer {FIREWORKS_API_KEY}",
"Content-Type": "application/json"
}
user_info = ""
if user is not None:
user_info = f"The following message is from {user.display_name} (ID: {user.id}):\n"
history_text = ""
if history:
formatted = []
for author, content in history:
if author == "bot":
formatted.append(f"Bot: {content}")
else:
formatted.append(f"{author}: {content}")
history_text = "Recent conversation:\n" + "\n".join(formatted) + "\n"
messages = [
{"role": "system", "content": system_prompt or ""},
{"role": "user", "content": history_text + user_info + prompt}
]
data = {
"model": LLAMA4_MODEL,
"messages": messages
}
try:
timeout = aiohttp.ClientTimeout(total=15)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(FIREWORKS_API_URL, headers=headers, json=data) as resp:
if resp.status == 200:
result = await resp.json()
if "choices" in result and result["choices"]:
return result["choices"][0]["message"]["content"]
return None
else:
logger.error(f"Llama 4 API error: {resp.status} {await resp.text()}")
return None
except Exception as e:
logger.error(f"Llama 4 API exception: {e}")
return None
@bot.command(name="miku")
async def miku(ctx, *, prompt: str):
"""Get an AI response from Miku."""
async with ctx.typing():
try:
history = await get_recent_channel_history(ctx.channel, bot.user, ctx.message, limit=10)
system_prompt_for_guild = get_system_prompt_with_timezone_and_duration(ctx.guild.id)
ai_response = await fetch_llama4_response(prompt, user=ctx.author, history=history, system_prompt=system_prompt_for_guild)
if ai_response and isinstance(ai_response, str):
if not hasattr(bot, '_recent_endings'):
bot._recent_endings = []
recent_endings = bot._recent_endings[-3:]
processed = postprocess_response(ai_response, recent_endings)
if processed:
last_words = processed.split()[-5:]
bot._recent_endings.append(" ".join(last_words))
await ctx.reply(processed)
else:
await ctx.reply("Sorry, I couldn't process that. Please try again.")
except Exception as e:
logger.error(f"Error in !miku command: {e}")
logger.error(f"Miku command traceback: {traceback.format_exc()}")
await ctx.reply("❌ An unexpected error occurred while processing your command.")
@bot.event
async def on_ready():
if bot.user:
logger.info(f"✅ Logged in as {bot.user.name}")
# Add persistent views
bot.add_view(RoleButtonView()) # Add the persistent view for game roles
# Start scheduled tasks
daily_role_reset.start()
logger.info(f"Bot is in {len(bot.guilds)} guilds")
# Ensure bot.loop is set
if not hasattr(bot, 'loop') or bot.loop is discord.utils.MISSING:
bot.loop = asyncio.get_event_loop()
logger.warning("Bot.loop was missing, explicitly set it in on_ready.")
# Set bot startup time for uptime tracking
setattr(bot, 'start_time', discord.utils.utcnow())
# Initialize bot attributes
if not hasattr(bot, 'user_themes'):
setattr(bot, 'user_themes', {})
if not hasattr(bot, '_recent_endings'):
setattr(bot, '_recent_endings', [])
# --- NEW: Initialize voice activity for all users currently in voice channels ---
for guild in bot.guilds:
guild_id = guild.id
if guild_id not in voice_activity_today:
voice_activity_today[guild_id] = {}
for channel in guild.voice_channels:
for member in channel.members:
user_id = str(member.id)
if user_id not in voice_activity_today[guild_id]:
voice_activity_today[guild_id][user_id] = {
"name": member.display_name,
"join_time": discord.utils.utcnow(), # treat as just joined
"total_time": 0
}
bot.loop.create_task(heartbeat())
bot.loop.create_task(reset_voice_activity())
bot.loop.create_task(reset_daily_stats())
# Remove the duplicate task creation since it's now properly integrated in the function
@bot.event
async def on_member_join(member):
"""Welcome new members to the server"""
try:
# Update server stats
server_stats["users_joined"] += 1
settings = get_guild_settings(member.guild.id)
welcome_channel_id = settings.get("welcome_channel_id")
welcome_channel = bot.get_channel(welcome_channel_id) if welcome_channel_id else None
if welcome_channel:
# Greeting detection
greetings = ["hello", "hi", "hey", "namaste", "yo", "sup", "wassup"]
display_name = member.display_name.lower()
is_greeting = any(
re.search(rf'\\b{{re.escape(word)}}\\b', display_name, re.IGNORECASE)
for word in greetings
)
# List of funny/scary welcome messages
spooky_messages = [
f"Welcome, {member.mention}! You've entered the haunted server… 👻",
f"Beware, {member.mention}! New souls rarely leave… 😈",
f"You've joined us… forever, {member.mention}. Mwahaha! 🦇",
f"Don't look behind you, {member.mention}. Just kidding… or am I? 😱",
f"Welcome, {member.mention}! The ghosts will show you around. Maybe.",
f"You're just in time for the midnight ritual, {member.mention}! 🔮",
f"Hey {member.mention}, did you hear that noise? Must be the server spirits… 👀",
f"Welcome, {member.mention}! We hope you survive your stay… 🪦",
f"A wild {member.mention} appeared! The monsters are pleased. 🧟♂️",
f"Welcome, {member.mention}! Don't feed the vampires after midnight. 🧛♂️"
]
greeting_messages = [
f"Well, look at you, {member.mention}! Your name is a greeting all by itself. Welcome to the server! 🎉",
f"Hello {member.mention}! With a name like that, you're already bringing good vibes. Glad to have you!",
f"Heyyy {member.mention}! A name that says hello? You're my kind of people. Welcome!",
f"Yo {member.mention}! Your username is basically a welcome mat. Come on in!"
]
if is_greeting:
welcome_text = random.choice(greeting_messages)
else:
welcome_text = random.choice(spooky_messages)
embed = discord.Embed(
title="🎃 Welcome to the Spooky Server!",
description=welcome_text,
color=0x00ff88)
gif_url = random.choice(WELCOME_GIFS)
embed.set_image(url=gif_url)
embed.set_thumbnail(url=member.display_avatar.url)
embed.set_footer(text=f"Member #{member.guild.member_count}")
embed.timestamp = discord.utils.utcnow()
if isinstance(welcome_channel, discord.TextChannel):
await welcome_channel.send(embed=embed, content=f"Welcome {member.mention}!")
logger.info(f"Welcomed new member: {member.display_name}")
# Send a DM to the new member
try:
welcome_text = (
"Hey there! 🎉\n\n"
"Welcome to **Miku Server**! We're excited to have you join our community.\n"
"Feel free to ask any questions or just say hi—everyone here is super friendly!\n\n"
"Enjoy your stay! 💖\n\n"
"- MIKU-BOT"
)
# Debug log for GIF selection
if WELCOME_GIFS:
gif_url = random.choice(WELCOME_GIFS)
logger.info(f"Selected welcome GIF for DM: {gif_url}")
else:
gif_url = None
logger.warning("WELCOME_GIFS list is empty! No GIF will be sent in DM.")
await member.send(welcome_text)
if gif_url:
await member.send(gif_url)
except Exception as e:
logger.error(f"Failed to send welcome DM to {member.display_name}: {e}")
except Exception as e:
logger.error(f"Error welcoming member {member.display_name}: {e}")
@bot.event
async def on_member_remove(member):
"""Handle member leaving"""
try:
server_stats["users_left"] += 1
settings = get_guild_settings(member.guild.id)
modlog_channel_id = settings.get("modlog_channel_id")
mod_channel = bot.get_channel(modlog_channel_id) if modlog_channel_id else None
if mod_channel:
embed = discord.Embed(
title="👋 Member Left",
description=f"{member.display_name} has left the server",
color=0xffaa00
)
embed.add_field(name="Account Created", value=discord.utils.format_dt(member.created_at, style='D'), inline=True)
embed.add_field(name="Joined", value=discord.utils.format_dt(member.joined_at, style='D'), inline=True)
embed.set_thumbnail(url=member.display_avatar.url)
embed.timestamp = discord.utils.utcnow()
if isinstance(mod_channel, discord.TextChannel):
await mod_channel.send(embed=embed)
except Exception as e:
logger.error(f"Error handling member leave: {e}")
@bot.event
async def on_message_delete(message):
"""Handle message deletion"""
try:
settings = get_guild_settings(message.guild.id)
modlog_channel_id = settings.get("modlog_channel_id")
mod_channel = bot.get_channel(modlog_channel_id) if modlog_channel_id else None
if mod_channel and not message.author.bot:
embed = discord.Embed(
title="🗑️ Message Deleted",
description=f"**Channel:** {message.channel.mention}\n**Author:** {message.author.mention}",
color=0xff0000
)
embed.add_field(name="Content", value=message.content[:1000] + "..." if len(message.content) > 1000 else message.content, inline=False)
embed.set_thumbnail(url=message.author.display_avatar.url)
embed.timestamp = discord.utils.utcnow()
if isinstance(mod_channel, discord.TextChannel):
await mod_channel.send(embed=embed)
except Exception as e:
logger.error(f"Error handling message deletion: {e}")
@bot.event
async def on_message_edit(before, after):
"""Handle message edits"""
try:
# Ignore bot messages and if content didn't change
if before.author.bot or before.content == after.content:
return
settings = get_guild_settings(before.guild.id)
modlog_channel_id = settings.get("modlog_channel_id")
mod_channel = bot.get_channel(modlog_channel_id) if modlog_channel_id else None
if mod_channel:
embed = discord.Embed(
title="✏️ Message Edited",
description=f"**Channel:** {before.channel.mention}\n**Author:** {before.author.mention}",
color=0xffaa00
)
embed.add_field(name="Before", value=before.content[:500] + "..." if len(before.content) > 500 else before.content, inline=False)
embed.add_field(name="After", value=after.content[:500] + "..." if len(after.content) > 500 else after.content, inline=False)
embed.add_field(name="Link", value=f"[Jump to Message]({after.jump_url})", inline=False)
embed.set_thumbnail(url=before.author.display_avatar.url)
embed.timestamp = discord.utils.utcnow()
await mod_channel.send(embed=embed)
except Exception as e:
logger.error(f"Error handling message edit: {e}")
@bot.event
async def on_error(event, *args, **kwargs):
logger.error(f"Error in event {event}: {args}")
@bot.event
async def on_command_error(ctx, error):
"""Handle command errors"""
if isinstance(error, commands.CommandNotFound):
return # don't spam chat for typos
elif isinstance(error, commands.MissingPermissions):
await ctx.send(f"❌ You don't have permission to use this command!")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"❌ Missing required argument: {error.param.name}")
elif isinstance(error, commands.BadArgument):
await ctx.send(f"❌ Invalid argument provided!")
elif isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"⏰ Command is on cooldown! Try again in {error.retry_after:.1f} seconds.")
elif isinstance(error, commands.NoPrivateMessage):
await ctx.send("❌ This command can only be used in servers!")
else:
logger.error(f"Unhandled command error: {error}")
logger.error(f"Command error traceback: {traceback.format_exc()}")
# await ctx.send("❌ An unexpected error occurred while processing your command.")
@bot.event
async def on_voice_state_update(member, before, after):
try:
guild_id = member.guild.id
user_id = str(member.id)
if guild_id not in voice_activity_today:
voice_activity_today[guild_id] = {}
if user_id not in voice_activity_today[guild_id]:
voice_activity_today[guild_id][user_id] = {
"name": member.display_name,
"join_time": None,
"total_time": 0
}
if guild_id not in voice_activity_alltime:
voice_activity_alltime[guild_id] = {}
if user_id not in voice_activity_alltime[guild_id]:
voice_activity_alltime[guild_id][user_id] = {
"name": member.display_name,
"total_time": 0
}
# User joined a voice channel
if after.channel and not before.channel:
# Only set join_time if not self-deafened, not self-muted, and not in AFK channel
settings = get_guild_settings(member.guild.id)
afk_channel_id = settings.get("afk_channel_id")
if not after.self_deaf and not after.self_mute and (not afk_channel_id or after.channel.id != afk_channel_id):
voice_activity_today[guild_id][user_id]["join_time"] = discord.utils.utcnow()
else:
voice_activity_today[guild_id][user_id]["join_time"] = None
# User left a voice channel or switched
elif before.channel and (not after.channel or before.channel != after.channel):
join_time = voice_activity_today[guild_id][user_id]["join_time"]
now = discord.utils.utcnow()
settings = get_guild_settings(member.guild.id)
afk_channel_id = settings.get("afk_channel_id")
# Only count time if not self-deafened, not self-muted, and not in AFK channel
if join_time is not None and not before.self_deaf and not before.self_mute and (not afk_channel_id or before.channel.id != afk_channel_id):
if (getattr(join_time, 'tzinfo', None) is not None and join_time.tzinfo is not None and join_time.tzinfo.utcoffset(join_time) is not None):
if getattr(now, 'tzinfo', None) is None or now.tzinfo is None or now.tzinfo.utcoffset(now) is None:
now = now.replace(tzinfo=timezone.utc)
else:
if getattr(now, 'tzinfo', None) is not None and now.tzinfo is not None and now.tzinfo.utcoffset(now) is not None:
now = now.replace(tzinfo=None)
time_spent = (now - join_time).total_seconds()
voice_activity_today[guild_id][user_id]["total_time"] += time_spent
# --- Alltime update ---
voice_activity_alltime[guild_id][user_id]["total_time"] += time_spent
voice_activity_alltime[guild_id][user_id]["name"] = member.display_name
update_weekly_voice_time(guild_id, user_id, time_spent)
# Reset join_time if still in a channel and not self-deafened, not self-muted, and not in AFK channel
if after.channel and not after.self_deaf and not after.self_mute and (not afk_channel_id or after.channel.id != afk_channel_id):
voice_activity_today[guild_id][user_id]["join_time"] = discord.utils.utcnow()
else:
voice_activity_today[guild_id][user_id]["join_time"] = None
# User switched channels (reset join time if still in voice)
elif before.channel and after.channel and before.channel != after.channel:
join_time = voice_activity_today[guild_id][user_id]["join_time"]
now = discord.utils.utcnow()
settings = get_guild_settings(member.guild.id)
afk_channel_id = settings.get("afk_channel_id")
# Only count time if not self-deafened, not self-muted, and not in AFK channel
if join_time is not None and not before.self_deaf and not before.self_mute and (not afk_channel_id or before.channel.id != afk_channel_id):
if (getattr(join_time, 'tzinfo', None) is not None and join_time.tzinfo is not None and join_time.tzinfo.utcoffset(join_time) is not None):
if getattr(now, 'tzinfo', None) is None or now.tzinfo is None or now.tzinfo.utcoffset(now) is None:
now = now.replace(tzinfo=timezone.utc)
else:
if getattr(now, 'tzinfo', None) is not None and now.tzinfo is not None and now.tzinfo.utcoffset(now) is not None:
now = now.replace(tzinfo=None)
time_spent = (now - join_time).total_seconds()
voice_activity_today[guild_id][user_id]["total_time"] += time_spent
# --- Alltime update ---
voice_activity_alltime[guild_id][user_id]["total_time"] += time_spent
voice_activity_alltime[guild_id][user_id]["name"] = member.display_name
update_weekly_voice_time(guild_id, user_id, time_spent)
# Reset join_time if still in a channel and not self-deafened, not self-muted, and not in AFK channel
if after.channel and not after.self_deaf and not after.self_mute and (not afk_channel_id or after.channel.id != afk_channel_id):
voice_activity_today[guild_id][user_id]["join_time"] = discord.utils.utcnow()
else:
voice_activity_today[guild_id][user_id]["join_time"] = None
# Use per-guild AFK channel
settings = get_guild_settings(member.guild.id)
afk_channel_id = settings.get("afk_channel_id")
# User joined a voice channel (start AFK tracking)
if after.channel and (not afk_channel_id or after.channel.id != afk_channel_id):
user_voice_activity[user_id] = {
"last_activity": discord.utils.utcnow(),
"channel_id": after.channel.id,
"afk_task": None,
"deafen_start": discord.utils.utcnow() if after.self_deaf else None
}
if user_id in user_voice_activity:
user_voice_activity[user_id]["afk_task"] = asyncio.create_task(
check_afk_status(member, user_id))
# Handle deafen/undeafen status changes
if after.channel and (not afk_channel_id or after.channel.id != afk_channel_id) and user_id in user_voice_activity:
if not before.self_deaf and after.self_deaf:
user_voice_activity[user_id]["deafen_start"] = discord.utils.utcnow()
elif before.self_deaf and not after.self_deaf:
user_voice_activity[user_id]["deafen_start"] = None
# Handle joining template channels
if after.channel and after.channel.id in [
v["id"] for v in TEMPLATE_CHANNELS.values()
]:
for name, info in TEMPLATE_CHANNELS.items():
if after.channel.id == info["id"]:
guild = member.guild
if not guild.me.guild_permissions.manage_channels:
logger.error("Bot lacks permission to manage channels")
return
try:
channel_name = f"{name} | {member.display_name}"
user_themes = getattr(bot, 'user_themes', {})
if str(member.id) in user_themes:
theme = user_themes[str(member.id)]
channel_name = f"{theme['emoji']} {theme['data']['name']} | {member.display_name}"
new_vc = await guild.create_voice_channel(
name=channel_name,
user_limit=info["limit"],
category=after.channel.category)
created_channels[new_vc.id] = True
await member.move_to(new_vc)
channel_stats["total_created"] += 1
if user_id not in channel_stats["user_activity"]:
channel_stats["user_activity"][user_id] = {
"name": member.display_name,
"channels_created": 0
}
channel_stats["user_activity"][user_id][
"channels_created"] += 1
await check_and_assign_roles(
member, channel_stats["user_activity"][user_id]
["channels_created"])
welcome_channel = bot.get_channel(WELCOME_CHANNEL_ID)
if welcome_channel:
embed = discord.Embed(
title="🎉 New Voice Channel Created!",
description=
f"{member.mention} just created **{new_vc.name}**",
color=0x00ff00)
embed.add_field(name="Channel Type",
value=name,
inline=True)
embed.add_field(name="User Limit",
value=f"{info['limit']} members",
inline=True)
embed.add_field(name="Created By",
value=member.display_name,
inline=True)
embed.set_thumbnail(url=member.display_avatar.url)
embed.timestamp = discord.utils.utcnow()
await welcome_channel.send(embed=embed)
logger.info(
f"Created channel: {new_vc.name} for {member.display_name}"
)
break
except discord.Forbidden:
logger.error(
"Bot forbidden to create channels or move members")
except discord.HTTPException as e:
logger.error(f"HTTP error creating channel: {e}")
# Handle leaving created channels
if before.channel and before.channel.id in created_channels:
await asyncio.sleep(5)
try:
channel = bot.get_channel(before.channel.id)
if channel and len(channel.members) == 0:
await channel.delete()
if before.channel.id in created_channels:
del created_channels[before.channel.id]
logger.info(f"Deleted empty channel: {channel.name}")
except discord.NotFound:
if before.channel.id in created_channels:
del created_channels[before.channel.id]
except discord.Forbidden:
logger.error("Bot forbidden to delete channel")
except discord.HTTPException as e:
logger.error(f"HTTP error deleting channel: {e}")
save_all_data()
except Exception as e:
logger.error(f"Unexpected error in voice state update: {e}")
# --- Auto-moderation function ---
async def auto_moderate(message: discord.Message):
"""Auto-moderation checks for messages"""
try:
# Skip if user has manage messages permission
if message.author.guild_permissions.manage_messages:
return
content = message.content
user_id = str(message.author.id)
# Caps check
if len(content) > 10:
caps_count = sum(1 for c in content if c.isupper())
caps_ratio = caps_count / len(content)
if caps_ratio > AUTO_MODERATION["caps_threshold"]:
await message.channel.send(f"⚠️ {message.author.mention}, please don't use excessive caps!")
return
# Banned words check
content_lower = content.lower()