-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsoupy_remastered.py
2404 lines (1986 loc) · 97.3 KB
/
soupy_remastered.py
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
"""
Soupy - A Discord bot that does chat and images.
Repository: https://github.com/sneezeparty/soupy
Licensed under the MIT License.
MIT License
Copyright (c) 2024-2025 sneezeparty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# Standard library imports
import asyncio
import json
import logging
import mimetypes
import os
import random
import re
import signal
import sys
import time
from collections import defaultdict
from datetime import datetime, timedelta, time as datetime_time
from functools import wraps
from io import BytesIO
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
# Third party imports
import aiohttp
import discord
import pytz
from aiohttp import ClientConnectorError, ClientOSError, ClientSession, ServerTimeoutError
from bs4 import BeautifulSoup
from discord import app_commands, AllowedMentions, Embed
from discord.ext import commands, tasks
from discord.ui import View, Modal, TextInput
from dotenv import load_dotenv
from geopy.geocoders import Nominatim
from openai import OpenAI, OpenAIError
from timezonefinder import TimezoneFinder
from logging.handlers import RotatingFileHandler
import html2text
import trafilatura
from PIL import Image
import soupy_interject
import soupy_search
# Logging and color imports
import colorama
from colorama import Fore, Style
from colorlog import ColoredFormatter
# Initialize colorama
colorama.init(autoreset=True)
"""
---------------------------------------------------------------------------------
Logging Configuration
---------------------------------------------------------------------------------
"""
# Add these near the top of the file, with your other imports and constants
DATE_FORMAT = "%Y-%m-%d %H:%M:%S,%f" # Changed from .%f to ,%f
LOG_FORMAT_FILE = "[%(asctime)s] (%(levelname)s) %(name)s => %(message)s"
class CustomFormatter(logging.Formatter):
"""Custom formatter with colors"""
COLORS = {
'DEBUG': '\033[95m', # Purple
'INFO': '\033[92m', # Bright Green
'WARNING': '\033[93m', # Yellow
'ERROR': '\033[91m', # Red
'CRITICAL': '\033[41m' # Red background
}
RESET = '\033[0m'
TIMESTAMP_COLOR = '\033[36m' # Cyan for timestamps
ARROW_COLOR = '\033[90m' # Grey for the arrow
NAME_COLOR = '\033[94m' # Blue for logger name
def format(self, record):
# Format the timestamp with milliseconds
timestamp = self.formatTime(record, self.datefmt)
# Color the level name with parentheses
level_color = self.COLORS.get(record.levelname, '')
colored_level = f"{level_color}({record.levelname}){self.RESET}"
# Format the full message with colors
formatted_message = (
f"{self.TIMESTAMP_COLOR}[{timestamp}]{self.RESET} "
f"{colored_level} "
f"{self.NAME_COLOR}{record.name}{self.RESET} "
f"{self.ARROW_COLOR}=>{self.RESET} "
f"{record.getMessage()}"
)
if record.exc_info:
# If there's an exception, add it to the message
exc_text = self.formatException(record.exc_info)
formatted_message = f"{formatted_message}\n{exc_text}"
return formatted_message
def formatTime(self, record, datefmt=None):
"""Format time with proper milliseconds"""
ct = self.converter(record.created)
if datefmt:
# Get milliseconds directly from the record's created timestamp
msec = int((record.created - int(record.created)) * 1000)
s = time.strftime(datefmt, ct)
# Replace the milliseconds placeholder with actual milliseconds
s = s.replace(',f', f',{msec:03d}')
return s
return time.strftime(self.default_time_format, ct)
# Create the formatters with the correct datetime format
console_formatter = CustomFormatter(
"[%(asctime)s] (%(levelname)s) %(name)s => %(message)s",
datefmt="%Y-%m-%d %H:%M:%S,f" # Changed from ,%f to ,f
)
file_formatter = logging.Formatter(
"[%(asctime)s] (%(levelname)s) %(name)s => %(message)s",
datefmt="%Y-%m-%d %H:%M:%S,f" # Changed from ,%f to ,f
)
# Create logs directory if it doesn't exist
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
# Generate base log filename without timestamp
log_filename = "soupy.log"
log_filepath = log_dir / log_filename
# Constants for log rotation
MAX_LOG_SIZE = 5 * 1024 * 1024 # 5 MB in bytes
BACKUP_COUNT = 5 # Keep up to 5 backup files
# Set up handlers
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(CustomFormatter(
"[%(asctime)s] (%(levelname)s) %(name)s => %(message)s",
datefmt="%Y-%m-%d %H:%M:%S,f"
))
file_handler = RotatingFileHandler(
filename=log_filepath,
maxBytes=MAX_LOG_SIZE,
backupCount=BACKUP_COUNT,
encoding='utf-8'
)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(CustomFormatter(
"[%(asctime)s] (%(levelname)s) %(name)s => %(message)s",
datefmt="%Y-%m-%d %H:%M:%S,f"
))
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
handlers=[console_handler, file_handler]
)
logger = logging.getLogger(__name__)
logger.info(f"Logging initialized. Log file: {log_filepath}")
"""
---------------------------------------------------------------------------------
Load Environment Variables
---------------------------------------------------------------------------------
"""
# Load Environment Variables
load_dotenv()
# The local LLM usage
client = OpenAI(
base_url=os.getenv("OPENAI_BASE_URL"),
api_key=os.getenv("OPENAI_API_KEY", "lm-studio")
)
# Parse OWNER_IDS from .env
OWNER_IDS = [
int(id.strip()) for id in os.getenv("OWNER_IDS", "").split(",")
if id.strip().isdigit()
]
if not OWNER_IDS:
logger.warning("No OWNER_IDS specified. Reload functionality will be disabled.")
RANDOMPROMPT = os.getenv("RANDOMPROMPT", "")
if not RANDOMPROMPT:
logger.warning("No RANDOMPROMPT prompt found. Random functionality will be disabled.")
# Categories
def load_text_file_from_env(env_var):
"""Reads a text file specified in the .env variable and returns a list of comma-separated values."""
file_path = os.getenv(env_var, "").strip()
if file_path and os.path.exists(file_path):
with open(file_path, "r", encoding="utf-8") as file:
return [item.strip() for item in file.read().split(",") if item.strip()]
return []
# Load themes, character concepts, and artistic styles from the files specified in the .env
OVERALL_THEMES = load_text_file_from_env("OVERALL_THEMES")
CHARACTER_CONCEPTS = load_text_file_from_env("CHARACTER_CONCEPTS")
ARTISTIC_RENDERING_STYLES = load_text_file_from_env("ARTISTIC_RENDERING_STYLES")
chatgpt_behaviour = os.getenv("BEHAVIOUR", "You're a stupid bot.")
max_tokens_default = int(os.getenv("MAX_TOKENS", "800"))
# Flux-specific environment vars
MAX_INTERACTIONS_PER_MINUTE = int(os.getenv("MAX_INTERACTIONS_PER_MINUTE", 4))
LIMIT_EXCEPTION_ROLES = os.getenv("LIMIT_EXCEPTION_ROLES", "")
EXEMPT_ROLES = {role.strip().lower() for role in LIMIT_EXCEPTION_ROLES.split(",") if role.strip()}
DISCORD_BOT_TOKEN = os.getenv("DISCORD_TOKEN")
if not DISCORD_BOT_TOKEN:
raise ValueError("No DISCORD_TOKEN environment variable set.")
FLUX_SERVER_URL = os.getenv("FLUX_SERVER_URL")
if not FLUX_SERVER_URL:
raise ValueError("No FLUX_SERVER_URL environment variable set.")
CHANNEL_IDS_ENV = os.getenv("CHANNEL_IDS", "")
CHANNEL_IDS = [
int(cid.strip()) for cid in CHANNEL_IDS_ENV.split(",")
if cid.strip().isdigit()
]
if not CHANNEL_IDS:
logger.warning("No CHANNEL_IDS specified. Shutdown notifications will not be sent.")
REMOVE_BG_API_URL = os.getenv("REMOVE_BG_API_URL")
if not REMOVE_BG_API_URL:
raise ValueError("No REMOVE_BG_API_URL environment variable set.")
# Near the top of your file, with other environment variable loads
SPECIAL_GUILD_ID = os.getenv("SPECIAL_GUILD_ID")
BEHAVIOUR_ALT = os.getenv("BEHAVIOUR_ALT")
async def get_guild_behaviour(guild_id: str) -> str:
"""Get the appropriate behavior for the given guild ID."""
if guild_id == SPECIAL_GUILD_ID:
return BEHAVIOUR_ALT
return os.getenv("BEHAVIOUR")
def format_error_message(error):
error_prefix = "Error: "
if isinstance(error, OpenAIError):
return f"{error_prefix}An OpenAI API error occurred: {str(error)}"
return f"{error_prefix}{str(error)}"
image_history = {} # Dictionary to store recent image descriptions
"""
---------------------------------------------------------------------------------
Discord Bot Setup
---------------------------------------------------------------------------------
"""
# Move this section to the top of the file, after your imports but before other code
class SoupyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.flux_queue = FluxQueueManager()
# Add the async_chat_completion method to the bot class
async def async_chat_completion(self, *args, **kwargs):
"""Wraps the OpenAI chat completion in an async context"""
return await asyncio.to_thread(client.chat.completions.create, *args, **kwargs)
class FluxQueueManager:
def __init__(self):
self.queue = asyncio.Queue()
self.is_shutting_down = False
async def put(self, task):
if not self.is_shutting_down:
await self.queue.put(task)
def qsize(self):
return self.queue.qsize()
async def process_queue(self):
"""Background task to process queued flux generation or button tasks."""
while True:
# Check shutdown flag before getting new task
if self.is_shutting_down and self.queue.empty():
logger.info("🛑 Shutdown flag detected and queue is empty, stopping queue processor")
break
task = await self.queue.get()
try:
task_type = task.get('type')
logger.info(f"Processing task of type '{task_type}' for user {task.get('interaction').user if task.get('interaction') else 'Unknown'}.")
if task_type == 'flux':
interaction = task.get('interaction')
description = task.get('description')
size = task.get('size')
seed = task.get('seed')
if interaction and isinstance(interaction, discord.Interaction):
await process_flux_image(interaction, description, size, seed)
else:
logger.error("Task missing 'interaction' or 'interaction' is not a discord.Interaction instance for flux task.")
elif task_type == 'button':
interaction = task.get('interaction')
action = task.get('action')
prompt = task.get('prompt')
width = task.get('width')
height = task.get('height')
seed = task.get('seed')
logger.debug(f"Handling button action '{action}' for user {interaction.user}.")
if action == 'random':
# 'random' action does not require 'prompt' or 'seed'
if all([interaction, action, width is not None, height is not None]) and isinstance(interaction, discord.Interaction):
await handle_random(interaction, width, height, self.qsize())
else:
logger.error("Incomplete button task parameters for 'random' action.")
if not interaction.response.is_done():
await interaction.response.send_message("❌ Incomplete task parameters.", ephemeral=True)
else:
await interaction.followup.send("❌ Incomplete task parameters.", ephemeral=True)
elif action in ['remix', 'edit', 'fancy', 'wide', 'tall']:
if all([interaction, action, prompt, width is not None, height is not None]) and isinstance(interaction, discord.Interaction):
if action == 'remix':
await handle_remix(interaction, prompt, width, height, seed, self.qsize())
elif action == 'edit':
await handle_edit(interaction, prompt, width, height, seed, self.qsize())
elif action == 'fancy':
await handle_fancy(
interaction,
prompt,
width,
height,
seed,
self.qsize()
)
elif action == 'wide':
await handle_wide(interaction, prompt, width, height, seed, self.qsize())
elif action == 'tall':
await handle_tall(interaction, prompt, width, height, seed, self.qsize())
else:
logger.error(f"Incomplete button task parameters for '{action}' action.")
if not interaction.response.is_done():
await interaction.response.send_message("❌ Incomplete task parameters.", ephemeral=True)
else:
await interaction.followup.send("❌ Incomplete task parameters.", ephemeral=True)
else:
logger.error(f"Unknown button action: {action}")
if not interaction.response.is_done():
await interaction.response.send_message(f"Unknown action: {action}", ephemeral=True)
else:
await interaction.followup.send(f"Unknown action: {action}", ephemeral=True)
else:
logger.error(f"Unknown task type: {task_type}")
except Exception as e:
interaction = task.get('interaction')
if interaction and isinstance(interaction, discord.Interaction):
try:
if not interaction.response.is_done():
await interaction.response.send_message(
f"❌ An error occurred: {str(e)}", ephemeral=True
)
else:
await interaction.followup.send(
f"❌ An error occurred: {str(e)}", ephemeral=True
)
except AttributeError:
logger.error("Failed to send error message: interaction does not have 'response' or 'followup'.")
logger.error(f"Error processing task: {e}", exc_info=True)
finally:
self.queue.task_done()
if self.is_shutting_down:
# Clear remaining items from queue
while not self.queue.empty():
try:
dropped_task = self.queue.get_nowait()
interaction = dropped_task.get('interaction')
if interaction and isinstance(interaction, discord.Interaction):
try:
if not interaction.response.is_done():
await interaction.response.send_message(
"❌ Task cancelled due to bot shutdown",
ephemeral=True
)
else:
await interaction.followup.send(
"❌ Task cancelled due to bot shutdown",
ephemeral=True
)
except Exception:
pass
self.queue.task_done()
except asyncio.QueueEmpty:
break
break
async def initiate_shutdown(self):
"""Initiates the shutdown process for the queue."""
self.is_shutting_down = True
try:
# Wait a reasonable time for current task to complete
logger.info("⏳ Waiting for current task to complete...")
await asyncio.wait_for(self.queue.join(), timeout=30.0)
logger.info("✅ Queue processing completed or timeout reached.")
except asyncio.TimeoutError:
logger.warning("⚠️ Timeout waiting for queue to finish, proceeding with shutdown")
except Exception as e:
logger.error(f"❌ Error while waiting for queue to finish: {e}")
# Then your bot initialization can use the SoupyBot class
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
intents.members = True
allowed_mentions = discord.AllowedMentions(users=True)
bot = SoupyBot(
command_prefix='!',
intents=intents,
allowed_mentions=allowed_mentions
)
RATE_LIMIT = 0.25
# Keep track of user interactions for rate limiting (flux part)
user_interaction_timestamps = defaultdict(list)
"""
---------------------------------------------------------------------------------
Helper Functions
---------------------------------------------------------------------------------
"""
USER_STATS_FILE = Path("user_stats.json")
user_stats_lock = asyncio.Lock()
# Retrieves today's date in the format: Month Day, Year (e.g., January 2, 2025).
def get_todays_date() -> str:
return datetime.utcnow().strftime("%B %d, %Y")
async def read_user_stats():
# Reads the user statistics from the JSON file.
async with user_stats_lock:
try:
data = json.loads(USER_STATS_FILE.read_text())
# Convert old format to new format if necessary
if data and not any('servers' in user_data for user_data in data.values()):
new_data = {}
for user_id, stats in data.items():
new_data[user_id] = {
'username': stats.get('username', 'Unknown'),
'servers': {
'global': { # Store old stats as global stats
'images_generated': stats.get('images_generated', 0),
'chat_responses': stats.get('chat_responses', 0),
'mentions': stats.get('mentions', 0)
}
}
}
return new_data
return data
except json.JSONDecodeError:
logger.error("Failed to decode 'user_stats.json'. Resetting the file.")
return {}
except Exception as e:
logger.error(f"Error reading 'user_stats.json': {e}")
return {}
async def write_user_stats(data):
# Writes the user statistics to the JSON file.
async with user_stats_lock:
try:
USER_STATS_FILE.write_text(json.dumps(data, indent=4))
except Exception as e:
logger.error(f"Error writing to 'user_stats.json': {e}")
def universal_cooldown_check():
"""
One decorator to handle both slash commands (func(interaction, ...))
and UI callbacks (func(self, interaction, ...)).
"""
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
# Figure out if `self` is the first argument or not
# Typically, for slash commands, args[0] is `interaction`
# For UI callbacks, args[0] is `self`, and args[1] is `interaction`
if isinstance(args[0], commands.Bot) or isinstance(args[0], View):
# It's a method call, so the real interaction is args[1]
interaction = args[1]
self_obj = args[0] # if you need it
else:
# It's a normal slash command function, so args[0] is the interaction
interaction = args[0]
# Now that we have `interaction`, do your existing rate-limit logic
user_id = interaction.user.id
current_time = time.time()
# Skip if user is owner
if user_id in OWNER_IDS:
return await func(*args, **kwargs)
# Remove old timestamps
user_interaction_timestamps[user_id] = [
ts for ts in user_interaction_timestamps[user_id]
if current_time - ts < 60
]
# Check if user has any exempt roles
member = interaction.user
is_exempt = False
if isinstance(member, discord.Member):
user_roles = {role.name.lower() for role in member.roles}
if EXEMPT_ROLES.intersection(user_roles):
is_exempt = True
if not is_exempt and len(user_interaction_timestamps[user_id]) >= MAX_INTERACTIONS_PER_MINUTE:
await interaction.response.send_message(
f"❌ You have reached the maximum of {MAX_INTERACTIONS_PER_MINUTE} interactions per minute. Please wait.",
ephemeral=True
)
logger.warning(f"User {interaction.user} exceeded interaction limit.")
return
user_interaction_timestamps[user_id].append(current_time)
# Finally, call the wrapped function
return await func(*args, **kwargs)
return wrapper
return decorator
# Update the shutdown function
async def shutdown():
"""Graceful shutdown procedure."""
logger.info("🔄 Initiating graceful shutdown...")
try:
# Commented out notification code
'''
# Create shutdown embed
shutdown_embed = discord.Embed(
description="Soupy is now going offline.",
color=discord.Color.red(),
)
# Safely get avatar URL
avatar_url = None
if bot.user and bot.user.avatar:
avatar_url = bot.user.avatar.url
shutdown_embed.set_footer(text="Soupy Bot | Shutdown", icon_url=avatar_url)
# Notify channels about shutdown and wait for completion
logger.info("🔄 Starting channel notifications...")
try:
# Add a longer timeout for notifications
await asyncio.wait_for(notify_channels(embed=shutdown_embed), timeout=5.0)
logger.info("✅ Shutdown notifications sent successfully")
except asyncio.TimeoutError:
logger.warning("⚠️ Shutdown notifications timed out")
except Exception as e:
logger.error(f"❌ Error sending shutdown notifications: {e}")
'''
# Initiate queue shutdown if it exists
if hasattr(bot, 'flux_queue'):
await bot.flux_queue.initiate_shutdown()
# Close Discord connection
logger.info("🔒 Closing the Discord bot connection...")
await bot.close()
logger.info("✅ Discord bot connection closed.")
# Final log message
logger.info("🔚 Shutdown process completed.")
# Get the current loop and schedule delayed exit
loop = asyncio.get_running_loop()
# Increased delay to ensure notifications are sent
def delayed_exit():
sys.exit(0)
loop.call_later(3, delayed_exit) # Increased to 3 seconds
except Exception as e:
logger.error(f"❌ Error during shutdown: {e}")
sys.exit(1)
def handle_signal(signum, frame):
"""Handle termination signals by scheduling the shutdown coroutine."""
logger.info(f"🛑 Received termination signal ({signum}). Initiating shutdown...")
# Get the current event loop
try:
loop = asyncio.get_event_loop()
if loop.is_running():
loop.create_task(shutdown())
else:
loop.run_until_complete(shutdown())
except Exception as e:
logger.error(f"❌ Error in signal handler: {e}")
sys.exit(1)
# Add this new function
def select_response_style() -> str:
"""
Randomly selects a response style based on weighted probabilities.
Returns the instruction for the selected style.
"""
total = sum(style['weight'] for style in RESPONSE_STYLES.values())
r = random.uniform(0, total)
cumulative = 0
for style_name, style_info in RESPONSE_STYLES.items():
cumulative += style_info['weight']
if r <= cumulative:
logger.debug(f"🎲 Selected response style: {style_name}")
return style_info['instruction']
return '' # Fallback to default behavior
def get_random_terms():
terms = {}
if OVERALL_THEMES:
num_themes = random.randint(1, 3)
chosen_themes = random.sample(OVERALL_THEMES, num_themes)
terms['Overall Theme'] = ', '.join(chosen_themes)
if CHARACTER_CONCEPTS:
rand_val = random.random()
if rand_val < 0.05: # 5% chance of no character
pass # Skip adding a character
elif rand_val < 0.05:
terms['Character Concept'] = "Grey Sphynx Cat"
else: # 47.5% chance (0.525 to 1.0)
terms['Character Concept'] = random.choice(CHARACTER_CONCEPTS)
if ARTISTIC_RENDERING_STYLES:
# Randomly decide how many styles to pick (1-4)
num_styles = random.randint(1, 4)
# Get random styles without repeats
chosen_styles = random.sample(ARTISTIC_RENDERING_STYLES, num_styles)
terms['Artistic Rendering Style'] = ', '.join(chosen_styles)
return terms
async def handle_random(interaction, width, height, queue_size):
"""
Handles the generation of a random image by selecting random terms from categories
and combining them with the base random prompt.
"""
try:
if not RANDOMPROMPT:
await interaction.response.send_message("❌ No RANDOMPROMPT found in .env.", ephemeral=True)
return
if not interaction.response.is_done():
await interaction.response.defer(ephemeral=True)
# Start timing for prompt generation
prompt_start_time = time.perf_counter()
# Show typing indicator in the channel
async with interaction.channel.typing():
# Randomly choose dimensions
dimension_choices = [
(1024, 1024), # Square
(1920, 1024), # Wide
(1024, 1920) # Tall
]
width, height = random.choice(dimension_choices)
logger.info(f"🔀 Selected random dimensions for {interaction.user}: {width}x{height}")
# Get random terms first
random_terms = get_random_terms()
formatted_descriptors = "\n".join([f"**{category}:** {term}" for category, term in random_terms.items()])
logger.info(f"🔀 Selected Descriptors for {interaction.user}:\n{formatted_descriptors}")
# Combine with base prompt, but emphasize artistic style
art_style = random_terms.get('Artistic Rendering Style', '')
other_terms = [term for category, term in random_terms.items() if category != 'Artistic Rendering Style']
# Create a more detailed artistic style instruction
style_emphasis = (
f"The image should be rendered combining these artistic styles: {art_style}. "
f"These artistic styles should be the dominant visual characteristics, "
f"blended together, with the following elements incorporated within these styles: {', '.join(other_terms)}"
)
combined_prompt = f"{RANDOMPROMPT} {style_emphasis}"
logger.info(f"🔀 Combined Prompt for {interaction.user}:\n{combined_prompt}")
# Now send to LLM with modified system message
system_msg = {
"role": "system",
"content": "You are an assistant that creates image prompts with strong emphasis on artistic style. "
"The artistic rendering style should be prominently featured in your prompt, affecting every element described."
}
user_msg = {"role": "user", "content": combined_prompt}
messages_for_llm = [system_msg, user_msg]
# Add logging for the messages being sent to LLM
formatted_messages = format_messages(messages_for_llm)
logger.debug(f"📜 Sending the following messages to LLM for random prompt:\n{formatted_messages}")
response = await async_chat_completion(
model=os.getenv("LOCAL_CHAT"),
messages=messages_for_llm,
temperature=0.9,
max_tokens=325
)
random_prompt = response.choices[0].message.content.strip()
logger.info(f"🔀 Generated random prompt for {interaction.user}: {random_prompt}")
# End timing for prompt generation
prompt_end_time = time.perf_counter()
prompt_duration = prompt_end_time - prompt_start_time
# Capture the randomly chosen terms as a comma-separated string
# Flatten the terms from the dictionary
selected_terms_list = []
for category, terms in random_terms.items():
# Split by comma in case there are multiple terms in a single category
split_terms = [term.strip() for term in terms.split(',')]
selected_terms_list.extend(split_terms)
selected_terms_str = ", ".join(selected_terms_list)
logger.info(f"🔀 Selected Terms for {interaction.user}: {selected_terms_str}")
new_seed = random.randint(0, 2**32 - 1)
await generate_flux_image(
interaction=interaction,
prompt=random_prompt,
width=width,
height=height,
seed=new_seed, # Use new random seed
action_name="Random",
queue_size=queue_size,
pre_duration=prompt_duration, # Pass the prompt rewriting duration
selected_terms=selected_terms_str # Pass the selected terms
)
await increment_user_stat(interaction.user.id, 'images_generated')
except Exception as e:
logger.error(f"🔀 Error generating random prompt for {interaction.user}: {e}")
if not interaction.response.is_done():
await interaction.response.send_message(f"❌ Error generating random prompt: {e}", ephemeral=True)
else:
await interaction.followup.send(f"❌ Error generating random prompt: {e}", ephemeral=True)
# Initialize the JSON file if it doesn't exist
if not USER_STATS_FILE.exists():
USER_STATS_FILE.write_text(json.dumps({}))
logger.info("Created 'user_stats.json' for tracking user statistics.")
# Check if current UTC time is within allowed window (3 PM - 7 AM)
def is_within_allowed_time():
now_utc = datetime.utcnow().time()
start_time = datetime_time(15, 0) # 3:00 PM UTC
end_time = datetime_time(7, 0) # 7:00 AM UTC
if start_time > end_time:
return now_utc >= start_time or now_utc < end_time
return start_time <= now_utc < end_time
async def increment_user_stat(user_id: int, stat: str, server_id: Optional[int] = None):
"""
Increments a specific statistic for a user, optionally for a specific server.
Args:
user_id (int): Discord user ID
stat (str): The statistic to increment ('images_generated', 'chat_responses', 'mentions')
server_id (Optional[int]): The Discord server ID. If None, increments global stats.
"""
stats = await read_user_stats()
str_user_id = str(user_id)
# Initialize user entry if it doesn't exist
if str_user_id not in stats:
stats[str_user_id] = {
'username': 'Unknown',
'servers': {
'global': {
'images_generated': 0,
'chat_responses': 0,
'mentions': 0
}
}
}
# Update username if possible
user = bot.get_user(user_id)
if user:
stats[str_user_id]['username'] = user.name
# Initialize server stats if needed
if server_id:
str_server_id = str(server_id)
if 'servers' not in stats[str_user_id]:
stats[str_user_id]['servers'] = {}
if str_server_id not in stats[str_user_id]['servers']:
stats[str_user_id]['servers'][str_server_id] = {
'images_generated': 0,
'chat_responses': 0,
'mentions': 0
}
# Increment both global and server-specific stats
if 'global' not in stats[str_user_id]['servers']:
stats[str_user_id]['servers']['global'] = {
'images_generated': 0,
'chat_responses': 0,
'mentions': 0
}
# Increment global stat
stats[str_user_id]['servers']['global'][stat] += 1
# Increment server-specific stat if applicable
if server_id:
str_server_id = str(server_id)
stats[str_user_id]['servers'][str_server_id][stat] += 1
await write_user_stats(stats)
logger.debug(f"📈 Updated '{stat}' for user ID {user_id} (server ID: {server_id})")
# Format uptime
def format_uptime(td: timedelta) -> str:
"""
Formats a timedelta object into a string like "1 day, 3 hours, 12 minutes".
Args:
td (timedelta): The timedelta object representing uptime.
Returns:
str: A formatted string representing the uptime.
"""
total_seconds = int(td.total_seconds())
days, remainder = divmod(total_seconds, 86400) # 86400 seconds in a day
hours, remainder = divmod(remainder, 3600) # 3600 seconds in an hour
minutes, _ = divmod(remainder, 60) # 60 seconds in a minute
parts = []
if days > 0:
parts.append(f"{days} day{'s' if days != 1 else ''}")
if hours > 0:
parts.append(f"{hours} hour{'s' if hours != 1 else ''}")
if minutes > 0:
parts.append(f"{minutes} minute{'s' if minutes != 1 else ''}")
if not parts:
return "less than a minute"
return ', '.join(parts)
# Track bot start time for uptime calculation
bot_start_time = None
# Track Flux server status
flux_server_online = True # Assume online at start
chat_functions_online = True # Assume online at start
# Verify chat functionality by performing test completion
async def check_chat_functions():
global chat_functions_online
try:
test_prompt = "Hello, are you operational?"
response = await async_chat_completion(
model=os.getenv("LOCAL_CHAT"),
messages=[{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": test_prompt}],
temperature=0.0,
max_tokens=10
)
reply = response.choices[0].message.content.strip().lower()
if reply:
chat_functions_online = True
logger.info("Chat functions are online.")
else:
chat_functions_online = False
logger.warning("Chat functions did not return a valid response.")
except Exception as e:
chat_functions_online = False
logger.error(f"Chat functions are offline or encountered an error: {e}")
# Send notifications to all configured channels
async def notify_channels(embed: discord.Embed = None):
"""Notify designated channels with an embed."""
if not bot.is_ready():
logger.warning("⚠️ Bot is not ready, cannot send notifications")
return False
channel_ids_str = os.getenv("CHANNEL_IDS", "").strip()
if not channel_ids_str:
logger.warning("⚠️ No channel IDs configured in environment")
return False
channel_ids = channel_ids_str.split(",")
notifications_sent = False
for channel_id in channel_ids:
try:
if channel_id: # Skip empty strings
channel_id = int(channel_id.strip())
channel = bot.get_channel(channel_id)
if channel is None:
# Try fetching the channel if get_channel returns None
try:
channel = await bot.fetch_channel(channel_id)
except discord.NotFound:
logger.warning(f"⚠️ Channel ID {channel_id} not found")
continue
except Exception as e:
logger.error(f"❌ Error fetching channel {channel_id}: {e}")
continue
if embed:
await channel.send(embed=embed)
notifications_sent = True
logger.info(f"✅ Notification sent to channel {channel_id}")
except ValueError:
logger.error(f"❌ Invalid channel ID format: {channel_id}")
except Exception as e:
logger.error(f"❌ Error notifying channel {channel_id}: {e}")
logger.info("✅ Channel notifications complete")
return notifications_sent
@bot.event
async def on_close():
"""Logs detailed information during bot shutdown"""
logger.info("🔄 Bot close event triggered")
# Log active connections
logger.info(f"📡 Active voice connections: {len(bot.voice_clients)}")
logger.info(f"🌐 Connected to {len(bot.guilds)} guilds")
# Log remaining tasks
remaining_tasks = [task for task in asyncio.all_tasks() if not task.done()]
logger.info(f"📝 Remaining tasks to complete: {len(remaining_tasks)}")
for task in remaining_tasks:
logger.info(f" - Task: {task.get_name()}")
logger.info("👋 Bot shutdown complete")