forked from xNul/chat-llama-discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
7067 lines (6339 loc) · 387 KB
/
bot.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
# pyright: reportOptionalMemberAccess=false
import logging as _logging
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from dataclasses_json import dataclass_json
from typing import Any, Optional
from pathlib import Path
import asyncio
import random
import json
import re
import glob
import os
import warnings
import discord
from discord.ext import commands
from discord import app_commands, File
import typing
import io
import base64
import yaml
from PIL import Image, PngImagePlugin
import requests
import aiohttp
import math
import time
from threading import Lock
from pydub import AudioSegment
import copy
from shutil import copyfile
import sys
import traceback
from modules.typing import ChannelID, UserID, MessageID, CtxInteraction # noqa: F401
import signal
from typing import Union
from functools import partial
sys.path.append("ad_discordbot")
from modules.utils_files import load_file, merge_base, save_yaml_file # noqa: F401
from modules.utils_shared import shared_path, bg_task_queue, task_processing, flows_queue, flows_event, patterns, bot_emojis, config, bot_database
from modules.database import StarBoard, Statistics, BaseFileMemory
from modules.utils_misc import check_probability, fix_dict, update_dict, sum_update_dict, update_dict_matched_keys, random_value_from_range, convert_lists_to_tuples, get_time, format_time, format_time_difference, get_normalized_weights # noqa: F401
from modules.utils_discord import Embeds, guild_only, guild_or_owner_only, configurable_for_dm_if, is_direct_message, ireply, sleep_delete_message, send_long_message, \
EditMessageModal, SelectedListItem, SelectOptionsView, get_user_ctx_inter, get_message_ctx_inter, apply_reactions_to_messages, replace_msg_in_history_and_discord, MAX_MESSAGE_LENGTH, muffled_send # noqa: F401
from modules.utils_aspect_ratios import ar_parts_from_dims, dims_from_ar, avg_from_dims, get_aspect_ratio_parts, calculate_aspect_ratio_sizes # noqa: F401
from modules.history import HistoryManager, History, HMessage, cnf
from modules.typing import AlertUserError, TAG
from modules.utils_asyncio import generate_in_executor
from modules.tags import base_tags, persistent_tags, Tags
from discord.ext.commands.errors import HybridCommandError, CommandError
from discord.errors import DiscordException
from discord.app_commands import AppCommandError, CommandInvokeError
from modules.logs import import_track, get_logger, log_file_handler, log_file_formatter; import_track(__file__, fp=True); log = get_logger(__name__) # noqa: E702
logging = log
# Databases
starboard = StarBoard()
bot_statistics = Statistics()
#################################################################
#################### DISCORD / BOT STARTUP ######################
#################################################################
bot_embeds = Embeds()
# Intercept custom bot arguments
def parse_bot_args():
bot_arg_list = ["--limit-history", "--token"]
bot_argv = []
for arg in bot_arg_list:
try:
index = sys.argv.index(arg)
except Exception:
index = None
if index is not None:
bot_argv.append(sys.argv.pop(index))
bot_argv.append(sys.argv.pop(index))
import argparse
parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=54))
parser.add_argument("--token", type=str, help="Discord bot token to use their API.")
parser.add_argument("--limit-history", type=int, help="When the history gets too large, performance issues can occur. Limit the history to improve performance.")
bot_args = parser.parse_args(bot_argv)
return bot_args
bot_args = parse_bot_args()
# Set Discord bot token from config, or args, or prompt for it, or exit
TOKEN = config.discord.get('TOKEN', None)
bot_token = bot_args.token if bot_args.token else TOKEN
if not bot_token:
print('\nA Discord bot token is required. Please enter it below.\n \
For help, refer to Install instructions on the project page\n \
(https://github.com/altoiddealer/ad_discordbot)')
print('\nDiscord bot token (enter "0" to exit):\n')
bot_token = (input().strip())
print()
if bot_token == '0':
log.error("Discord bot token is required. Exiting.")
sys.exit(2)
elif bot_token:
config.discord['TOKEN'] = bot_token
config.save()
log.info("Discord bot token saved to 'config.yaml'")
else:
log.error("Discord bot token is required. Exiting.")
sys.exit(2)
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
os.environ["BITSANDBYTES_NOWELCOME"] = "1"
warnings.filterwarnings("ignore", category=UserWarning, message="TypedStorage is deprecated")
warnings.filterwarnings("ignore", category=UserWarning, message="You have modified the pretrained model configuration to control generation")
# Set discord intents
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix=".", intents=intents)
client.is_first_on_ready = True # type: ignore
#################################################################
################### Stable Diffusion Startup ####################
#################################################################
class SD:
def __init__(self):
self.enabled:bool = config.sd.get('enabled', True)
self.url:str = config.sd.get('SD_URL', 'http://127.0.0.1:7860')
self.client:str = None
self.session_id:str = None
self.last_img_payload = {}
if self.enabled:
if asyncio.run(self.online()):
asyncio.run(self.init_sdclient())
async def online(self, ictx:CtxInteraction|None=None):
channel = ictx.channel if ictx else None
e_title = f"Stable Diffusion is not running at: {self.url}"
e_description = f"Launch your SD WebUI client with `--api --listen` command line arguments\n\
Read more [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/API)"
async with aiohttp.ClientSession() as session:
try:
async with session.get(f'{self.url}/') as response:
if response.status == 200:
log.debug(f'Request status to SD: {response.status}')
return True
else:
log.warning(f'Non-200 status code received: {response.status}')
await bot_embeds.send('system', e_title, e_description, channel=channel, delete_after=10)
return False
except aiohttp.ClientError as exc:
# never successfully connected
if self.client is None:
log.warning(e_title)
log.warning("Launch your SD WebUI client with `--api --listen` command line arguments")
log.warning("Image commands/features will function when client is active and accessible via API.'")
# was previously connected
else:
log.warning(exc)
await bot_embeds.send('system', e_title, e_description, channel=channel, delete_after=10)
return False
async def api(self, endpoint:str, method='get', json=None, retry=True, warn=True) -> dict:
headers = {'Content-Type': 'application/json'}
try:
async with aiohttp.ClientSession() as session:
async with session.request(method.lower(), url=f'{self.url}{endpoint}', json=json or {}, headers=headers) as response:
response_text = await response.text()
if response.status == 200:
r = await response.json()
if self.client is None and endpoint not in ['/sdapi/v1/cmd-flags', '/API/GetNewSession']:
await self.init_sdclient()
if self.client and not self.client == 'SwarmUI':
bot_settings.imgmodel.refresh_enabled_extensions(print=True)
for settings in guild_settings.values():
settings:Settings
settings.imgmodel.refresh_enabled_extensions()
return r
# Try resolving certain issues and retrying
elif response.status in [422, 500]:
error_json = await response.json()
try_resolve = False
# Check if it's related to an invalid override script
if 'Script' in error_json.get('detail', ''):
script_name = error_json['detail'].split("'")[1] # Extract the script name
if json and 'alwayson_scripts' in json:
# Remove the problematic script
if script_name in json['alwayson_scripts']:
log.info(f"Removing invalid script: {script_name}")
json['alwayson_scripts'].pop(script_name, None)
try_resolve = True
elif 'KeyError' in error_json.get('error', ''):
# Extract the key name from the error message
key_error_msg = error_json.get('errors', '')
key_name = key_error_msg.split("'")[1] # Extract the key inside single quotes
log.info(f"Removing invalid key: {key_name}")
# Remove the problematic key from the payload
if json and key_name in json:
json.pop(key_name, None)
try_resolve = True
if try_resolve:
return await self.api(endpoint, method, json, retry=False, warn=warn)
# Handle internal server error (status 500)
elif response.status == 500:
error_json = await response.json()
# Check if it's related to the KeyError
if 'KeyError' in error_json.get('error', '') and "'forge_inference_memory'" in error_json.get('errors', ''):
log.info("Removing problematic key: 'forge_inference_memory'")
# Remove 'forge_inference_memory' from the payload if it exists
if json and 'forge_inference_memory' in json:
json.pop('forge_inference_memory', None)
# Retry the request with the modified payload
return await self.api(endpoint, method, json, retry=False, warn=warn)
# Log the error if the request failed
if warn:
log.error(f'{self.url}{endpoint} response: {response.status} "{response.reason}"')
log.error(f'Response content: {response_text}')
# Retry on specific status codes (408, 500)
if retry and response.status in [408, 500]:
log.info("Retrying the request in 3 seconds...")
await asyncio.sleep(3)
return await self.api(endpoint, method, json, retry=False)
except aiohttp.client.ClientConnectionError:
log.warning(f'Failed to connect to: "{self.url}{endpoint}", offline?')
except Exception as e:
if endpoint == '/sdapi/v1/server-restart' or endpoint == '/sdapi/v1/progress':
return None
else:
log.error(f'Error getting data from "{self.url}{endpoint}": {e}')
traceback.print_exc()
def determine_client_type(self, r):
ui_settings_file = r.get("ui_settings_file", "").lower()
if "reforge" in ui_settings_file:
self.client = 'SD WebUI ReForge'
elif "forge" in ui_settings_file:
self.client = 'SD WebUI Forge'
elif "webui" in ui_settings_file:
self.client = 'A1111 SD WebUI'
else:
self.client = 'SD WebUI'
async def try_sdwebuis(self):
try:
log.info("Checking if SD Client is A1111, Forge, ReForge, or other.")
r = await self.api(endpoint='/sdapi/v1/cmd-flags')
if not r:
raise ConnectionError(f'Failed to connect to SD API, ensure it is running or disable the API in your config.')
self.determine_client_type(r)
except ConnectionError as e:
log.error(f"Connection error: {e}")
except Exception as e:
log.error(f"Unexpected error when checking SD WebUI clients: {e}")
traceback.print_exc()
async def try_swarmui(self):
try:
log.info("Checking if SD Client is SwarmUI.")
r = await self.api(endpoint='/API/GetNewSession', method='post', warn=False)
if r is None:
return False # Early return if the response is None or the API call failed
self.session_id = r.get('session_id', None)
if self.session_id:
self.client = 'SwarmUI'
return True
except aiohttp.ClientError as e:
log.error(f"Error getting SwarmUI session: {e}")
return False
async def init_sdclient(self):
if await self.try_swarmui():
return
if not self.session_id:
await self.try_sdwebuis()
sd = SD()
if sd.enabled:
# Function to attempt restarting the SD WebUI Client in the event it gets stuck
@client.hybrid_command(description=f"Immediately Restarts the {sd.client} server. Requires '--api-server-stop' SD WebUI launch flag.")
@guild_or_owner_only()
async def restart_sd_client(ctx: commands.Context):
await ctx.send(f"**`/restart_sd_client` __will not work__ unless {sd.client} was launched with flag: `--api-server-stop`**", delete_after=10)
await sd.api(endpoint='/sdapi/v1/server-restart', method='post', json=None, retry=False)
title = f"{ctx.author.display_name} used '/restart_sd_client'. Restarting {sd.client} ..."
await bot_embeds.send('system', title=title, description='Attempting to re-establish connection in 5 seconds (Attempt 1 of 10)', channel=ctx.channel)
log.info(title)
response = None
retry = 1
while response is None and retry < 11:
await bot_embeds.edit('system', description=f'Attempting to re-establish connection in 5 seconds (Attempt {retry} of 10)')
await asyncio.sleep(5)
response = await sd.api(endpoint='/sdapi/v1/progress', method='get', json=None, retry=False)
retry += 1
if response:
title = f"{sd.client} restarted successfully."
await bot_embeds.edit('system', title=title, description=f"Connection re-established after {retry} out of 10 attempts.")
log.info(title)
else:
title = f"{sd.client} server unresponsive after Restarting."
await bot_embeds.edit('system', title=title, description="Connection was not re-established after 10 attempts.")
log.error(title)
if sd.client:
log.info(f"Initializing with SD WebUI enabled: '{sd.client}'")
else:
log.info("SD WebUI currently offline. Image commands/features will function when client is active and accessible via API.'")
#################################################################
##################### TEXTGENWEBUI STARTUP ######################
#################################################################
sys.path.append(shared_path.dir_tgwui)
from modules.utils_tgwui import tts, tgwui, shared, utils, extensions_module, \
custom_chatbot_wrapper, chatbot_wrapper, load_character, save_history, unload_model, count_tokens
#################################################################
##################### BACKGROUND QUEUE TASK #####################
#################################################################
async def process_tasks_in_background():
while True:
task = await bg_task_queue.get()
await task
#################################################################
########################## BOT STARTUP ##########################
#################################################################
## Function to automatically change image models
# Select imgmodel based on mode, while avoid repeating current imgmodel
async def auto_select_imgmodel(current_imgmodel_name, mode='random'):
try:
all_imgmodels = await fetch_imgmodels()
all_imgmodel_names = [imgmodel.get('imgmodel_name', '') for imgmodel in all_imgmodels]
current_index = None
if current_imgmodel_name and current_imgmodel_name in all_imgmodel_names:
current_index = all_imgmodel_names.index(current_imgmodel_name)
if mode == 'random':
if current_index is not None and len(all_imgmodels) > 1:
all_imgmodels.pop(current_index)
return random.choice(all_imgmodels)
elif mode == 'cycle':
if current_index is not None:
next_index = (current_index + 1) % len(all_imgmodel_names) # Cycle to the beginning if at the end
return all_imgmodels[next_index]
else:
log.info("[Auto Change Imgmodels] Previous imgmodel name was not matched in list of fetched imgmodels.")
log.info("[Auto Change Imgmodels] New imgmodel was selected at random instead of 'cycle'.")
return random.choice(all_imgmodels) # If no image model set yet, select randomly
except Exception as e:
log.error(f"[Auto Change Imgmodels] Error selecting image model: {e}")
# Task to auto-select an imgmodel at user defined interval
async def auto_update_imgmodel_task(mode, duration):
while True:
await asyncio.sleep(duration)
try:
# Select an imgmodel automatically
selected_imgmodel = await auto_select_imgmodel(bot_database.last_imgmodel_name, mode)
# CREATE TASK AND QUEUE IT
params = Params(imgmodel=selected_imgmodel)
change_imgmodel_task = Task('change_imgmodel', ictx=None, params=params)
await task_manager.task_queue.put(change_imgmodel_task)
except Exception as e:
log.error(f"[Auto Change Imgmodels] Error updating image model: {e}")
#await asyncio.sleep(duration)
imgmodel_update_task = None # Global variable allows process to be cancelled and restarted (reset sleep timer)
if sd.enabled:
# Register command for helper function to toggle auto-select imgmodel
@client.hybrid_command(description='Toggles the automatic Img model changing task')
@guild_or_owner_only()
async def toggle_auto_change_imgmodels(ctx: commands.Context):
global imgmodel_update_task
if imgmodel_update_task and not imgmodel_update_task.done():
imgmodel_update_task.cancel()
await ctx.send("Auto-change Imgmodels task was cancelled.", ephemeral=True, delete_after=5)
log.info("[Auto Change Imgmodels] Task was cancelled via '/toggle_auto_change_imgmodels_task'")
else:
await bg_task_queue.put(start_auto_change_imgmodels())
await ctx.send("Auto-change Img models task was started.", ephemeral=True, delete_after=5)
# helper function to begin auto-select imgmodel task
async def start_auto_change_imgmodels(status:str='started'):
try:
global imgmodel_update_task
imgmodels_data = load_file(shared_path.img_models, {})
auto_change_settings = imgmodels_data.get('settings', {}).get('auto_change_imgmodels', {})
mode = auto_change_settings.get('mode', 'random')
frequency = auto_change_settings.get('frequency', 1.0)
duration = frequency*3600 # 3600 = 1 hour
imgmodel_update_task = client.loop.create_task(auto_update_imgmodel_task(mode, duration))
log.info(f"[Auto Change Imgmodels] Task was {status} (Mode: '{mode}', Frequency: {frequency} hours).")
except Exception as e:
log.error(f"[Auto Change Imgmodels] Error starting task: {e}")
async def init_auto_change_imgmodels():
if sd.enabled:
imgmodels_data = load_file(shared_path.img_models, {})
if imgmodels_data and imgmodels_data.get('settings', {}).get('auto_change_imgmodels', {}).get('enabled', False):
if config.is_per_server() and len(guild_settings) > 1:
log.warning('[Auto Change Imgmodels] Main config is set for "per-guild" settings management. Disabling this task.')
# Remove the registered command '/toggle_auto_change_imgmodels'
client.remove_command("toggle_auto_change_imgmodels")
else:
await bg_task_queue.put(start_auto_change_imgmodels())
# Try getting a valid character file source
def get_character(guild_id:int|None=None, guild_settings=None):
# Determine applicable Settings()
settings:Settings = guild_settings if guild_settings is not None else bot_settings
joined_msg = 'has joined the chat'
if guild_settings:
joined_msg = f'has joined {settings._guild_name}'
try:
# Try loading last known character with fallback sources
sources = [
bot_settings.get_last_setting_for("last_character", guild_id=guild_id),
settings.llmcontext.name,
client.user.display_name
]
char_name = None
for try_source in sources:
log.debug(f'Trying to load character "{try_source}"...')
try:
_, char_name, _, _, _ = load_character(try_source, '', '')
if char_name:
log.info(f'"{try_source}" {joined_msg}.')
source = try_source
break # Character loaded successfully, exit the loop
except Exception as e:
log.error(f"Error loading character for chat mode: {e}")
if not char_name:
log.error(f"Character not found. Tried files: {sources}")
return None
return source
except Exception as e:
log.error(f"Error trying to load character data: {e}")
return None
# Try loading character data regardless of mode (chat/instruct)
async def init_characters():
# Per-server characters
if config.is_per_character():
for guild_id, settings in guild_settings.items():
log.info("----------------------------------------------")
log.info(f"Initializing {settings._guild_name}...")
char_name = get_character(guild_id, settings)
if char_name:
await character_loader(char_name, settings, guild_id=guild_id)
# Not per-server characters
else:
char_name = get_character()
if char_name:
await character_loader(char_name, bot_settings)
bot_status.build_idle_weights()
def update_base_tags_modified():
mod_time = os.path.getmtime(shared_path.tags)
last_mod_time = bot_database.last_base_tags_modified
updated = (mod_time > last_mod_time) if last_mod_time else False
bot_database.set("last_base_tags_modified", mod_time, save_now=updated) # update value
return updated
# Creates instances of Settings() for all guilds the bot is in
async def init_guilds():
global guild_settings
per_server_settings = config.is_per_server()
post_settings = config.discord['post_active_settings'].get('enabled', True)
if per_server_settings or post_settings:
# check/update last time modified for dict_tags.yaml
tags_updated = update_base_tags_modified()
# iterate over guilds
for guild in client.guilds:
# create Settings()
if per_server_settings:
guild_settings[guild.id] = Settings(guild)
# post Tags settings
previously_sent_settings = bot_database.settings_sent.get(guild.id) # must have sent settings before
previously_sent_tags = bool(bot_database.get_settings_msgs_for(guild.id, 'tags'))
# post tags if file was updated, or if guild has not yet posted them
if post_settings and previously_sent_settings and (tags_updated or not previously_sent_tags):
await bg_task_queue.put(post_active_settings(guild, ['tags']))
# If first time bot script is run
async def first_run():
try:
log.info('Welcome to ad_discordbot!')
log.info('• Use "/character" for changing characters.')
log.info('• Use "/helpmenu" to see other useful commands.')
log.info('• Visit https://github.com/altoiddealer/ad_discordbot for more info.')
log.info('• Learn about command permissions in the Wiki section: "Commands".')
for guild in client.guilds: # Iterate over all guilds the bot is a member of
if guild.text_channels and bot_embeds.enabled('system'):
# Find the 'general' channel, if it exists
default_channel = None
for channel in guild.text_channels:
if channel.name == 'general':
default_channel = channel
break
# If 'general' channel is not found, use the first text channel
if default_channel is None:
default_channel = guild.text_channels[0]
async with muffled_send(default_channel):
await default_channel.send(embed = bot_embeds.helpmenu())
break # Exit the loop after sending the message to the first guild
log.info('Welcome to ad_discordbot! Use "/helpmenu" to see main commands. (https://github.com/altoiddealer/ad_discordbot) for more info.')
except Exception as e: # muffled send will not catch all errors, only specific ones we can ignore.
log.error(f"An error occurred while welcoming user to the bot: {e}")
finally:
bot_database.set('first_run', False)
#################################################################
########################### ON READY ############################
#################################################################
@client.event
async def on_ready():
# If first time running bot
if bot_database.first_run:
await first_run()
# Ensure startup tasks do not re-execute if bot's discord connection status fluctuates
if client.is_first_on_ready: # type: ignore
client.is_first_on_ready = False # type: ignore
# Create background task processing queue
client.loop.create_task(process_tasks_in_background())
# Start the Task Manager
client.loop.create_task(task_manager.process_tasks())
# Run guild startup tasks
await init_guilds()
# Load character(s)
if tgwui.enabled:
await init_characters()
# Start background task to to change image models automatically
await init_auto_change_imgmodels()
log.info("----------------------------------------------")
log.info(" Bot is ready")
log.info(" Use Ctrl+C to shutdown the bot cleanly")
log.info("----------------------------------------------")
# Run only on discord reconnections
else:
await voice_clients.restore_state()
######################
# Run every on_ready()
# Start background task to sync the discord client tree
await bg_task_queue.put(client.tree.sync())
# Schedule bot to go idle, if configured
await bot_status.schedule_go_idle()
#################################################################
################### DISCORD EVENTS/FEATURES #####################
#################################################################
@client.event
async def on_message(message: discord.Message):
text = message.clean_content # primarily converts @mentions to actual user names
settings:Settings = get_settings(message)
last_character = bot_settings.get_last_setting_for("last_character", message)
if tgwui.enabled and not settings.behavior.bot_should_reply(message, text, last_character):
return # Check that bot should reply or not
# Store the current time. The value will save locally to database.yaml at another time
bot_database.update_last_msg_for(message.channel.id, 'user', save_now=False)
# if @ mentioning bot, remove the @ mention from user prompt
if text.startswith(f"@{last_character} "):
text = text.replace(f"@{last_character} ", "", 1)
# apply wildcards
text = await dynamic_prompting(text, message, message.author.display_name)
# Create Task from message
task = Task('on_message', message, text=text)
# Send to to MessageManager()
await message_manager.queue_message_task(task, settings)
# Starboard feature
@client.event
async def on_raw_reaction_add(endorsed_img):
if not config.discord.get('starboard', {}).get('enabled', False):
return
channel = await client.fetch_channel(endorsed_img.channel_id)
message = await channel.fetch_message(endorsed_img.message_id)
total_reaction_count = 0
if config.discord['starboard'].get('emoji_specific', False):
for emoji in config.discord['starboard'].get('react_emojis', []):
reaction = discord.utils.get(message.reactions, emoji=emoji)
if reaction:
total_reaction_count += reaction.count
else:
bot_emojis_list = bot_emojis.get_emojis()
for reaction in message.reactions:
if reaction.emoji in bot_emojis_list:
continue
total_reaction_count += reaction.count
if total_reaction_count >= config.discord['starboard'].get('min_reactions', 2):
target_channel_id = config.discord['starboard'].get('target_channel_id', None)
if target_channel_id == 11111111111111111111:
target_channel_id = None
target_channel = client.get_channel(target_channel_id)
if target_channel and message.id not in starboard.messages:
# Create the message link
message_link = f'[Original Message]({message.jump_url})'
# Duplicate image and post message link to target channel
if message.attachments:
attachment_url = message.attachments[0].url
await target_channel.send(message_link)
await target_channel.send(attachment_url)
elif message.embeds and message.embeds[0].image:
image_url = message.embeds[0].image.url
await target_channel.send(message_link)
await target_channel.send(image_url)
# Add the message ID to the set and update the file
starboard.messages.append(message.id)
starboard.save()
#################################################################
##################### POST ACTIVE SETTINGS ######################
#################################################################
async def delete_old_settings_messages(channel:discord.TextChannel, old_msg_ids:list):
for msg_id in old_msg_ids:
message = None
try:
message = await channel.fetch_message(msg_id)
except Exception as e:
log.warning(f"[Post Active Settings] Tried deleting an old settings message which was not found: {e}")
if message:
await message.delete()
# Post settings to all servers
async def post_active_settings_to_all(key_str_list:Optional[list[str]]=None):
for guild in client.guilds:
await post_active_settings(guild, key_str_list)
# Post settings to a dedicated channel
async def post_active_settings(guild:discord.Guild, key_str_list:Optional[list[str]]=None, channel:discord.TextChannel|None=None):
# List of settings keys to update
key_str_list = key_str_list if key_str_list is not None else ['character', 'behavior', 'tags', 'imgmodel', 'llmstate']
# For configured keys: Delete old settings messages -> Send new settings
managed_keys = config.discord['post_active_settings'].get('post_settings_for', [])
# Warn for old config setting
old_settings_chan = config.discord['post_active_settings'].get('target_channel_id', None)
if old_settings_chan and not bot_database.was_warned('old_settings_chan'):
bot_database.update_was_warned('old_settings_chan')
log.warning("[Post Active Settings] This feature now uses channels set by a command '/set_server_settings_channel'.")
log.warning("[Post Active Settings] Ignoring 'target_channel_id'. Check '.../settings_templates/config.yaml' for current settings.")
# get settings channel if not provided to function
if channel is None:
channel_id = bot_database.get_settings_channel_id_for(guild.id)
# Warn (once) if no ID set for server while setting is enabled
if not channel_id:
if not bot_database.was_warned(f'{guild.id}_chan'):
bot_database.update_was_warned(f'{guild.id}_chan')
log.warning(f"[Post Active Settings] This feature is enabled, but a channel is not yet set for server '{guild.name}'.")
log.warning("[Post Active Settings] Use command '/set_server_settings_channel' to designate a 'settings channel'.")
return
try:
channel = await guild.fetch_channel(channel_id)
except:
log.error(f"[Post Active Settings] Failed to fetch channel from stored id '{channel_id}'")
log.info("[Post Active Settings] Use command '/set_server_settings_channel' to set a new channel.")
return
log.info(f"[Post Active Settings] Posting updated settings for '{guild.name}': {key_str_list}.")
# Collect current settings
settings:"Settings" = guild_settings.get(guild.id, bot_settings)
settings_copy = copy.deepcopy(settings.get_vars())
# Extract tags for Tags message
char_tags = settings_copy['llmcontext'].pop('tags', [])
imgmodel_tags = settings_copy['imgmodel'].pop('tags', [])
# Manage settings messages for the provided list of settings keys, as configured
for key_name in key_str_list:
if key_name not in managed_keys:
continue # skip keys not configured
# Get stored IDs for old settings messages
old_msg_ids_list = bot_database.get_settings_msgs_for(guild.id, key_name)
# Fetch and delete the old messages
if old_msg_ids_list:
await delete_old_settings_messages(channel, old_msg_ids_list)
# Set empty defaults
tags_ids = []
tags_key = None
custom_prefix = ''
# Determine settings sources for current key
if key_name == 'character':
custom_prefix = f'name: {bot_settings.get_last_setting_for("last_character", guild_id=guild.id)}\n'
# resolve alias
settings_key = settings_copy.get('llmcontext', {})
# check if updating character tags
if 'tags' in managed_keys:
tags_key = char_tags
elif key_name == 'imgmodel':
custom_prefix = f'name: {bot_settings.get_last_setting_for("last_imgmodel_name", guild_id=guild.id)}\n'
settings_key = settings_copy.get('imgmodel', {})
# check if updating imgmodel tags
if 'tags' in managed_keys:
tags_key = imgmodel_tags
elif key_name == 'tags':
settings_key = base_tags.tags
else:
settings_key = settings_copy.get(key_name, {})
# Convert dictionary to yaml for message
settings_content = yaml.dump(settings_key, default_flow_style=False)
# Send the updated settings content to the settings channel
new_settings_ids, _ = await send_long_message(channel, f"## {key_name.upper()}:\n```yaml\n{custom_prefix}{settings_content}\n────────────────────────────────```")
# Also send relevant Tags for the item in a second process
if tags_key is not None:
# Convert tags list to yaml for message
tags_content = yaml.dump(tags_key, default_flow_style=False)
tags_ids, _ = await send_long_message(channel, f"### {key_name.upper()} TAGS:\n```yaml\n{tags_content}\n────────────────────────────────```")
# Merge all sent message IDs while retaining them to database
new_settings_ids = new_settings_ids + tags_ids
# Update the database with the new message ID(s)
bot_database.update_settings_key_msgs_for(guild.id, key_name, new_settings_ids)
async def switch_settings_channels(guild:discord.Guild, channel:discord.TextChannel):
# Get old settings dict (if any)
old_settings_dict = bot_database.get_settings_msgs_for(guild.id)
# Get old settings channel ID (if any)
old_channel_id = bot_database.get_settings_channel_id_for(guild.id)
# Update the guild settings channel
bot_database.update_settings_channel(guild.id, channel.id)
# Delete messages from old settings channel
if old_channel_id and old_settings_dict:
log.info("[Post Active Settings] Trying to delete old messages from previous settings channel...")
old_channel = None
try:
old_channel = await guild.fetch_channel(old_channel_id)
except Exception as e:
log.error(f"[Post Active Settings] Failed to fetch old settings channel from ID '{old_channel_id}': {e}")
if old_channel:
for old_msg_ids in old_settings_dict.values():
await delete_old_settings_messages(old_channel, old_msg_ids)
# Post all current settings to new settings channel
await post_active_settings(guild, channel=channel)
if config.discord['post_active_settings'].get('enabled', True):
# Command to set settings channels (post_active_settings feature)
@client.hybrid_command(name="set_server_settings_channel", description="Assign a channel as the settings channel for this server.")
@app_commands.describe(channel='Begin typing the channel name and it should appear in the menu.')
@app_commands.checks.has_permissions(manage_channels=True)
@guild_only()
async def set_server_settings_channel(ctx: commands.Context, channel: Optional[discord.TextChannel]=None):
if channel is None:
raise AlertUserError("Please select a text channel to set (select from 'channel').")
if channel not in ctx.guild.channels:
raise AlertUserError('Selected channel not found in this server.')
# Skip update process if same channel as previously set
old_channel_id = bot_database.get_settings_channel_id_for(ctx.guild.id)
if channel.id == old_channel_id:
await ctx.send("New settings channel is the same as the previously set one.", delete_after=5)
return
log.info(f'[Post Active Settings] {ctx.author.display_name} used "/set_server_settings_channel".')
log.info(f"[Post Active Settings] Settings channel for '{ctx.guild.name}' was set to '{channel.name}'")
# Reply to interaction
await ctx.send(f"Settings channel for **{ctx.guild.name}** set to **{channel.name}**.", delete_after=5)
# Process message updates in the background
await bg_task_queue.put(switch_settings_channels(ctx.guild, channel))
#################################################################
######################## TTS PROCESSING #########################
#################################################################
class VoiceClients:
def __init__(self):
self.guild_vcs:dict = {}
self.expected_state:dict = {}
self.queued_tts:list = []
def is_connected(self, guild_id):
if self.guild_vcs.get(guild_id):
return self.guild_vcs[guild_id].is_connected()
return False
def should_be_connected(self, guild_id):
return self.expected_state.get(guild_id, False)
# Try loading character data regardless of mode (chat/instruct)
async def restore_state(self):
for guild_id, should_be_connected in self.expected_state.items():
try:
if should_be_connected and not self.is_connected(guild_id):
voice_channel = client.get_channel(bot_database.voice_channels[guild_id])
self.guild_vcs[guild_id] = await voice_channel.connect()
elif not should_be_connected and self.is_connected(guild_id):
await self.guild_vcs[guild_id].disconnect()
except Exception as e:
log.error(f'[Voice Clients] An error occurred while restoring voice channel state for guild ID "{guild_id}": {e}')
async def toggle_voice_client(self, guild_id, toggle:str=None):
try:
if toggle == 'enabled' and not self.is_connected(guild_id):
if bot_database.voice_channels.get(guild_id):
voice_channel = client.get_channel(bot_database.voice_channels[guild_id])
self.guild_vcs[guild_id] = await voice_channel.connect()
self.expected_state[guild_id] = True
else:
log.warning(f'[Voice Clients] "{tts.client}" enabled, but a valid voice channel is not set for this server.')
log.info('[Voice Clients] Use "/set_server_voice_channel" to select a voice channel for this server.')
if toggle == 'disabled':
if self.is_connected(guild_id):
await self.guild_vcs[guild_id].disconnect()
self.expected_state[guild_id] = False
except Exception as e:
log.error(f'[Voice Clients] An error occurred while toggling voice channel for guild ID "{guild_id}": {e}')
async def voice_channel(self, guild_id:int, vc_setting:bool=True):
try:
# Start voice client if configured, and not explicitly deactivated in character settings
if tts.enabled and vc_setting == True and int(tts.settings.get('play_mode', 0)) != 1 and not self.guild_vcs.get(guild_id):
try:
if tts.client and tts.client in shared.args.extensions:
await self.toggle_voice_client(guild_id, 'enabled')
else:
if not bot_database.was_warned('char_tts'):
bot_database.update_was_warned('char_tts')
log.warning('[Voice Clients] No "tts_client" is specified in config.yaml')
except Exception as e:
log.error(f"[Voice Clients] An error occurred while connecting to voice channel: {e}")
# Stop voice client if explicitly deactivated in character settings
if self.guild_vcs.get(guild_id) and self.guild_vcs[guild_id].is_connected():
if vc_setting is False:
log.info("[Voice Clients] New context has setting to disconnect from voice channel. Disconnecting...")
await self.toggle_voice_client(guild_id, 'disabled')
except Exception as e:
log.error(f"[Voice Clients] An error occurred while managing channel settings: {e}")
def after_playback(self, guild_id, file, error):
if error:
log.info(f'[Voice Clients] Message from audio player: {error}, output: {error.stderr.decode("utf-8")}')
# Check save mode setting
if int(tts.settings.get('save_mode', 0)) > 0:
try:
os.remove(file)
except Exception:
pass
# Check if there are queued tasks
if self.queued_tts:
# Pop the first task from the queue and play it
next_file = self.queued_tts.pop(0)
source = discord.FFmpegPCMAudio(next_file)
self.guild_vcs[guild_id].play(source, after=lambda e: self.after_playback(guild_id, next_file, e))
async def play_in_voice_channel(self, guild_id, file):
if not self.guild_vcs.get(guild_id):
log.warning(f"[Voice Clients] tts response detected, but bot is not connected to a voice channel in guild ID {guild_id}")
return
# Queue the task if audio is already playing
if self.guild_vcs[guild_id].is_playing():
self.queued_tts.append(file)
else:
# Otherwise, play immediately
source = discord.FFmpegPCMAudio(file)
self.guild_vcs[guild_id].play(source, after=lambda e: self.after_playback(guild_id, file, e))
def detect_format(self, file_path):
try:
audio = AudioSegment.from_wav(file_path)
return 'wav'
except:
pass
try:
audio = AudioSegment.from_mp3(file_path)
return 'mp3'
except:
pass
return None
async def upload_tts_file(self, channel:discord.TextChannel, tts_resp:str|None=None, bot_hmessage:HMessage|None=None):
file = tts_resp
filename = os.path.basename(file)
original_ext = os.path.splitext(filename)[1]
correct_ext = original_ext
detected_format = self.detect_format(file)
if detected_format is None:
raise ValueError(f"Could not determine the audio file format for file: {file}")
if original_ext != f'.{detected_format}':
correct_ext = f'.{detected_format}'
new_filename = os.path.splitext(filename)[0] + correct_ext
new_file_path = os.path.join(os.path.dirname(file), new_filename)
os.rename(file, new_file_path)
file = new_file_path
mp3_filename = os.path.splitext(filename)[0] + '.mp3'
bit_rate = int(tts.settings.get('mp3_bit_rate', 128))
with io.BytesIO() as buffer:
if file.endswith('wav'):
audio = AudioSegment.from_wav(file)
elif file.endswith('mp3'):
audio = AudioSegment.from_mp3(file)
else:
log.error('TTS generated unsupported file format:', file)
audio.export(buffer, format="mp3", bitrate=f"{bit_rate}k")
mp3_file = File(buffer, filename=mp3_filename)
sent_message = await channel.send(file=mp3_file)
# if bot_hmessage:
# bot_hmessage.update(audio_id=sent_message.id)
async def process_tts_resp(self, ictx:CtxInteraction, tts_resp:Optional[str]=None, bot_hmessage:Optional[HMessage]=None):
play_mode = int(tts.settings.get('play_mode', 0))
# Upload to interaction channel
if play_mode > 0:
await self.upload_tts_file(ictx.channel, tts_resp, bot_hmessage)
# Play in voice channel
connected = self.guild_vcs.get(ictx.guild.id)
if not is_direct_message(ictx) and play_mode != 1 and self.guild_vcs.get(ictx.guild.id):
await bg_task_queue.put(self.play_in_voice_channel(ictx.guild.id, tts_resp)) # run task in background
if bot_hmessage:
bot_hmessage.update(spoken=True)
voice_clients = VoiceClients()
# Command to set voice channels
@client.hybrid_command(name="set_server_voice_channel", description="Assign a channel as the voice channel for this server")
@app_commands.checks.has_permissions(manage_channels=True)
@guild_only()
async def set_server_voice_channel(ctx: commands.Context, channel: Optional[discord.VoiceChannel]=None):
if isinstance(ctx.author, discord.Member) and ctx.author.voice:
channel = channel or ctx.author.voice.channel # type: ignore
if channel is None:
raise AlertUserError('Please select or join a voice channel to set.')
log.info(f'{ctx.author.display_name} used "/set_server_voice_channel".')
bot_database.update_voice_channels(ctx.guild.id, channel.id)
await ctx.send(f"Voice channel for **{ctx.guild}** set to **{channel.name}**.", delete_after=5)
if tgwui.enabled:
# Register command for helper function to toggle TTS
@client.hybrid_command(description='Toggles TTS on/off')
@guild_only()
async def toggle_tts(ctx: commands.Context):
if not tts.client:
await ctx.reply('No TTS client is configured, so the TTS setting cannot be toggled.', ephemeral=True, delete_after=5)
return
await ireply(ctx, 'toggle TTS') # send a response msg to the user
# offload to TaskManager() queue
log.info(f'{ctx.author.display_name} used "/toggle_tts"')
toggle_tts_task = Task('toggle_tts', ctx)
await task_manager.task_queue.put(toggle_tts_task)
#################################################################
###################### DYNAMIC PROMPTING ########################
#################################################################
def get_wildcard_value(matched_text:str, dir_path: Optional[str] = None) -> Optional[str]:
dir_path = dir_path or shared_path.dir_wildcards
selected_option: Optional[str] = None
search_phrase = matched_text[2:] if matched_text.startswith('##') else matched_text
search_path = f"{search_phrase}.txt"
# List files in the directory