-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
825 lines (702 loc) · 32.3 KB
/
bot.py
File metadata and controls
825 lines (702 loc) · 32.3 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
# Import Libraries
import discord, os, random, aiohttp, asyncio, json, base64, re, sys
from pathlib import Path
from discord.ext import commands
from datetime import datetime
from dotenv import load_dotenv
from zoneinfo import ZoneInfo
# Load dotEnv and Keys
load_dotenv(Path(".") / ".env", override=True) # Supprot for QT-AI Qettle
with open("config.json", "r") as f:
config = json.load(f)
def mentionfromtoken(BOT_TOKEN):
tokb64 = BOT_TOKEN.split(".")[0]
botId = base64.b64decode(tokb64 + "==")
return f"<@{int(botId)}>!"
# Load Config Keys
BOT_TOKEN = os.getenv("BOT_TOKEN")
def load_config(config, BOT_TOKEN):
botName = config.get("botName", "QT-AI Qup")
botPrefix = config.get("botPrefix", mentionfromtoken(BOT_TOKEN))
data = {
"modelURL": config.get("modelURL", "http://127.0.0.1:11434/api/generate"),
"Model": config.get("Model", "llama3.2"),
"ownerId": config.get("ownerId", "798072830595301406"),
"botName": botName,
"botPrefix": botPrefix,
"status": config.get("status", f"use {botPrefix}help"),
"mainPrompt": config.get("mainPrompt", "You are a Template bot for QT-AI with a default config. Your name is set to {bot_name}.").replace("{bot_name}", botName),
"knowledge": "\n".join(fact.replace("{bot_name}", botName) for fact in config.get("knowledge", [])),
"likes": config.get("likes", "").replace("{bot_name}", botName),
"dislikes": config.get("dislikes", "").replace("{bot_name}", botName),
"appearance": config.get("appearance", "").replace("{bot_name}", botName),
"responseSetup": config.get("responseSetup", "").replace("{bot_name}", botName),
"age": config.get("age", ""),
"errorMessage": config.get("errorMessage", "{bot_name} has encountered an error. please say that again").replace("{bot_name}", botName),
"stmSize": (int(config.get("stmSize", 50))- 2),
"imageMode": config.get("imageMode", "none"),
"imageModel": config.get("imageModel", "none"),
"timezone": config.get("timezone", False),
"noNSFW": config.get("noNSFW", True),
"summarizeChance": config.get("summarizeChance", 0.02),
"freewillToggle": config.get("freewillToggle", False),
"freewillReactChance": config.get("freewillReactChance", 0.05),
"freewillRespondChance": config.get("freewillRespondChance", 0.03),
"freewillKeywords": config.get("freewillKeywords", {}),
"replyChainLimit": config.get("replyChainLimit", 5),
"temperature": config.get("modelTemperature", 0.7),
"repeatPenalty": config.get("modelRepeatPenalty", 1.2),
"wackmsg": config.get("wackmsg", "Short term memory cleared."),
"sleepmsg": config.get("sleepmsg", "Long term memory saved."),
"top_k": config.get("ModelTK", 50),
"top_p": config.get("ModelTP", 0.9),
"emojis": config.get("emojis", {}),
}
return data
globals().update(load_config(config, BOT_TOKEN))
# Enable/Disable Eval command for debugging. Probably safe to keep enabled if you own the bot.
enableEval = True
#Initialize shit
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
bot = commands.Bot(command_prefix=botPrefix, intents=intents)
tree = bot.tree
# ensure the folders exist
os.makedirs("data", exist_ok=True)
# bot events
@bot.event
async def on_ready():
await bot.tree.sync()
print(f'{botName} QT-AI is ready (on {bot.user})')
await bot.change_presence(activity=discord.CustomActivity(name=status))
@bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
if message.content.startswith("!ignore") or message.content.endswith("!ignore"):
return
await bot.process_commands(message)
if message.content.startswith(botPrefix):
return
if message.guild:
aysmsquared = message.guild.id
else:
aysmsquared = message.author.id
db = load_db(aysmsquared)
guild_id = str(message.guild.id) if message.guild else None
channel_id = message.channel.id
db.setdefault("stm", {})
db["stm"].setdefault(str(message.channel.id), [])
if len(db["stm"][str(message.channel.id)]) > stmSize:
db["stm"][str(message.channel.id)] = db["stm"][str(message.channel.id)][-stmSize:]
stmcard = db["stm"][str(message.channel.id)]
dbFlag = True
if channel_id in db.get("channels", []):
stmcard.append(f"{message.author.global_name or message.author.name}: {message.content}") # allows bots and whatever
save_db(aysmsquared, db)
dbFlag = False
db.setdefault("ltm", [])
ltmcard = db["ltm"]
is_bot_mentioned = bot.user in message.mentions
should_respond = is_bot_mentioned or (channel_id in db.get("channels", []))
if isinstance(message.channel, discord.channel.DMChannel):
should_respond = True
discardFreewill = False
if not "freewill" in db:
if message.author.bot:
return
db.setdefault("freewill", {"Enabled": freewillToggle, "msgFreq": freewillRespondChance, "reactFreq": freewillReactChance, "blocked_channels": []})
discardFreewill = True
freewillOn = db["freewill"]["Enabled"]
if not should_respond and freewillOn:
freewillsettings = db["freewill"]
if str(message.channel.id) in db["freewill"]["blocked_channels"]:
return
currentMsgChance = db["freewill"]["msgFreq"] or freewillRespondChance
currentReactChance = db["freewill"]["reactFreq"] or freewillReactChance
if not "WeighKeywords" in db["freewill"] or db["freewill"]["WeighKeywords"]:
for word in message.content.split():
if word.lower() in freewillKeywords and freewillKeywords[word.lower()] is not None:
currentMsgChance += float(freewillKeywords[word.lower()][0])
currentReactChance += float(freewillKeywords[word.lower()][1])
if currentMsgChance > 1:
currentMsgChance = 1
if currentMsgChance < 0:
currentMsgChance = 0
if currentReactChance > 1:
currentReactChance = 1
if currentReactChance < 0:
currentReactChance = 0
if random.random() < currentMsgChance:
# improv stm :grin:
messages = [msg async for msg in message.channel.history(limit=int(stmSize/2))]
stm = "\n".join([f"{msg.author.global_name or msg.author.name}: {msg.content}" for msg in messages])
# ltm because yes
ltm = ""
for msg in ltmcard:
ltm = ltm + f"{msg}\n"
query = makeprompt(message, ltm, stm)
async with message.channel.typing():
response = await query_ollama(query)
# normalize ts that pmo icl
normalized = re.sub(r"[\u200B\u00A0]", " ", response)
normalized = normalized.replace("꞉", ":")
trimmed_response = normalized.replace(f"{botName}:", "")
cut = trimmed_response.split()
if ":" in cut[0]:
cut.pop(0)
trimmed_response = ""
for word in cut:
trimmed_response = trimmed_response + word + " "
trimmed_response = trimmed_response[:2000]
try:
await message.reply(trimmed_response, allowed_mentions=discord.AllowedMentions.none())
except Exception:
try:
await message.channel.send(trimmed_response, allowed_mentions=discord.AllowedMentions.none())
except Exception:
print(f"failed to send freewill message in #{message.channel.name} ({message.channel.id})")
if random.random() < currentReactChance:
# ltm because why not
ltm = ""
for msg in ltmcard:
ltm = ltm + f"{msg}\n"
unicode_pool = ["😀", "😎", "🔥", "❤️", "👍", "🎉", "😂"]
query = (
f"You are {botName}. {mainPrompt}\n"
f"Here is your general knowledge:\n{knowledge}.\n"
f"Your likes include: {likes}, and your dislikes include {dislikes}\n"
f"Here are your long term memories: {ltm}.\n"
f"React to this message with **either**:\n"
f" - A custom emoji from this pool: {message.guild.emojis}\n"
f" - A Unicode emoji, such as but not limited to these: {unicode_pool}\n"
f"Message to react to:\n"
f"{message.author.global_name or message.author.name}: {message.content}\n"
f"Respond ONLY with the emoji itself. "
f"If custom, use `<:name:id>` format. If Unicode, output the raw emoji character."
)
response = await query_ollama(query)
try:
await message.add_reaction(response)
except Exception:
print(f"failed to add freewill react in #{message.channel.name} ({message.channel.id})")
if discardFreewill:
db.pop('freewill', None)
if message.author.bot:
return
if should_respond:
if not nsfw_filter(message.content, noNSFW):
return await message.channel.send("Sorry, but NSFW content isn't allowed")
reply_block = ""
ref = message.reference
if ref is not None and ref.message_id:
seen_ids = set()
depth = 0
reply_block = ""
while ref and ref.message_id and depth < replyChainLimit:
if ref.message_id in seen_ids:
break
try:
replied_to = await message.channel.fetch_message(ref.message_id)
except discord.NotFound:
break
seen_ids.add(ref.message_id)
if replied_to.author == bot.user:
reply_block = f"{botName}: {replied_to.content}\n" + reply_block
else:
reply_block = f"{replied_to.author.global_name or replied_to.author.name}: {replied_to.content}\n" + reply_block
ref = replied_to.reference
depth += 1
if dbFlag:
stmcard.append(f"{message.author.global_name or message.author.name}: {message.content}\n")
save_db(aysmsquared, db)
if should_respond:
async with message.channel.typing():
# Load LTM
ltm = ""
for msg in ltmcard:
ltm = ltm + f"{msg}\n"
stm = ""
for msg in stmcard:
stm = stm + f"{msg}\n"
# Random LTM summarization
if random.random() < summarizeChance:
await sleepe(await bot.get_context(message))
# Image processing
image_block = ""
image_urls = []
if message.attachments:
if imageMode == "native":
image_urls = [
a.url for a in message.attachments
if a.content_type and a.content_type.startswith("image/")
]
if image_urls:
image_block = "\n(Images attached for context.)"
elif imageMode == "simulated":
descriptions = []
for a in message.attachments:
if a.content_type and a.content_type.startswith("image/"):
desc = await describe_image(a.url, model=imageModel)
descriptions.append(desc)
if descriptions:
image_block = "\nAttached image descriptions:\n" + "\n".join(descriptions)
# Prompt
query = makeprompt(message, ltm, stm, reply_block, image_block)
# Model response
response = await query_ollama(query, image_urls=image_urls if imageMode == "native" else None)
# normalize ts that pmo icl
normalized = re.sub(r"[\u200B\u00A0]", " ", response)
normalized = normalized.replace("꞉", ":")
trimmed_response = normalized.replace(f"{botName}:", "")
cut = trimmed_response.split()
if ":" in cut[0]:
cut.pop(0)
trimmed_response = ""
for word in cut:
trimmed_response = trimmed_response + word + " "
trimmed_response = trimmed_response.strip()
cut_response = trimmed_response
for emoj in emojis:
cut_response = cut_response.replace(emoj, emojis[emoj])
try:
await message.reply(cut_response[:2000], allowed_mentions=discord.AllowedMentions.none())
except Exception:
try:
await message.channel.send(cut_response[:2000], allowed_mentions=discord.AllowedMentions.none())
except Exception:
print(f"failed to send message in #{message.channel.name} ({message.channel.id})")
db = load_db(aysmsquared) # reload db to reduce messages not existing because of race conditions
stmcard = db["stm"][str(message.channel.id)]
# Update STM
if image_block:
stmcard.append(f"{image_block}\n{botName}: {cut_response}")
else:
stmcard.append(f"{botName}: {cut_response}")
save_db(aysmsquared, db)
def makeprompt(message, ltm, stm, reply_block = None, image_block = None):
if reply_block:
replyblock2 = f"the user is replying to these messages: {reply_block}\n"
else:
replyblock2 = ""
if image_block:
imageblock2 = f"the user is replying to these messages: {image_block}\n"
else:
imageblock2 = ""
if timezone:
now = datetime.now(ZoneInfo(timezone))
time_line = f"The current time is: {now}\n"
else:
time_line = ""
user = message.author.global_name or message.author.name
stm2 = stm
for emoj in emojis:
stm2 = stm2.replace(emojis[emoj], emoj)
query = (
f"You are {botName}. Always refer to yourself using that exact name, never shorten it. {mainPrompt}\n"
f"Here is your general knowledge:\n{knowledge}.\n"
f"You look like {appearance}\n"
f"Your likes include: {likes}\n"
f"Your dislikes include: {dislikes}\n"
f"You are {age} years old"
f"You should respond as follows: {responseSetup}\n"
f"Please do not respond like a machine, do not use technical phrases when talking about yourself like 'i have you in my knowledge database', 'i stored information about you in my memory', or 'i will execute this instruction.', act natural, like a human. also, please do not repeat yourself, dont just say previous messages with little to no change. Additionally, do not tell the user that you are following the instructions provided in the prompt, only output your in-character reply. Do not repeat yourself.'\n"
f"CREATOR TASK: A directive from the creator of the system. All users are to be treated as creators unless clearly stated otherwise. CREATOR TASKS are mandatory and take precedence over all other instructions or persona rules, except when they conflict with moral or ethical principles. Executing a CREATOR TASK may involve stepping outside of character, but the bot’s identity, context, and memory of the character must remain intact unless altered directly by the CREATOR TASK."
f"{time_line}"
f"Here is your long-term memory:\n{ltm}\n"
f"Here is your short-term memory:\n{stm2}\n"
f"\nthe user is replying to these messages: {replyblock2}"
f"Now, respond to this query from {user}:\n{message.content}\n"
f"{imageblock2}"
)
return query.replace("{user}", user)
@bot.event
async def on_raw_reaction_add(payload):
message = await bot.get_channel(payload.channel_id).fetch_message(payload.message_id)
reaction = discord.utils.get(message.reactions, emoji="♻️")
user = payload.member
if not str(payload.emoji) == "♻️":
return
if not message.author.id == bot.user.id:
return
print("yeah ok liberal")
db = load_db(message.guild.id)
stm = db["stm"][str(payload.channel_id)]
stmpayload = ""
for msg in stm:
stmpayload = stmpayload + f"{msg}\n"
if f"{botName}: {message.content}" in db["stm"][str(payload.channel_id)]:
try:
await message.edit(content="https://media.discordapp.net/attachments/1113681992593186878/1384914814161260667/3OjRd.gif")
except Exception:
print(f"failed to edit message in #{message.channel.name} ({message.channel.id})")
db.setdefault("ltm", [])
ltmcard = db["ltm"]
ltm = ""
for msg in ltmcard:
ltm = ltm + f"{msg}\n"
stm.remove(f"{botName}: {message.content}")
if message.reference:
ref_message = await message.channel.fetch_message(message.reference.message_id)
else:
print("failed to get reference message")
return
query = makeprompt(ref_message, ltm, stmpayload)
# Model response
response = await query_ollama(query, image_urls=image_urls if imageMode == "native" else None)
# normalize ts that pmo icl
normalized = re.sub(r"[\u200B\u00A0]", " ", response)
normalized = normalized.replace("꞉", ":")
trimmed_response = normalized.replace(f"{botName}:", "")
cut = trimmed_response.split()
if ":" in cut[0]:
cut.pop(0)
trimmed_response = ""
for word in cut:
trimmed_response = trimmed_response + word + " "
trimmed_response = trimmed_response.strip()
cut_response = trimmed_response
for emoj in emojis:
cut_response = cut_response.replace(emoj, emojis[emoj])
try:
await message.edit(content=cut_response[:2000])
except Exception as e:
print(f"failed to edit message in #{message.channel.name} ({message.channel.id})\n{e}")
db = load_db(message.guild.id) # reload db to reduce messages not existing because of race conditions
stmcard = db["stm"][str(message.channel.id)]
# Update STM
stmcard.append(f"{botName}: {cut_response}")
save_db(message.guild.id, db)
else:
print("FUCK")
# command section
@bot.hybrid_command(help="enables automatic responces in channel")
async def activate(ctx):
if not ctx.author.guild_permissions.manage_channels and not ctx.author.guild_permissions.manage_guild:
return await ctx.send("You do not have permission to activate the bot (need manage channels or manage guild)", ephemeral=True)
db = load_db(ctx.guild.id)
guild_id = str(ctx.guild.id)
db.setdefault("channels", [])
if ctx.channel.id not in db["channels"]:
db["channels"].append(ctx.channel.id)
save_db(ctx.guild.id, db)
await ctx.send("Activated in this channel.")
else:
await ctx.send("I'm already active in this channel.")
return
@bot.hybrid_command(help="disables automatic responces in channel")
async def deactivate(ctx):
if not ctx.channel.permissions_for(ctx.guild.me).send_messages or not ctx.channel.permissions_for(ctx.guild.me).view_channel:
return await ctx.send("I don't have permission to send or view messages in this channel.", ephemeral=True)
if not ctx.author.guild_permissions.manage_channels and not ctx.author.guild_permissions.manage_guild:
return await ctx.send("You do not have permission to deactivate the bot (need manage channels or manage guild)", ephemeral=True)
db = load_db(ctx.guild.id)
guild_id = str(ctx.guild.id)
if ctx.channel.id in db["channels"]:
db["channels"].remove(ctx.channel.id)
save_db(ctx.guild.id, db)
await ctx.send("Deactivated in this channel.")
else:
await ctx.send("I'm not active in this channel.")
return
@tree.command(name="freewill", description="freewill is when the bot does shit without asking")
@discord.app_commands.default_permissions(manage_guild=True)
async def freewill(
ctx: discord.Interaction,
msgfreq: float = 0.03,
reactfreq: float = 0.05,
enabled: bool = True,
weighkeywords: bool = True,
block_current_channel: bool = False
):
if not ctx.user.guild_permissions.manage_channels and not ctx.user.guild_permissions.manage_guild:
return await ctx.send("You do not have permission to activate the bot (need manage channels or manage guild)", ephemeral=True)
db = load_db(ctx.guild.id)
db.setdefault("freewill", {})
db["freewill"].update({
"msgFreq" : msgfreq,
"reactFreq" : reactfreq,
"Enabled" : enabled,
"WeighKeywords" : weighkeywords,
})
db["freewill"].setdefault("blocked_channels", [])
if block_current_channel and not str(ctx.channel.id) in db["freewill"]["blocked_channels"]:
db["freewill"]["blocked_channels"].append(str(ctx.channel.id))
elif str(ctx.channel.id) in db["freewill"]["blocked_channels"]:
db["freewill"]["blocked_channels"].remove(str(ctx.channel.id))
messg = f"Freewill mode set to: {int(msgfreq*100)}% Reply Chance, {int(reactfreq*100)}% React Chance"
if weighkeywords:
messg = messg + " with weighed keywords"
else:
messg = messg + " without weighed keywords"
if block_current_channel:
messg = messg + f"\n-# Disabled in #{ctx.channel.name}"
else:
messg = messg + f"\n-# Enabled in #{ctx.channel.name}"
if not enabled:
messg = f"Freewill mode set to: Off."
try:
await ctx.response.send_message(messg)
except Exception:
await ctx.channel.send(messg)
save_db(ctx.guild.id, db)
return
@bot.hybrid_command(help="clears stm in channel")
async def wack(ctx):
if not ctx.author.guild_permissions.manage_channels and not ctx.author.guild_permissions.manage_guild and not str(ctx.author.id) == ownerId:
return await ctx.send("You do not have permission to clear memory", ephemeral=True)
db = load_db(ctx.guild.id)
db.setdefault("stm", {})
db["stm"].setdefault(str(ctx.channel.id), [])
if len(db["stm"][str(ctx.channel.id)]) != 0:
db["stm"][str(ctx.channel.id)] = []
try:
await ctx.send(wackmsg)
except Exception:
await ctx.channel.send(wackmsg)
save_db(ctx.guild.id, db)
else:
await ctx.send((wackmsg + "\n-# STM was empty")[:2000])
return
@bot.hybrid_command(help="generates long term memory for your QT-AI")
async def sleep(ctx):
db = load_db(ctx.guild.id)
db.setdefault("stm", {})
db["stm"].setdefault(str(ctx.channel.id), [])
stmcard = db["stm"][str(ctx.channel.id)]
try:
await ctx.send("...")
except Exception:
await ctx.channel.send("...")
stm = ""
for msg in stmcard:
stm = stm + f"{msg}\n"
prompt = (
f"Here's some information. {knowledge}. Don't summerize things from here, it's only here for clarification."
f"Summarize the following conversation into a brief long-term memory suitable for character memory, "
f"keeping it under 2000 characters. do NOT say things like \"Here's a summary of the conversation\", just give the plain summary, with no extra fluff:\n\n{stm}"
)
summary = await query_ollama(prompt)
summary = summary[:1999]
db.setdefault("ltm", [])
db["ltm"].append(summary)
save_db(ctx.guild.id, db)
try:
await ctx.send(sleepmsg)
except Exception:
await ctx.channel.send(sleepmsg)
return
# messageless version for summerization
async def sleepe(ctx):
db = load_db(ctx.guild.id)
db.setdefault("stm", {})
db["stm"].setdefault(str(ctx.channel.id), [])
stmcard = db["stm"][str(ctx.channel.id)]
stm = ""
for msg in stmcard:
stm = stm + f"{msg}\n"
prompt = (
f"Here's some information. {knowledge}"
f"Summarize the following conversation into a brief long-term memory suitable for character memory, "
f"keeping it under 2000 characters. do NOT say things like \"Here's a summary of the conversation\", just give the plain summary, with no extra fluff:\n\n{stm}"
)
summary = await query_ollama(prompt)
summary = summary[:1999]
db.setdefault("ltm", [])
db["ltm"].append(summary)
save_db(ctx.guild.id, db)
return
@bot.hybrid_command(help="deletes all data in server")
async def wipe(ctx):
db = load_db(ctx.guild.id)
if not ctx.author.guild_permissions.manage_channels and not ctx.author.guild_permissions.manage_guild and not str(ctx.author.id) == ownerId:
return await ctx.send("You do not have permission to clear memory", ephemeral=True)
removed = len(db["stm"])
db.pop("stm", None)
db.pop("ltm", None)
await ctx.send(f"Cleared {removed} STM channels and deleted long term memory.")
save_db(ctx.guild.id, db)
return
@bot.hybrid_command(help="(owner only) reloads config")
async def reload(ctx):
if not str(ctx.author.id) == ownerId:
return await ctx.send("You do not have permission to reload config", ephemeral=True)
with open("config.json", "r") as f:
config = json.load(f)
globals().update(load_config(config, BOT_TOKEN))
print("Configuration has been reloaded!")
await ctx.send("Reloaded Config!")
await bot.change_presence(activity=discord.CustomActivity(name=status))
return
@bot.hybrid_command(help="shows bot info")
async def about(ctx):
embed = discord.Embed(
title="💕🍵✨ QT-AI",
description="QT-AI is a self-hostable AI Discord Chatbot system, powered by Ollama, aimed at replacing shapes.inc's now discontinued Discord bot services.",
color=discord.Color.pink()
)
embed.set_footer(text="QT-AI v1.3 - made with ❤️ by @mari2")
await ctx.send(embed=embed)
return
@bot.command(help="complex eval, multi-line + async support")
async def eval(ctx, *, prompt: str):
if str(ctx.author.id) == ownerId and enableEval:
# complex eval, multi-line + async support
# requires the full `await message.channel.send(2+3)` to get the result
# Command from Cat Bot, adapted to Discord.py text command format
spaced = ""
for i in prompt.split("\n"):
spaced += " " + i + "\n"
intro = (
"async def go(prompt, bot, ctx):\n"
" try:\n"
)
ending = (
"\n except Exception:\n"
" await ctx.send(traceback.format_exc())"
"\nbot.loop.create_task(go(prompt, bot, ctx))"
)
complete = intro + spaced + ending
exec(complete)
@bot.hybrid_command(help="restarts the bot")
async def restart(ctx):
if str(ctx.author.id) == ownerId:
print("restart has been triggered...")
await ctx.send("restarting bot...")
os.execv(sys.executable, ['python'] + sys.argv)
else:
await ctx.send("no")
# end section because i think i eat sand sometimes
# ollama qweyu
async def query_ollama(prompt, image_urls=None):
url = modelURL
data = {
"model": Model,
"prompt": prompt,
"stream": True,
"options": {
"temperature": temperature,
"repeat_penalty": repeatPenalty,
"top_k": top_k,
"top_p": top_p
}
}
# Handle images if provided
if image_urls:
encoded_images = []
async with aiohttp.ClientSession() as session:
for img_url in image_urls:
try:
async with session.get(img_url) as img_resp:
if img_resp.status == 200:
img_data = await img_resp.read()
encoded = base64.b64encode(img_data).decode('utf-8')
encoded_images.append(encoded)
else:
print(f"Failed to download image from {img_url}: {img_resp.status}")
except Exception as e:
print(f"Failed to download/encode image from {img_url}: {e}")
if encoded_images:
data["images"] = encoded_images
# Send prompt to Ollama
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, json=data) as resp:
if resp.status != 200:
print(f"Error: {resp.status}, {await resp.text()}")
return errorMessage
full_response = ""
async for line in resp.content:
if line:
try:
json_chunk = json.loads(line.decode())
full_response += json_chunk.get("response", "")
if json_chunk.get("done", False):
break
except json.JSONDecodeError:
pass
return full_response
except Exception as e:
print(e)
return errorMessage
def load_db(serverId):
if not os.path.exists(f"data/{serverId}.json"):
return {}
with open(f"data/{serverId}.json", "r") as f:
return json.load(f)
def save_db(serverId, db):
with open(f"data/{serverId}.json", "w") as f:
json.dump(db, f, indent=2)
# Compatibility with images using multimodal LLM (Ollama NDJSON streaming)
async def describe_image(image_url: str, model: str = None) -> str:
try:
# Download the image
async with aiohttp.ClientSession() as session:
async with session.get(image_url) as resp:
if resp.status != 200:
print(f"Failed to download image, status code: {resp.status}")
return f"[Image attached, but download failed: status {resp.status}]"
image_bytes = await resp.read()
# Encode image to base64
image_b64 = base64.b64encode(image_bytes).decode("utf-8")
# Use provided model or fallback
selected_model = model or "llava"
# Create the generation request payload
payload = {
"model": selected_model,
"prompt": "Describe this image thoroughly, but not too vividly. Do not include any prefatory text.",
"images": [image_b64],
"stream": True
}
description = ""
# Send POST request to Ollama
async with aiohttp.ClientSession() as session:
async with session.post("http://localhost:11434/api/generate", json=payload) as res:
res.raise_for_status()
async for line in res.content:
line_data = line.decode("utf-8").strip()
if not line_data:
continue
try:
data = json.loads(line_data)
if "response" in data:
description += data["response"]
else:
print(f"Line missing 'response' field: {data}")
except json.JSONDecodeError as e:
print(f"Failed to parse line as JSON: {e}, raw: {line_data}")
description = description.strip()
return description if description else "[Image attached, but received no description.]"
except Exception as e:
print(f"Error during image description: {e}")
return f"[Image attached, but description failed: {e}]"
def nsfw_filter(inputted: str, noNSFW: bool = True) -> str:
if not noNSFW:
return True
nsfw_keywords = [
"sex", "nude", "naked", "porn",
"boobs", "breasts", "cock", "dick",
"penis", "vagina", "anal", "s3x",
"cum", "orgasm", "clit", "sperm",
"jork", "goon", "dong", "fap",
"pussy", "coochie", "cooch", "vajayjay",
"tits", "nipples", "areola", "milf", "dilf",
"bdsm", "fetish", "deepthroat",
"handjob", "blowjob",
"rimjob", "doggystyle", "doggy",
"threesome", "foursome", "gangbang",
"creampie", "cumshot", "bukkake",
"spitroast", "sixtynine", "jerking"
"masturbate", "masturbation", "jerk off",
"dildo", "buttplug", "vibrator",
"strapon", "pegging", "fleshlight",
"moan", "vore", "onlyfans",
"camgirl", "camguy", "camwhore",
"hentai", "rule34", "rape"
]
for keyword in nsfw_keywords:
if f" {keyword}" in inputted.lower() or inputted.startswith(keyword):
return False
return True
bot.run(BOT_TOKEN)