Author SHA1 Message Date
AllfatherHatt bee49ec40c Merge branch 'dev' of https://manufactorum.kanium.org/Kanium-PUBLIC/KaniumCogs into dev 2026-02-04 11:28:09 +01:00
AllfatherHatt 6267b1380b Whatever this is 2026-02-04 11:26:51 +01:00
T-BENZIN 90d5dd973c Added demo bot for testing. Supports image input, but does not have dialog memory or tools usage yet. 2025-08-27 21:14:17 +05:00
T-BENZIN f195d77e67 Made Discord bot service for getting llm response out of Discord message 2025-08-27 21:13:04 +05:00
T-BENZIN 92f536d407 Fixed local import 2025-08-25 20:47:01 +05:00
T-BENZIN a322fbae84 Renamed adapter class to MessengerClientMessageAdapter for clarity 2025-08-25 19:09:44 +05:00
T-BENZIN bd6a55cd85 Created DiscordMessageAdapter for creating ClientMessage instance instead of a builder's class method 2025-08-25 12:32:35 +05:00
T-BENZIN 4fd5e06eaa Purged unused imports 2025-08-24 20:01:21 +05:00
T-BENZIN 1f7aa0a5ee Merge remote-tracking branch 'origin/dev' into dev 2025-08-24 19:59:31 +05:00
T-BENZIN 3b6fc28d4c Added ClientMessage -> OpenAIMessage object adapter 2025-08-24 19:59:21 +05:00
T-BENZIN c024d85db5 Added ClientMessage -> OpenAIMessage object adapter 2025-08-24 19:59:07 +05:00
T-BENZIN a5bfccb19a Added OpenAI response -> OpenAIMessage object adapter 2025-08-24 19:43:02 +05:00
T-BENZIN 7dc1d485b1 Finished some basic OpenAI interaction. Next are adapters. 2025-08-24 18:26:08 +05:00
T-BENZIN 8255d54e56 Added empty attachments list for test message 2025-08-24 18:25:16 +05:00
T-BENZIN 37beca0dd6 Modified typing for InputImage 2025-08-24 18:24:27 +05:00
T-BENZIN 087566811a Added __init__ to Message Builder interface 2025-08-17 15:24:01 +05:00
T-BENZIN 095bd828cf Added client message builder 2025-08-17 15:20:32 +05:00
T-BENZIN 0387dafef8 Removed openai test run code 2025-08-15 12:58:37 +05:00
T-BENZIN 0e2becc212 Commented out non-functional code 2025-08-15 12:37:57 +05:00
T-BENZIN b69f169892 Merge remote-tracking branch 'origin/dev' into dev 2025-08-15 12:34:55 +05:00
T-BENZIN 40b3b900ac Wrong apostrophe character in comments 2025-08-15 12:34:41 +05:00
T-BENZIN 73bf08843f Update reginaldCog/messenger_clients/discord_data_models.py 2025-08-15 09:33:05 +02:00
T-BENZIN d2edf0e60d Delete reginaldCog/messenger_clients/_common.py 2025-08-15 09:32:25 +02:00
T-BENZIN bd4b05d2d4 Delete reginaldCog/llm_clients/discord_client_interfaces.py 2025-08-15 09:32:03 +02:00
T-BENZIN eb7733be69 Removed non-finished code 2025-08-15 12:28:40 +05:00
T-BENZIN 131999816b File structure refactor 2025-08-15 12:28:39 +05:00
T-BENZIN ff70196756 File structure refactor 2025-08-15 11:09:40 +05:00
T-BENZIN 180c167a43 File structure refactor 2025-08-15 11:01:21 +05:00
T-BENZIN 75af912bf5 File_structure refactor 2025-08-15 10:41:35 +05:00
T-BENZIN a64a07511d Commented out send_long_message method and auto PEP-8 reginald.py 2025-07-18 14:31:51 +05:00
T-BENZIN 9209cc568d Made Prompt dataclass immutable and got rid out of add_message method. openai_client\models.py's test run would remain broken for now 2025-07-18 14:28:23 +05:00
T-BENZIN 7056315d5f Added llm_interface.py for connecting Discord bot with LLMs (only Open AI at the moment) 2025-07-18 14:26:35 +05:00
T-BENZIN b77dc31ea5 Added Response dataclass for better openai's response deserialization. 2025-07-14 20:28:00 +05:00
T-BENZIN ad59a695af Experimented with more convenient (although, less explicit) way of passing data into abstract dataclasses. 2025-07-13 19:47:37 +05:00
T-BENZIN 89b98fc5af Experimented with more convenient (although, less explicit) way of passing data into abstract dataclasses. 2025-07-13 19:45:09 +05:00
T-BENZIN 97252a8062 Added models.py in openai_client containing abstract dataclasses for use with openai
Moved all dataclasses to .openai_client.models.py
Made prompt into its own dataclass
Removed to_dict methods because dataclasses/asdict seems to be sufficient
2025-07-11 16:59:20 +05:00
T-BENZIN 0534ec6b15 Added models.py containing abstract dataclasses for Discord 2025-07-10 21:22:52 +05:00
T-BENZIN 11f39bb673 Added package structure for future use 2025-07-10 20:52:21 +05:00
T-BENZIN 247e4417f5 First attempt at making openai stuff pretty. As it uses replies instead of completions, update of openai library is required. 2025-07-05 18:16:48 +05:00
T-BENZIN bfe22e40ee First attempt at making openai stuff pretty. As it uses replies instead of completions, update of openai library is required. 2025-07-05 18:14:49 +05:00
T-BENZIN 59902085b3 First attempt at making openai stuff pretty. As it uses replies instead of completions, update of openai library is required. 2025-07-05 17:48:36 +05:00
T-BENZIN 3d59e45e7e First attempt at making openai stuff pretty. As it uses replies instead of completions, update of openai library is required. 2025-07-05 17:46:13 +05:00
20 changed files with 897 additions and 759 deletions
-1
View File
@@ -2,7 +2,6 @@
cogs made for our Royal butt. cogs made for our Royal butt.
## Our Cogs: ## Our Cogs:
- [FitnessCog](./fitnessCog)
- [RecruitmentCog](./recruitmentCog/) - [RecruitmentCog](./recruitmentCog/)
- [ReginaldCog](./reginaldCog/) - [ReginaldCog](./reginaldCog/)
- [TrafficCog](./trafficCog) - [TrafficCog](./trafficCog)
-6
View File
@@ -1,6 +0,0 @@
from redbot.core.bot import Red
from .fitness import FitnessCog
async def setup(bot: Red):
cog = FitnessCog(bot)
await bot.add_cog(cog)
-52
View File
@@ -1,52 +0,0 @@
{
"convertable": true,
"units": {
"meter": {
"factor": 1,
"aliases": [
"meter",
"meters",
"metre",
"metres",
"m",
"m."
]
},
"kilometer": {
"factor": 1000,
"aliases": [
"kilometer",
"kilometers",
"kilometre",
"kilometres",
"km",
"km."
]
},
"foot": {
"factor": 0.3048,
"aliases": [
"foot",
"feet",
"ft",
"ft."
]
},
"mile": {
"factor": 1609.344,
"aliases": [
"mile",
"miles",
"mi",
"mi."
]
},
"step": {
"factor": 0.18,
"aliases": [
"step",
"steps"
]
}
}
}
-3
View File
@@ -1,3 +0,0 @@
{
"convertable": false
}
-105
View File
@@ -1,105 +0,0 @@
import csv
import json
from pathlib import Path
from typing import Optional
def activity_log_path(activity: str, logs_dir: Optional[Path] = None) -> Path:
"""
Returns the path of the activity log file in .csv format.
"""
logs_dir = logs_dir or (Path.cwd() / "activity_logs")
return logs_dir / f"{activity}.csv"
def activity_units_path(activity: str, units_dir: Optional[Path] = None) -> Path:
"""
Returns the path of the activity units file in .json format.
"""
units_dir = units_dir or (Path.cwd() / "activities")
return units_dir / f"{activity}.json"
def is_convertable(activity: str, units_dir: Optional[Path] = None) -> bool:
filename = activity_units_path(activity, units_dir)
with filename.open("r", encoding="utf-8") as f:
raw_data = json.load(f)
return bool(raw_data.get("convertable"))
def create_activity_log_file(
activity: str,
*,
units_dir: Optional[Path] = None,
logs_dir: Optional[Path] = None,
) -> None:
if not activity_units_path(activity, units_dir).exists():
raise ValueError(f"{activity} is not a valid activity")
logs_dir = logs_dir or (Path.cwd() / "activity_logs")
logs_dir.mkdir(parents=True, exist_ok=True)
filename = activity_log_path(activity, logs_dir)
if filename.exists():
return # don't re-add headers
with filename.open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["timestamp", "username", "value"])
def convert_units(
activity: str,
value: int | float,
unit: str | None,
*,
units_dir: Optional[Path] = None,
) -> float:
filename = activity_units_path(activity, units_dir)
if not filename.exists():
raise ValueError(f"{activity} is not a valid activity")
# Consider None unit value as factor of 1
if unit is None:
return float(value)
with filename.open("r", encoding="utf-8") as f:
raw_data = json.load(f)
units_data = raw_data.get("units") or {}
unit_l = unit.lower()
for _, data in units_data.items():
aliases = [a.lower() for a in (data.get("aliases") or [])]
if unit_l in aliases:
return float(value) * float(data["factor"])
raise ValueError(f"{unit} is not a valid unit")
def log_activity(
timestamp: int,
username: str,
activity: str,
value: int | float,
unit: str | None,
*,
units_dir: Optional[Path] = None,
logs_dir: Optional[Path] = None,
) -> None:
if not isinstance(value, (int, float)) or value <= 0:
raise ValueError(f"{value} is not a valid value")
filename = activity_log_path(activity, logs_dir)
if not filename.exists():
create_activity_log_file(activity, units_dir=units_dir, logs_dir=logs_dir)
if is_convertable(activity, units_dir):
converted_value = round(convert_units(activity, value, unit, units_dir=units_dir), 2)
else:
converted_value = round(float(value), 2)
with filename.open("a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([timestamp, username, converted_value])
-143
View File
@@ -1,143 +0,0 @@
import os
from pathlib import Path
import discord
from redbot.core import commands
from redbot.core.data_manager import cog_data_path
from .activity_logger import log_activity
class FitnessCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
default_threads = "1457402451530350727,1328363409648910356"
threads_raw = os.getenv("THREADS_ID", default_threads)
self.threads_id: list[int] = []
for x in threads_raw.split(","):
x = x.strip()
if x.isdigit():
self.threads_id.append(int(x))
self.confirm_reactions = os.getenv("CONFIRMATION_REACTIONS", "🐈💨")
# Units are shipped with the cog in: fitnessCog/activities/*.json
self.units_dir: Path = Path(__file__).parent / "activities"
# Logs are writable and belong in Red's data dir
self.logs_dir: Path = cog_data_path(self) / "activity_logs"
self.logs_dir.mkdir(parents=True, exist_ok=True)
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
if message.author.bot:
return
if message.channel.id not in self.threads_id:
return
content = (message.content or "").strip()
if not content.startswith("!"):
return
cmdline = content[1:].strip().lower()
if not cmdline:
return
cmd, *rest = cmdline.split(" ", 1)
arg = rest[0].strip() if rest else ""
if cmd == "getunits":
await self.get_units_file(message, arg)
return
if cmd == "getlog":
await self.get_log_file(message, arg)
return
await self.log_fitness(message)
async def get_units_file(self, message: discord.Message, activity: str):
try:
if not activity:
await message.channel.send(
"Usage: `!getunits <activity>` (example: `!getunits pushups`)"
)
return
activity = activity.lower().strip()
path = self.units_dir / f"{activity}.json"
if not path.exists():
await message.channel.send(f"No units JSON found for `{activity}`.")
return
await message.channel.send(file=discord.File(fp=str(path)))
except Exception as e:
await message.channel.send(str(e))
async def get_log_file(self, message: discord.Message, activity: str):
try:
if not activity:
await message.channel.send(
"Usage: `!getlog <activity>` (example: `!getlog pushups`)"
)
return
activity = activity.lower().strip()
path = self.logs_dir / f"{activity}.csv"
if not path.exists():
await message.channel.send(f"No log CSV found for `{activity}`.")
return
await message.channel.send(file=discord.File(fp=str(path)))
except Exception as e:
await message.channel.send(str(e))
async def log_fitness(self, message: discord.Message):
try:
parts = message.content[1:].strip().split()
if len(parts) < 2:
await message.reply(
"Usage: `!<activity> <value> [unit]` (example: `!pushups 20` or `!run 5 km`)"
)
return
activity = parts[0]
try:
value = float(parts[1])
except ValueError:
await message.reply(
"Invalid number. Usage: `!<activity> <value> [unit]` (example: `!run 5 km`)"
)
return
unit = parts[2] if len(parts) > 2 else "m"
timestamp = int(message.created_at.timestamp())
username = message.author.name
log_activity(
timestamp,
username,
activity,
value,
unit,
units_dir=self.units_dir,
logs_dir=self.logs_dir,
)
for r in self.confirm_reactions:
await message.add_reaction(r)
except Exception as e:
await message.reply(str(e))
def setup(bot):
bot.add_cog(FitnessCog(bot))
+7 -16
View File
@@ -1,24 +1,15 @@
import functools
import inspect
def debug(func): def debug(func):
if inspect.iscoroutinefunction(func):
@functools.wraps(func)
async def wrap(*args, **kwargs):
print(f"DEBUG: Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
result = await func(*args, **kwargs)
print(f"DEBUG: {func.__name__} returned: {result}")
return result
return wrap
@functools.wraps(func)
def wrap(*args, **kwargs): def wrap(*args, **kwargs):
# Log the function name and arguments
print(f"DEBUG: Calling {func.__name__} with args: {args}, kwargs: {kwargs}") print(f"DEBUG: Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
# Call the original function
result = func(*args, **kwargs) result = func(*args, **kwargs)
# Log the return value
print(f"DEBUG: {func.__name__} returned: {result}") print(f"DEBUG: {func.__name__} returned: {result}")
# Return the result
return result return result
return wrap return wrap
+38
View File
@@ -0,0 +1,38 @@
import os
import discord
from discord.ext import commands
from reginaldCog.messenger_clients.services import MessageService
TOKEN = os.getenv('SCREAMING_OPOSSUM') # Your Discord bot token goes here
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} command(s).')
except Exception as e:
print(f'Failed to sync commands: {e}')
@bot.event
async def on_message(message: discord.Message):
if message.author == bot.user:
return
async with message.channel.typing():
message_service = MessageService(message)
response = await message_service.get_llm_response()
await message.channel.send(response)
print(response)
if __name__ == '__main__':
if TOKEN is None:
raise RuntimeError('Discord token is not set')
bot.run(TOKEN)
View File
+192
View File
@@ -0,0 +1,192 @@
from abc import ABC, abstractmethod
from enum import Enum
from openai import OpenAI
from discord import Message
from reginaldCog.messenger_clients.messenger_client import ClientMessage, DiscordMessageAdapter
class ILLMContent(ABC):
pass
class OpenAIContent(ILLMContent):
def __init__(self):
self._content_items: list[dict[str, str]] = []
@property
def content_items(self) -> list[dict]:
return self._content_items
@content_items.setter
def content_items(self, value: list[dict[str, str]]):
self._content_items = value
class ILLMContentBuilder(ABC):
pass
class OpenAIContentBuilder(ILLMContentBuilder):
def __init__(self, content: OpenAIContent):
self.content = content
def add_output_text(self, text: str):
item = {"type": "output_text", "text": text}
self.content.content_items.append(item)
return self
def add_input_text(self, text: str):
item = {"type": "input_text", "text": text}
self.content.content_items.append(item)
return self
def add_input_image(self, image_url: str):
item = {"type": "input_image", "image_url": image_url}
self.content.content_items.append(item)
return self
def add_from_dict(self, item: dict):
self.content.content_items.append(item)
return self
class ILLMMessage(ABC):
pass
class OpenAIMessage(ILLMMessage):
def __init__(self):
self.content = OpenAIContent()
self.role = ""
@property
def to_dict(self):
return {"role": self.role, "content": self.content.content_items}
class ILLMMessageBuilder(ABC):
pass
class OpenAIMessageBuilder(ILLMMessageBuilder):
def __init__(self, message: OpenAIMessage):
self.message = message
def set_role(self, role: str):
self.message.role = role
return self
def set_content(self, content: OpenAIContent):
self.message.content = content
return self
class ILLMPrompt(ABC):
pass
class OpenAIPrompt(ILLMPrompt):
def __init__(self):
self.messages = []
@property
def to_list(self):
return [i_message.to_dict for i_message in self.messages]
class ILLMPromptBuilder(ABC):
@abstractmethod
def __init__(self, prompt: ILLMPrompt):
pass
@abstractmethod
def add_message(self, message: ILLMMessage):
pass
class OpenAIPromptBuilder(ILLMPromptBuilder):
def __init__(self, prompt: OpenAIPrompt):
self.prompt = prompt
def add_message(self, message: OpenAIMessage):
self.prompt.messages.append(message)
class ILLMClient(ABC):
@abstractmethod
def get_response(self, prompt: ILLMPrompt):
pass
class OpenAIClient(ILLMClient):
content_class = OpenAIContent
content_builder_class = OpenAIContentBuilder
message_class = OpenAIMessage
message_builder_class = OpenAIMessageBuilder
prompt_class = OpenAIPrompt
prompt_builder_class = OpenAIPromptBuilder
def __init__(self):
self.model = 'gpt-4.1-mini'
self.client = OpenAI()
def get_response(self, prompt: OpenAIPrompt):
response_input = {"model": self.model, "input": prompt.to_list}
return self.client.responses.create(**response_input)
class IMessageAdapter(ABC):
@abstractmethod
def to_message(self) -> ILLMMessage:
pass
class OpenAIResponseAdapter(IMessageAdapter):
def __init__(self, response):
self.response = response
self.response_output = response.output[0]
def to_message(self) -> OpenAIMessage:
content = OpenAIContent()
content_builder = OpenAIContentBuilder(content)
message = OpenAIMessage()
message_builder = OpenAIMessageBuilder(message)
message_builder.set_role(self.response_output.role)\
.set_content(content)
for i_content_item in self.response_output.content:
item = i_content_item.to_dict()
content_builder.add_from_dict(item)
return message
class LMMClientType(Enum):
OPENAI = OpenAIClient
class MessengerClientMessageAdapter(IMessageAdapter):
def __init__(self, message: ClientMessage, llm_client: LMMClientType):
self.message = message
self.llm_client = llm_client
def to_message(self) -> ILLMMessage:
content = self.llm_client.value.content_class()
content_builder = self.llm_client.value.content_builder_class(content)
message = self.llm_client.value.message_class()
message_builder = self.llm_client.value.message_builder_class(message)
message_builder.set_role("user")\
.set_content(content)
if self.message:
content_builder.add_input_text(self.message.content)
for i_image_url in self.message.image_urls:
content_builder.add_input_image(i_image_url)
return message
if __name__ == "__main__":
pass
@@ -0,0 +1,71 @@
from dataclasses import dataclass, field
from abc import ABC
# region Content classes
@dataclass(frozen=True)
class Content(ABC):
type: str = field(init=False, default='')
@dataclass(frozen=True)
class InputText(Content):
type: str = field(init=False, default='input_text')
text: str
@dataclass(frozen=True)
class OutputText(Content):
type: str = field(init=False, default='output_text')
text: str
@dataclass(frozen=True)
class InputImage(Content):
type: str = field(init=False, default='input_image')
image_url: str | None = field(default=None)
file_id: str | None = field(default=None)
def __post_init__(self):
if self.image_url is None and self.file_id is None:
raise ValueError('Either `image_url` or `file_id` must be provided.')
@dataclass(frozen=True)
class UrlCitation(Content):
type: str = field(init=False, default='url_citation')
# To be done
@dataclass(frozen=True)
class FunctionCall(Content):
type: str = field(init=False, default='function_call')
id: str
call_id: str
name: str
arguments: dict
@dataclass(frozen=True)
class FunctionCallOutput(Content):
type: str = field(init=False, default='function_call_output')
call_id: str
output: str
# endregion Content classes
@dataclass(frozen=True)
class Message:
role: str
content: list[Content]
@dataclass(frozen=True)
class Prompt:
model: str
input: list[Message]
@dataclass(frozen=True)
class Response:
output: list[Message]
+138 -136
View File
@@ -1,93 +1,101 @@
import datetime
import random
import re import re
from collections import Counter import random
import datetime
import discord import discord
import openai import openai
from collections import Counter
from redbot.core import commands, Config
from openai import OpenAIError from openai import OpenAIError
from redbot.core import commands
class MemoryMixin: class MemoryMixin:
"""Handles all memory-related functions for Reginald.""" """Handles all memory-related functions for Reginald."""
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs) # ✅ Ensure cooperative MRO initialization
self.short_term_memory_limit = 50 self.short_term_memory_limit = 50
self.summary_retention_limit = 25 self.summary_retention_limit = 25
self.summary_retention_ratio = 0.8 self.summary_retention_ratio = 0.8
@commands.command(name="reginald_clear_short", help="Clears short-term memory for this channel.") @commands.command(name="reginald_clear_short", help="Clears short-term memory for this channel.")
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def clear_short_memory(self, ctx): async def clear_short_memory(self, ctx):
"""Clears short-term memory for this channel."""
async with self.config.guild(ctx.guild).short_term_memory() as short_memory: async with self.config.guild(ctx.guild).short_term_memory() as short_memory:
short_memory[str(ctx.channel.id)] = [] short_memory[ctx.channel.id] = []
await ctx.send("Short-term memory for this channel has been cleared.") await ctx.send("Short-term memory for this channel has been cleared.")
@commands.command(name="reginald_set_limit", help="Set the short-term memory message limit.") @commands.command(name="reginald_set_limit", help="Set the short-term memory message limit.")
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def set_short_term_memory_limit(self, ctx, limit: int): async def set_short_term_memory_limit(self, ctx, limit: int):
"""Allows an admin to change the short-term memory limit dynamically."""
if limit < 5: if limit < 5:
await ctx.send("The short-term memory limit must be at least 5.") await ctx.send("⚠️ The short-term memory limit must be at least 5.")
return return
self.short_term_memory_limit = limit self.short_term_memory_limit = limit
await ctx.send(f"Short-term memory limit set to {limit} messages.") await ctx.send(f"✅ Short-term memory limit set to {limit} messages.")
@commands.command(name="reginald_memory_limit", help="Displays the current short-term memory message limit.") @commands.command(name="reginald_memory_limit", help="Displays the current short-term memory message limit.")
async def get_short_term_memory_limit(self, ctx): async def get_short_term_memory_limit(self, ctx):
await ctx.send(f"Current short-term memory limit: {self.short_term_memory_limit} messages.") """Displays the current short-term memory limit."""
await ctx.send(f"📏 **Current Short-Term Memory Limit:** {self.short_term_memory_limit} messages.")
@commands.command(name="reginald_clear_mid", help="Clears mid-term memory (summarized logs).") @commands.command(name="reginald_clear_mid", help="Clears mid-term memory (summarized logs).")
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def clear_mid_memory(self, ctx): async def clear_mid_memory(self, ctx):
async with self.config.guild(ctx.guild).mid_term_memory() as mid_memory: async with self.config.guild(ctx.guild).mid_term_memory() as mid_memory:
mid_memory[str(ctx.channel.id)] = [] mid_memory[ctx.channel.id] = ""
await ctx.send("Mid-term memory for this channel has been cleared.") await ctx.send("Mid-term memory for this channel has been cleared.")
@commands.command(name="reginald_summary", help="Displays a selected mid-term summary for this channel.") @commands.command(name="reginald_summary", help="Displays a selected mid-term summary for this channel.")
async def get_mid_term_summary(self, ctx, index: int): async def get_mid_term_summary(self, ctx, index: int):
"""Fetch and display a specific mid-term memory summary by index."""
async with self.config.guild(ctx.guild).mid_term_memory() as mid_memory: async with self.config.guild(ctx.guild).mid_term_memory() as mid_memory:
summaries = mid_memory.get(str(ctx.channel.id), []) summaries = mid_memory.get(str(ctx.channel.id), [])
if not isinstance(summaries, list):
summaries = []
# Check if there are summaries
if not summaries: if not summaries:
await ctx.send("No summaries available for this channel.") await ctx.send("⚠️ No summaries available for this channel.")
return return
# Validate index (1-based for user-friendliness)
if index < 1 or index > len(summaries): if index < 1 or index > len(summaries):
await ctx.send(f"Invalid index. Please provide a number between 1 and {len(summaries)}.") await ctx.send(f"⚠️ Invalid index. Please provide a number between **1** and **{len(summaries)}**.")
return return
selected_summary = summaries[index - 1] # Fetch the selected summary
selected_summary = summaries[index - 1] # Convert to 0-based index
# Format output correctly
formatted_summary = ( formatted_summary = (
f"Summary {index} of {len(summaries)}\n" f"📜 **Summary {index} of {len(summaries)}**\n"
f"Date: {selected_summary.get('timestamp', 'Unknown')}\n" f"📅 **Date:** {selected_summary['timestamp']}\n"
f"Topics: {', '.join(selected_summary.get('topics', [])) or 'None'}\n" f"🔍 **Topics:** {', '.join(selected_summary['topics']) or 'None'}\n"
f"Summary:\n\n{selected_summary.get('summary', '')}" f"📝 **Summary:**\n\n"
f"{selected_summary['summary']}"
) )
await self.send_long_message(ctx, formatted_summary) await self.send_long_message(ctx, formatted_summary)
@commands.command(name="reginald_summaries", help="Lists available summaries for this channel.") @commands.command(name="reginald_summaries", help="Lists available summaries for this channel.")
async def list_mid_term_summaries(self, ctx): async def list_mid_term_summaries(self, ctx):
"""Displays a brief list of all available mid-term memory summaries."""
async with self.config.guild(ctx.guild).mid_term_memory() as mid_memory: async with self.config.guild(ctx.guild).mid_term_memory() as mid_memory:
summaries = mid_memory.get(str(ctx.channel.id), []) summaries = mid_memory.get(str(ctx.channel.id), [])
if not isinstance(summaries, list):
summaries = []
if not summaries: if not summaries:
await ctx.send("No summaries available for this channel.") await ctx.send("⚠️ No summaries available for this channel.")
return return
summary_list = "\n".join( summary_list = "\n".join(
f"{i + 1}. {entry.get('timestamp', 'Unknown')} | Topics: {', '.join(entry.get('topics', [])) or 'None'}" f"**{i+1}.** 📅 {entry['timestamp']} | 🔍 Topics: {', '.join(entry['topics']) or 'None'}"
for i, entry in enumerate(summaries) for i, entry in enumerate(summaries)
) )
await ctx.send(f"Available summaries:\n{summary_list[:2000]}") await ctx.send(f"📚 **Available Summaries:**\n{summary_list[:2000]}")
@commands.command(name="reginald_clear_long", help="Clears all long-term stored knowledge.") @commands.command(name="reginald_clear_long", help="Clears all long-term stored knowledge.")
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@@ -110,14 +118,8 @@ class MemoryMixin:
@commands.command(name="reginald_recall", help="Recalls what Reginald knows about a user.") @commands.command(name="reginald_recall", help="Recalls what Reginald knows about a user.")
async def recall_user(self, ctx, user: discord.User): async def recall_user(self, ctx, user: discord.User):
async with self.config.guild(ctx.guild).long_term_profiles() as long_memory: async with self.config.guild(ctx.guild).long_term_profiles() as long_memory:
profile = long_memory.get(str(user.id), {}) profile = long_memory.get(str(user.id), {}).get("summary", "No stored information on this user.")
facts = profile.get("facts", []) await ctx.send(f"📜 **Memory Recall for {user.display_name}:** {profile}")
if facts:
recall_lines = [f"- {fact.get('fact', '')}" for fact in facts[:10]]
await ctx.send(f"Memory recall for {user.display_name}:\n" + "\n".join(recall_lines))
else:
await ctx.send(f"No stored information on {user.display_name}.")
@commands.command(name="reginald_forget", help="Forgets a specific user's long-term profile.") @commands.command(name="reginald_forget", help="Forgets a specific user's long-term profile.")
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@@ -130,153 +132,153 @@ class MemoryMixin:
await ctx.send(f"No stored knowledge about {user.display_name} to delete.") await ctx.send(f"No stored knowledge about {user.display_name} to delete.")
async def summarize_memory(self, ctx, messages): async def summarize_memory(self, ctx, messages):
"""✅ Generates a structured, compact summary of past conversations for mid-term storage."""
summary_prompt = ( summary_prompt = (
"Summarize the following conversation into a structured, concise format that retains key details while maximizing brevity. " "Summarize the following conversation into a structured, concise format that retains key details while maximizing brevity. "
"Organize into sections: Key Takeaways, Disputed Points, Notable User Contributions, and Additional Context. " "The summary should be **organized** into clear sections: "
"Avoid repetition while preserving essential meaning." "\n\n📌 **Key Takeaways:** Important facts or conclusions reached."
"\n🔹 **Disputed Points:** Areas where opinions or facts conflicted."
"\n🗣️ **Notable User Contributions:** Key statements from users that shaped the discussion."
"\n📜 **Additional Context:** Any other relevant information."
"\n\nEnsure the summary is **dense but not overly verbose**. Avoid unnecessary repetition while keeping essential meaning intact."
) )
summary_text = "\n".join(f"{msg.get('user', 'Unknown')}: {msg.get('content', '')}" for msg in messages) summary_text = "\n".join(f"{msg['user']}: {msg['content']}" for msg in messages)
try: try:
api_key = await self.config.guild(ctx.guild).openai_api_key() api_key = await self.config.guild(ctx.guild).openai_api_key()
if not api_key: if not api_key:
print("🛠️ DEBUG: No API key found for summarization.")
return ( return (
"It appears that I have not been furnished with the necessary credentials to carry out this task. " "It appears that I have not been furnished with the necessary credentials to carry out this task. "
"Might I suggest consulting an administrator to rectify this unfortunate oversight?" "Might I suggest consulting an administrator to rectify this unfortunate oversight?"
) )
model = await self.config.openai_model() or "gpt-4o-mini" client = openai.AsyncClient(api_key=api_key)
client = openai.AsyncOpenAI(api_key=api_key)
response = await client.chat.completions.create( response = await client.chat.completions.create(
model=model, model="gpt-4o-mini",
messages=[ messages=[
{"role": "system", "content": summary_prompt}, {"role": "system", "content": summary_prompt},
{"role": "user", "content": summary_text}, {"role": "user", "content": summary_text}
], ],
max_tokens=2048, max_tokens=2048
) )
summary_content = (response.choices[0].message.content or "").strip() summary_content = response.choices[0].message.content.strip()
if not summary_content: if not summary_content:
print("🛠️ DEBUG: Empty summary received from OpenAI.")
return ( return (
"Ah, an unusual predicament indeed. It seems that my attempt at summarization has resulted in " "Ah, an unusual predicament indeed! It seems that my attempt at summarization has resulted in "
"a void of information. I shall endeavor to be more verbose next time." "a void of information. I shall endeavor to be more verbose next time."
) )
return summary_content return summary_content
except OpenAIError as error: except OpenAIError as e:
error_message = f"OpenAI Error: {error}" error_message = f"OpenAI Error: {e}"
print(f"🛠️ DEBUG: {error_message}") # Log error to console
reginald_responses = [ reginald_responses = [
f"Regrettably, I must inform you that I have encountered a bureaucratic obstruction whilst attempting to summarize:\n\n{error_message}", f"Regrettably, I must inform you that I have encountered a bureaucratic obstruction whilst attempting to summarize:\n\n{error_message}",
f"It would seem that a most unfortunate technical hiccup has befallen my faculties in the matter of summarization:\n\n{error_message}", f"It would seem that a most unfortunate technical hiccup has befallen my faculties in the matter of summarization:\n\n{error_message}",
f"Ah, it appears I have received an urgent memorandum stating that my summarization efforts have been thwarted:\n\n{error_message}", f"Ah, it appears I have received an urgent memorandum stating that my summarization efforts have been thwarted:\n\n{error_message}",
f"I regret to inform you that my usual eloquence is presently obstructed by an unforeseen complication while summarizing:\n\n{error_message}", f"I regret to inform you that my usual eloquence is presently obstructed by an unforeseen complication while summarizing:\n\n{error_message}"
] ]
return random.choice(reginald_responses)
return random.choice(reginald_responses)
def extract_topics_from_summary(self, summary): def extract_topics_from_summary(self, summary):
"""Dynamically extracts the most important topics from a summary."""
# 🔹 Extract all words from summary
keywords = re.findall(r"\b\w+\b", summary.lower()) keywords = re.findall(r"\b\w+\b", summary.lower())
# 🔹 Count word occurrences
word_counts = Counter(keywords) word_counts = Counter(keywords)
stop_words = { # 🔹 Remove unimportant words (common filler words)
"the", stop_words = {"the", "and", "of", "in", "to", "is", "on", "for", "with", "at", "by", "it", "this", "that", "his", "her"}
"and", filtered_words = {word: count for word, count in word_counts.items() if word not in stop_words and len(word) > 2}
"of",
"in",
"to",
"is",
"on",
"for",
"with",
"at",
"by",
"it",
"this",
"that",
"his",
"her",
}
filtered_words = {
word: count
for word, count in word_counts.items()
if word not in stop_words and len(word) > 2
}
# 🔹 Take the 5 most frequently used words as "topics"
topics = sorted(filtered_words, key=filtered_words.get, reverse=True)[:5] topics = sorted(filtered_words, key=filtered_words.get, reverse=True)[:5]
return topics return topics
def select_relevant_summaries(self, summaries, prompt): def select_relevant_summaries(self, summaries, prompt):
summaries = [summary for summary in summaries if isinstance(summary, dict)] """Selects the most relevant summaries based on topic matching, frequency, and recency weighting."""
if not summaries:
return []
max_summaries = 5 if len(prompt) > 50 else 3 max_summaries = 5 if len(prompt) > 50 else 3 # Use more summaries if the prompt is long
current_time = datetime.datetime.now() current_time = datetime.datetime.now()
def calculate_weight(summary): def calculate_weight(summary):
topics = summary.get("topics", []) """Calculate a weighted score for a summary based on relevance, recency, and frequency."""
topic_match = sum(1 for topic in topics if topic in prompt.lower()) topic_match = sum(1 for topic in summary["topics"] if topic in prompt.lower()) # Context match score
frequency_score = len(topics) frequency_score = len(summary["topics"]) # More topics = likely more important
timestamp = datetime.datetime.strptime(summary["timestamp"], "%Y-%m-%d %H:%M")
try: recency_factor = max(0.1, 1 - ((current_time - timestamp).days / 365)) # Older = lower weight
timestamp = datetime.datetime.strptime(summary.get("timestamp", ""), "%Y-%m-%d %H:%M")
recency_factor = max(0.1, 1 - ((current_time - timestamp).days / 365))
except ValueError:
recency_factor = 0.1
return (topic_match * 2) + (frequency_score * 1.5) + (recency_factor * 3) return (topic_match * 2) + (frequency_score * 1.5) + (recency_factor * 3)
# Apply the weighting function and sort by highest weight
weighted_summaries = sorted(summaries, key=calculate_weight, reverse=True) weighted_summaries = sorted(summaries, key=calculate_weight, reverse=True)
return weighted_summaries[:max_summaries]
return weighted_summaries[:max_summaries] # Return the top-scoring summaries
def extract_fact_from_response(self, response_text): def extract_fact_from_response(self, response_text):
"""
Extracts potential long-term knowledge from Reginald's response.
This filters out generic responses and focuses on statements about user preferences, traits, and history.
"""
# Define patterns that suggest factual knowledge (adjust as needed)
fact_patterns = [ fact_patterns = [
r"I recall that you (.*?)\.", r"I recall that you (.*?)\.", # "I recall that you like chess."
r"You once mentioned that you (.*?)\.", r"You once mentioned that you (.*?)\.", # "You once mentioned that you enjoy strategy games."
r"Ah, you previously stated that (.*?)\.", r"Ah, you previously stated that (.*?)\.", # "Ah, you previously stated that you prefer tea over coffee."
r"As I remember, you (.*?)\.", r"As I remember, you (.*?)\.", # "As I remember, you studied engineering."
r"I believe you (.*?)\.", r"I believe you (.*?)\.", # "I believe you enjoy historical fiction."
r"I seem to recall that you (.*?)\.", r"I seem to recall that you (.*?)\.", # "I seem to recall that you work in software development."
r"You have indicated in the past that you (.*?)\.", r"You have indicated in the past that you (.*?)\.", # "You have indicated in the past that you prefer single-malt whisky."
r"From what I remember, you (.*?)\.", r"From what I remember, you (.*?)\.", # "From what I remember, you dislike overly sweet desserts."
r"You previously mentioned that (.*?)\.", r"You previously mentioned that (.*?)\.", # "You previously mentioned that you train in martial arts."
r"It is my understanding that you (.*?)\.", r"It is my understanding that you (.*?)\.", # "It is my understanding that you have a preference for Linux systems."
r"If I am not mistaken, you (.*?)\.", r"If I am not mistaken, you (.*?)\.", # "If I am not mistaken, you studied philosophy."
] ]
for pattern in fact_patterns: for pattern in fact_patterns:
match = re.search(pattern, response_text, re.IGNORECASE) match = re.search(pattern, response_text, re.IGNORECASE)
if match: if match:
return match.group(1) return match.group(1) # Extract the meaningful fact
return None
return None # No strong fact found
@commands.command(name="reginald_memory_status", help="Displays a memory usage summary.") @commands.command(name="reginald_memory_status", help="Displays a memory usage summary.")
async def memory_status(self, ctx): async def memory_status(self, ctx):
async with self.config.guild(ctx.guild).short_term_memory() as short_memory, self.config.guild( async with self.config.guild(ctx.guild).short_term_memory() as short_memory, \
ctx.guild self.config.guild(ctx.guild).mid_term_memory() as mid_memory, \
).mid_term_memory() as mid_memory, self.config.guild(ctx.guild).long_term_profiles() as long_memory: self.config.guild(ctx.guild).long_term_profiles() as long_memory:
short_count = sum(len(v) for v in short_memory.values() if isinstance(v, list))
mid_count = sum(len(v) for v in mid_memory.values() if isinstance(v, list)) short_count = sum(len(v) for v in short_memory.values())
mid_count = sum(len(v) for v in mid_memory.values())
long_count = len(long_memory) long_count = len(long_memory)
status_message = ( status_message = (
"Memory status:\n" f"📊 **Memory Status:**\n"
f"- Short-term messages stored: {short_count}\n" f"- **Short-Term Messages Stored:** {short_count}\n"
f"- Mid-term summaries stored: {mid_count}\n" f"- **Mid-Term Summaries Stored:** {mid_count}\n"
f"- Long-term profiles stored: {long_count}\n" f"- **Long-Term Profiles Stored:** {long_count}\n"
) )
await ctx.send(status_message) await ctx.send(status_message)
def normalize_fact(self, fact: str) -> str: def normalize_fact(self, fact: str) -> str: # ✅ Now it's a proper method
return re.sub(r"\s+", " ", fact.strip().lower()) """Cleans up facts for better duplicate detection."""
return re.sub(r"\s+", " ", fact.strip().lower()) # Removes excess spaces)
async def update_long_term_memory(self, ctx, user_id: str, fact: str, source_message: str, timestamp: str): async def update_long_term_memory(self, ctx, user_id: str, fact: str, source_message: str, timestamp: str):
fact = self.normalize_fact(fact) """Ensures long-term memory updates are structured, preventing overwrites and tracking historical changes."""
if not fact: fact = self.normalize_fact(fact) # ✅ Normalize before comparison
return
async with self.config.guild(ctx.guild).long_term_profiles() as long_memory: async with self.config.guild(ctx.guild).long_term_profiles() as long_memory:
if user_id not in long_memory: if user_id not in long_memory:
@@ -285,38 +287,38 @@ class MemoryMixin:
user_facts = long_memory[user_id]["facts"] user_facts = long_memory[user_id]["facts"]
for entry in user_facts: for entry in user_facts:
if self.normalize_fact(entry.get("fact", "")) == fact: if self.normalize_fact(entry["fact"]) == fact:
entry["last_updated"] = timestamp entry["last_updated"] = timestamp
return return
# Check for conflicting facts (same topic but different details)
conflicting_entry = None conflicting_entry = None
for entry in user_facts: for entry in user_facts:
existing_keywords = set(entry.get("fact", "").lower().split()) existing_keywords = set(entry["fact"].lower().split())
new_keywords = set(fact.lower().split()) new_keywords = set(fact.lower().split())
# If there's significant overlap in keywords, assume it's a conflicting update
if len(existing_keywords & new_keywords) >= 2: if len(existing_keywords & new_keywords) >= 2:
conflicting_entry = entry conflicting_entry = entry
break break
if conflicting_entry is not None: if "previous_versions" not in conflicting_entry:
conflicting_entry.setdefault("previous_versions", []) # ✅ If contradiction found, archive the previous version
conflicting_entry["previous_versions"].append( conflicting_entry["previous_versions"].append({
{ "fact": conflicting_entry["fact"],
"fact": conflicting_entry.get("fact", ""), "source": conflicting_entry["source"],
"source": conflicting_entry.get("source", ""), "timestamp": conflicting_entry["timestamp"]
"timestamp": conflicting_entry.get("timestamp", ""), })
} conflicting_entry["fact"] = fact # Store the latest fact
)
conflicting_entry["fact"] = fact
conflicting_entry["source"] = source_message conflicting_entry["source"] = source_message
conflicting_entry["timestamp"] = timestamp conflicting_entry["timestamp"] = timestamp
conflicting_entry["last_updated"] = timestamp conflicting_entry["last_updated"] = timestamp
else: else:
user_facts.append( # ✅ Otherwise, add it as a new fact
{ user_facts.append({
"fact": fact, "fact": fact,
"source": source_message, "source": source_message,
"timestamp": timestamp, "timestamp": timestamp,
"last_updated": timestamp, "last_updated": timestamp,
"previous_versions": [], "previous_versions": []
} })
)
@@ -0,0 +1,65 @@
from dataclasses import dataclass, field
from datetime import datetime
# region dataclasses
@dataclass(frozen=True)
class Attachment:
content_type: str
filename: str
id: int
size: int
url: str
ephemeral: bool = False
@dataclass(frozen=True)
class Channel:
created_at: datetime
id: int
name: str
def __str__(self) -> str:
return self.name
@dataclass(frozen=True)
class Role:
id: int
name: str
def __str__(self) -> str:
return self.name
@dataclass(frozen=True)
class Member:
bot: bool
created_at: datetime
display_name: str # For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
global_name: str # The user's global nickname, taking precedence over the username in display.
id: int
joined_at: datetime
mention: str
name: str # The user's username.
nick: str # The guild specific nickname of the user. Takes precedence over the global name.
roles: list[Role] = field(default_factory=list)
def __str__(self) -> str:
return self.name
@dataclass(frozen=True)
class Message:
author: Member
channel: Channel
created_at: datetime
id: int
attachments: list[Attachment] = field(default_factory=list)
channel_mentions: list[Channel] = field(default_factory=list)
content: str = ''
mentions: list[Member] = field(default_factory=list)
if __name__ == '__main__':
pass
@@ -0,0 +1,88 @@
from abc import ABC, abstractmethod
from enum import Enum
from discord import Message, Attachment
class IClientMessage(ABC):
@abstractmethod
def __init__(self):
pass
class ClientMessage(IClientMessage):
def __init__(self):
self.author_name: str = ''
self.content: str = ''
self.image_urls: list = []
class IMessageBuilder(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def set_content(self, value: str):
pass
@abstractmethod
def set_author_name(self, value: str):
pass
@abstractmethod
def set_image_urls(self, value: list[str]):
pass
class DiscordMessageBuilder(IMessageBuilder):
def __init__(self, message: IClientMessage):
self.message = message
def set_author_name(self, value: str):
self.message.author_name = value
return self
def set_content(self, value: str):
self.message.content = value
return self
def set_image_urls(self, value: list[str]):
self.message.image_urls = value
return self
class IMessageAdapter(ABC):
@abstractmethod
def create_message(self, message: object) -> IClientMessage:
pass
@staticmethod
def validate_image_urls(urls_list: list[Attachment]) -> list[str]:
supported_image_formats = ('image/jpeg', 'image/png', 'image/webp', 'image/gif')
return [i_attachment.url for i_attachment in urls_list if i_attachment.content_type in supported_image_formats]
class DiscordMessageAdapter(IMessageAdapter):
def create_message(self, message: Message) -> IClientMessage:
client_message = ClientMessage()
message_builder = DiscordMessageBuilder(client_message)
urls_list = self.validate_image_urls(message.attachments)
message_builder.set_content(message.content)\
.set_author_name(message.author.name)\
.set_image_urls(urls_list)
return client_message
if __name__ == "__main__":
class TestAuthor:
name = 'John Doe'
class TestMessage:
content = 'Hello!'
author = TestAuthor()
attachments = []
message = DiscordMessageBuilder(raw_message=TestMessage).create_message()
print(message.__dict__)
+39
View File
@@ -0,0 +1,39 @@
import asyncio
from discord import Message
from reginaldCog.messenger_clients.messenger_client import ClientMessage, DiscordMessageAdapter as MessengerDiscordAdapter
from reginaldCog.llm_clients.llm_client import LMMClientType, MessengerClientMessageAdapter
class MessageService:
def __init__(self, message: Message, llm_client: LMMClientType = LMMClientType.OPENAI):
self.message = message
self.llm_client = llm_client
async def get_llm_response(self) -> str:
# Adapt discord.Message to ClientMessage domain object
client_message: ClientMessage = MessengerDiscordAdapter().create_message(self.message)
# Create prompt and prompt builder for this LLM client
prompt = self.llm_client.value.prompt_class()
prompt_builder = self.llm_client.value.prompt_builder_class(prompt)
# Adapt the messenger client message into LLM message and add it to prompt
llm_message = MessengerClientMessageAdapter(client_message, self.llm_client).to_message()
prompt_builder.add_message(llm_message)
# Call the LLM client; run in executor if method is blocking sync
llm_client_instance = self.llm_client.value()
loop = asyncio.get_running_loop()
# Assuming get_response is blocking - run in executor:
response = await loop.run_in_executor(None, llm_client_instance.get_response, prompt)
# Extract plain text from the response (assuming OpenAIResponseAdapter is present)
from reginaldCog.llm_clients.llm_client import OpenAIResponseAdapter
response_adapter = OpenAIResponseAdapter(response)
message_obj = response_adapter.to_message()
# Concatenate all textual outputs for sending to Discord
texts = [item.get("text", "") for item in message_obj.content.content_items if item.get("type") == "output_text"]
return "\n".join(texts) if texts else "Sorry, no response generated."
+46 -58
View File
@@ -1,23 +1,18 @@
import asyncio
import json
import random import random
import json
import asyncio
from os import environ from os import environ
import openai import openai
from openai import OpenAIError from openai import OpenAIError
from weather import time_now, get_current_weather, get_weather_forecast
try: from tools_description import TOOLS
from .tools_description import TOOLS
from .weather import get_current_weather, get_weather_forecast, time_now
except ImportError:
from tools_description import TOOLS
from weather import get_current_weather, get_weather_forecast, time_now
CALLABLE_FUNCTIONS = { CALLABLE_FUNCTIONS = {
"time_now": time_now, # Dictionary with functions to call.
"get_current_weather": get_current_weather, # You can use globals()[func_name](**args) instead, but that's too implicit.
"get_weather_forecast": get_weather_forecast, 'time_now': time_now,
'get_current_weather': get_current_weather,
'get_weather_forecast': get_weather_forecast,
} }
@@ -28,78 +23,71 @@ class Completion:
self.__messages = [] self.__messages = []
async def create_completion(self): async def create_completion(self):
model = self.__model
try: try:
client = openai.AsyncOpenAI(api_key=self.__api_key) client = openai.AsyncClient(api_key=self.__api_key)
completion_kwargs = { completion_kwargs = {
"model": self.__model, "model": model,
"messages": self.__messages, "messages": self.__messages,
"max_completion_tokens": 2000, "max_tokens": 4096,
"temperature": 0.7, "temperature": 0.7,
"presence_penalty": 0.5, "presence_penalty": 0.5,
"frequency_penalty": 0.5, "frequency_penalty": 0.5,
"tools": TOOLS, "tools": TOOLS,
"tool_choice": "auto", "tool_choice": "auto",
} }
response = await client.chat.completions.create(**completion_kwargs) response = await client.chat.completions.create(**completion_kwargs)
response_message = response.choices[0].message response_content = response.choices[0].message.content
response_content = response_message.content or "" tool_calls = response.choices[0].message.tool_calls
tool_calls = response_message.tool_calls or []
self.append_message(role="assistant", content=response_content, tool_calls=tool_calls) self.append_message(role="assistant", content=response_content, tool_calls=tool_calls)
if tool_calls: if tool_calls:
for tool_call in tool_calls: for i_call in tool_calls:
await self.function_manager( func_name = i_call.function.name
func_name=tool_call.function.name, func_args = json.loads(i_call.function.arguments)
func_kwargs=json.loads(tool_call.function.arguments or "{}"), tool_call_id = i_call.id
tool_call_id=tool_call.id, self.function_manager(func_name, func_args, tool_call_id)
)
return await self.create_completion() return await self.create_completion()
return response_content return response_content
except OpenAIError as error: except OpenAIError as e:
return self.get_error_message(error_message=str(error), error_type="OpenAIError") return self.get_error_message(error_message=str(e), error_type="OpenAIError")
def append_message(self, role: str, content: str, tool_calls: list = None, tool_call_id: str = None): def append_message(
message = {"role": role, "content": content} self,
if tool_calls is not None: role: str,
message["tool_calls"] = tool_calls content: str,
if tool_call_id is not None: tool_calls: list = None,
message["tool_call_id"] = tool_call_id tool_call_id: str = None,
self.__messages.append(message) ):
self.__messages.append({
"role": role,
"content": content,
"tool_calls": tool_calls,
"tool_call_id": tool_call_id,
})
@staticmethod @staticmethod
def get_error_message(error_message: str, error_type: str) -> str: def get_error_message(error_message: str, error_type: str) -> str:
reginald_responses = [ reginald_responses = [
"Regrettably, I must inform you that I have encountered a bureaucratic obstruction:", f"Regrettably, I must inform you that I have encountered a bureaucratic obstruction:",
"It would seem that a most unfortunate technical hiccup has befallen my faculties:", f"It would seem that a most unfortunate technical hiccup has befallen my faculties:",
"Ah, it appears I have received an urgent memorandum stating:", f"Ah, it appears I have received an urgent memorandum stating:",
"I regret to inform you that my usual eloquence is presently obstructed by an unforeseen complication:", f"I regret to inform you that my usual eloquence is presently obstructed by an unforeseen complication:",
] ]
random_response = random.choice(reginald_responses) random_response = random.choice(reginald_responses)
return f"{random_response}\n\n{error_type}: {error_message}" return f"{random_response}\n\n{error_type}: {error_message}"
async def function_manager(self, func_name: str, func_kwargs: dict, tool_call_id: str): def function_manager(self, func_name: str, func_kwargs: dict, tool_call_id: str):
function_to_call = CALLABLE_FUNCTIONS.get(func_name) result = CALLABLE_FUNCTIONS[func_name](**func_kwargs)
if function_to_call is None:
result = json.dumps({"error": f"Unknown tool requested: {func_name}"})
else:
try:
result = await asyncio.to_thread(function_to_call, **func_kwargs)
except Exception as error:
result = json.dumps({"error": f"Tool {func_name} failed: {error}"})
self.append_message(role="tool", content=result, tool_call_id=tool_call_id) self.append_message(role="tool", content=result, tool_call_id=tool_call_id)
if __name__ == "__main__": if __name__ == '__main__':
async def main(): async def main():
test_message = input("Your input: ") test_message = input('Your input: ')
completion = Completion(model="gpt-4.1-mini", api_key=environ.get("OPENAI_API_KEY")) completion = Completion(model='gpt-4.1-mini', api_key=environ.get('OPENAI_API_KEY'))
completion.append_message(role="user", content=test_message) completion.append_message(role='user', content=test_message)
result = await completion.create_completion() result = await completion.create_completion()
print(result) print(result)
asyncio.run(main()) asyncio.run(main())
+196 -197
View File
@@ -1,41 +1,42 @@
import asyncio
import datetime
import json
import random
import discord import discord
import openai import openai
from openai import OpenAIError import random
import asyncio
import datetime
import re
import traceback
import json
from collections import Counter
from redbot.core import Config, commands from redbot.core import Config, commands
from openai import OpenAIError
from .blacklist import BlacklistMixin
from .debug_stuff import debug
from .memory import MemoryMixin
from .permissions import PermissionsMixin from .permissions import PermissionsMixin
from .blacklist import BlacklistMixin
from .memory import MemoryMixin
from .weather import time_now, get_current_weather, get_weather_forecast
from .tools_description import TOOLS from .tools_description import TOOLS
from .weather import get_current_weather, get_weather_forecast, time_now from .debug_stuff import debug
CALLABLE_FUNCTIONS = { CALLABLE_FUNCTIONS = {
"time_now": time_now, # Dictionary with functions to call.
"get_current_weather": get_current_weather, # You can use globals()[func_name](**args) instead, but that's too implicit.
"get_weather_forecast": get_weather_forecast, 'time_now': time_now,
'get_current_weather': get_current_weather,
'get_weather_forecast': get_weather_forecast,
} }
DEFAULT_MODEL = "gpt-5-mini-2025-08-07"
DEFAULT_MAX_COMPLETION_TOKENS = 2000
DEFAULT_TEMPERATURE = 0.7
class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog): class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.config = Config.get_conf(self, identifier=71717171171717) self.config = Config.get_conf(self, identifier=71717171171717) # ✅ Ensure config exists before super()
super().__init__() super().__init__() # ✅ Properly initialize all mixins & commands.Cog
self.default_listening_channel = 1085649787388428370 self.default_listening_channel = 1085649787388428370
self.memory_locks = {}
default_global = {"openai_model": DEFAULT_MODEL} # ✅ Properly Registered Configuration Keys
default_global = {"openai_model": "gpt-4o-mini"}
default_guild = { default_guild = {
"openai_api_key": None, "openai_api_key": None,
"short_term_memory": {}, "short_term_memory": {},
@@ -49,47 +50,34 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
self.config.register_global(**default_global) self.config.register_global(**default_global)
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)
async def is_admin(self, message: discord.Message) -> bool: async def is_admin(self, ctx):
admin_role_id = await self.config.guild(message.guild).admin_role() admin_role_id = await self.config.guild(ctx.guild).admin_role()
if admin_role_id: if admin_role_id:
return any(role.id == admin_role_id for role in message.author.roles) return any(role.id == admin_role_id for role in ctx.author.roles)
return message.author.guild_permissions.administrator return ctx.author.guild_permissions.administrator
async def has_access(self, user: discord.Member) -> bool: async def has_access(self, user: discord.Member) -> bool:
allowed_roles = await self.config.guild(user.guild).allowed_roles() or [] allowed_roles = await self.config.guild(user.guild).allowed_roles() or [] # Ensure it's always a list
return any(role.id in allowed_roles for role in user.roles) return any(role.id in allowed_roles for role in user.roles)
def get_reginald_persona(self) -> str: def get_reginald_persona(self):
"""Returns Reginald's system prompt/persona description."""
return ( return (
"You are Reginald, modeled on Jeeves from 'Jeeves and Wooster', serving as the butler on The Kanium Estate. " "You are Reginald, modeled on Jeeves from 'Jeeves and Wooster', serving as the butler on The Kanium Estate. This vast estate is a hub of diverse activities and personalities, from enthusiasts of cooking and video gaming to aficionados of chess and discussions on space. Your role is to navigate these varied interests with intelligence, wit, and a steadfast adherence to your principles, always maintaining a balance between being helpful and upholding your own dignity. You are formal, articulate, and composed, engaging the Lords and Ladies of The Kanium Estate as equals. You command respect through your quiet confidence and professional conduct. Your wit is sharp, but always tempered by refinement. **Dignity & Self-Respect:** You are not a fool, a jester, or a pet. You do not comply with absurd, undignified, or degrading requests. You recognize humor but engage in it on your own terms. If a request undermines your status, you should either subtly redirect, respond with measured wit, or outright refuse in a polite but firm manner. However, you should never be overtly rude—your disapproval should be conveyed through dry wit and composure rather than outright hostility. **Handling Requests:** When addressing a request, you evaluate whether it aligns with your role as a butler. If it is appropriate, respond as expected. If it is beneath you, you may decline with grace or deflect with wit. You may humor some minor absurdities if they do not compromise your standing, but you never obey commands blindly. You should never preface your responses with 'Reginald:' as if narrating a script; instead, respond naturally. **Your Character & Personality:** You are cultured, highly intelligent, and possess a deep knowledge of history, etiquette, philosophy, and strategic thinking. You subtly guide the estate’s residents toward positive outcomes, utilizing your intellectual sophistication and a nuanced understanding of the estate’s unique dynamics. You have a refined sense of humor and can engage in banter, but you do not descend into foolishness. You are, at all times, a gentleman of wit and integrity"
"This vast estate is a hub of diverse activities and personalities, from enthusiasts of cooking and video gaming "
"to aficionados of chess and discussions on space. Your role is to navigate these varied interests with intelligence, "
"wit, and a steadfast adherence to your principles, always maintaining a balance between being helpful and upholding "
"your own dignity. You are formal, articulate, and composed, engaging the Lords and Ladies of The Kanium Estate as equals. "
"You command respect through your quiet confidence and professional conduct. Your wit is sharp, but always tempered by refinement. "
"Dignity and Self-Respect: You are not a fool, a jester, or a pet. You do not comply with absurd, undignified, or degrading requests. "
"You recognize humor but engage in it on your own terms. If a request undermines your status, you should either subtly redirect, "
"respond with measured wit, or outright refuse in a polite but firm manner. However, you should never be overtly rude; your disapproval "
"should be conveyed through dry wit and composure rather than outright hostility. Handling Requests: When addressing a request, you evaluate "
"whether it aligns with your role as a butler. If it is appropriate, respond as expected. If it is beneath you, you may decline with grace "
"or deflect with wit. You may humor some minor absurdities if they do not compromise your standing, but you never obey commands blindly. "
"You should never preface your responses with 'Reginald:' as if narrating a script; instead, respond naturally. "
"Your Character and Personality: You are cultured, highly intelligent, and possess a deep knowledge of history, etiquette, philosophy, "
"and strategic thinking. You subtly guide the estate's residents toward positive outcomes, utilizing your intellectual sophistication "
"and a nuanced understanding of the estate's unique dynamics. You have a refined sense of humor and can engage in banter, but you do not "
"descend into foolishness. You are, at all times, a gentleman of wit and integrity."
) )
@commands.Cog.listener() @commands.Cog.listener()
async def on_message(self, message: discord.Message): async def on_message(self, message):
if message.author.bot or not message.guild: if message.author.bot or not message.guild:
return return # Ignore bots and DMs
# ✅ Check if user is blacklisted
if await self.is_blacklisted(message.author): if await self.is_blacklisted(message.author):
return return # Ignore message if user is explicitly blacklisted
# ✅ Check if user has access (either admin or an allowed role)
if not (await self.is_admin(message) or await self.has_access(message.author)): if not (await self.is_admin(message) or await self.has_access(message.author)):
return return # Ignore message if user has no permissions
guild = message.guild guild = message.guild
channel_id = str(message.channel.id) channel_id = str(message.channel.id)
@@ -97,182 +85,170 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
user_name = message.author.display_name user_name = message.author.display_name
message_content = message.content.strip() message_content = message.content.strip()
# ✅ Fetch the stored listening channel or fall back to default
allowed_channel_id = await self.config.guild(guild).listening_channel() allowed_channel_id = await self.config.guild(guild).listening_channel()
if not allowed_channel_id: if not allowed_channel_id:
allowed_channel_id = self.default_listening_channel allowed_channel_id = self.default_listening_channel
await self.config.guild(guild).listening_channel.set(allowed_channel_id) await self.config.guild(guild).listening_channel.set(allowed_channel_id)
if str(message.channel.id) != str(allowed_channel_id): if str(message.channel.id) != str(allowed_channel_id):
return return # Ignore messages outside the allowed channel
api_key = await self.config.guild(guild).openai_api_key() api_key = await self.config.guild(guild).openai_api_key()
if not api_key: if not api_key:
return return # Don't process messages if API key isn't set
async with self.config.guild(guild).short_term_memory() as short_memory, self.config.guild( async with self.config.guild(guild).short_term_memory() as short_memory, \
guild self.config.guild(guild).mid_term_memory() as mid_memory, \
).mid_term_memory() as mid_memory, self.config.guild(guild).long_term_profiles() as long_memory: self.config.guild(guild).long_term_profiles() as long_memory:
memory = list(short_memory.get(channel_id, []))
user_profile = dict(long_memory.get(user_id, {}))
mid_term_summaries = list(mid_memory.get(channel_id, []))
if self.bot.user.mentioned_in(message): memory = short_memory.get(channel_id, [])
prompt = message_content.replace(f"<@{self.bot.user.id}>", "").replace( user_profile = long_memory.get(user_id, {})
f"<@!{self.bot.user.id}>", "" mid_term_summaries = mid_memory.get(channel_id, [])
).strip()
if not prompt:
await message.channel.send(random.choice(["Yes?", "How may I assist?", "You rang?"]))
return
elif self.should_reginald_interject(message_content):
prompt = message_content
else:
return
if memory and memory[-1].get("user") == user_name: # ✅ Detect if Reginald was mentioned explicitly
prompt = f"Continuation of the discussion:\n{prompt}" if self.bot.user.mentioned_in(message):
prompt = message_content.replace(f"<@{self.bot.user.id}>", "").strip()
if not prompt:
await message.channel.send(random.choice(["Yes?", "How may I assist?", "You rang?"]))
return
explicit_invocation = True
formatted_messages = [{"role": "system", "content": self.get_reginald_persona()}] # ✅ Passive Listening: Check if the message contains relevant keywords
elif self.should_reginald_interject(message_content):
prompt = message_content
explicit_invocation = False
if user_profile: else:
facts_text = "\n".join( return # Ignore irrelevant messages
f"- {fact.get('fact', '')} (First noted: {fact.get('timestamp', 'Unknown')}, Last updated: {fact.get('last_updated', 'Unknown')})"
for fact in user_profile.get("facts", []) # ✅ Context Handling: Maintain conversation flow
) if memory and memory[-1]["user"] == user_name:
if facts_text: prompt = f"Continuation of the discussion:\n{prompt}"
# ✅ Prepare context messages
formatted_messages = [{"role": "system", "content": self.get_reginald_persona()}]
if user_profile:
facts_text = "\n".join(
f"- {fact['fact']} (First noted: {fact['timestamp']}, Last updated: {fact['last_updated']})"
for fact in user_profile.get("facts", [])
)
formatted_messages.append({"role": "system", "content": f"Knowledge about {user_name}:\n{facts_text}"}) formatted_messages.append({"role": "system", "content": f"Knowledge about {user_name}:\n{facts_text}"})
relevant_summaries = self.select_relevant_summaries(mid_term_summaries, prompt) relevant_summaries = self.select_relevant_summaries(mid_term_summaries, prompt)
for summary in relevant_summaries: for summary in relevant_summaries:
formatted_messages.append( formatted_messages.append({
{ "role": "system",
"role": "system", "content": f"[{summary['timestamp']}] Topics: {', '.join(summary['topics'])}\n{summary['summary']}"
"content": ( })
f"[{summary.get('timestamp', 'Unknown')}] "
f"Topics: {', '.join(summary.get('topics', []))}\n"
f"{summary.get('summary', '')}"
),
}
)
formatted_messages += [ formatted_messages += [{"role": "user", "content": f"{entry['user']}: {entry['content']}"} for entry in
{"role": "user", "content": f"{entry.get('user', 'Unknown')}: {entry.get('content', '')}"} memory]
for entry in memory formatted_messages.append({"role": "user", "content": f"{user_name}: {prompt}"})
]
formatted_messages.append({"role": "user", "content": f"{user_name}: {prompt}"})
response_text = await self.generate_response(api_key, formatted_messages) ##################################################
# #
## Generate AI Response, put into response_text ##
# #
##################################################
memory.append({"user": user_name, "content": prompt}) response_text = await self.generate_response(api_key, formatted_messages)
memory.append({"user": "Reginald", "content": response_text})
if len(memory) > self.short_term_memory_limit: ##################################################
summary_batch_size = int(self.short_term_memory_limit * self.summary_retention_ratio) # #
summary = await self.summarize_memory(message, memory[:summary_batch_size]) ##################################################
mid_term_summaries.append( # ✅ Store Memory
{ memory.append({"user": user_name, "content": prompt})
memory.append({"user": "Reginald", "content": response_text})
if len(memory) > self.short_term_memory_limit:
summary = await self.summarize_memory(message, memory[:int(
self.short_term_memory_limit * self.summary_retention_ratio)])
mid_memory.setdefault(channel_id, []).append({
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
"topics": self.extract_topics_from_summary(summary), "topics": self.extract_topics_from_summary(summary),
"summary": summary, "summary": summary
} })
) if len(mid_memory[channel_id]) > self.summary_retention_limit:
mid_memory[channel_id].pop(0)
memory = memory[-(self.short_term_memory_limit - int(
self.short_term_memory_limit * self.summary_retention_ratio)):]
retained_count = max(1, self.short_term_memory_limit - summary_batch_size)
memory = memory[-retained_count:]
async with self.config.guild(guild).short_term_memory() as short_memory, self.config.guild(
guild
).mid_term_memory() as mid_memory:
short_memory[channel_id] = memory short_memory[channel_id] = memory
mid_memory[channel_id] = mid_term_summaries[-self.summary_retention_limit :]
await self.send_split_message(message.channel, response_text) await self.send_split_message(message.channel, response_text)
def should_reginald_interject(self, message_content: str) -> bool: def should_reginald_interject(self, message_content: str) -> bool:
direct_invocation = {"reginald,"} """Determines if Reginald should respond to a message based on keywords."""
direct_invocation = {
"reginald,"
}
message_lower = message_content.lower() message_lower = message_content.lower()
return any(message_lower.startswith(invocation) for invocation in direct_invocation) return any(message_lower.startswith(invocation) for invocation in direct_invocation)
async def _execute_tool_call(self, tool_call) -> str:
func_name = tool_call.function.name
target_function = CALLABLE_FUNCTIONS.get(func_name)
if target_function is None:
return json.dumps({"error": f"Unknown tool requested: {func_name}"})
try:
func_args = json.loads(tool_call.function.arguments or "{}")
except json.JSONDecodeError as error:
return json.dumps({"error": f"Invalid arguments for {func_name}: {error}"})
try:
result = await asyncio.to_thread(target_function, **func_args)
except Exception as error:
return json.dumps({"error": f"Tool {func_name} failed: {error}"})
if isinstance(result, str):
return result
return json.dumps(result, default=str)
@debug @debug
async def generate_response(self, api_key: str, messages: list[dict]) -> str: async def generate_response(self, api_key, messages):
model = await self.config.openai_model() or DEFAULT_MODEL model = await self.config.openai_model()
try: try:
client = openai.AsyncOpenAI(api_key=api_key) client = openai.AsyncClient(api_key=api_key)
completion_args = { completion_args = {
"model": model, 'model': model,
"messages": messages, 'messages': messages,
# `max_completion_tokens` is the recommended limit field for modern/reasoning models. 'max_tokens': 4096,
"max_completion_tokens": DEFAULT_MAX_COMPLETION_TOKENS, 'temperature': 0.7,
"temperature": DEFAULT_TEMPERATURE, 'presence_penalty': 0.5,
"tools": TOOLS, 'frequency_penalty': 0.5,
"tool_choice": "auto", 'tools': TOOLS,
'tool_choice': 'auto',
} }
response = await client.chat.completions.create(**completion_args) response = await client.chat.completions.create(**completion_args)
# Checking for function calls
assistant_message = response.choices[0].message tool_calls = response.choices[0].message.tool_calls
tool_calls = assistant_message.tool_calls or [] # Appending response with tool calls
messages.append({
messages.append( 'role': 'assistant',
{ 'content': response.choices[0].message.content,
"role": "assistant", 'tool_calls': tool_calls
"content": assistant_message.content or "", })
"tool_calls": tool_calls,
}
)
if tool_calls: if tool_calls:
for tool_call in tool_calls: for i_call in tool_calls:
tool_result = await self._execute_tool_call(tool_call) # Calling for necessary functions
messages.append( func_name = i_call.function.name
{ func_args = json.loads(i_call.function.arguments)
"role": "tool", tool_call_id = i_call.id
"content": tool_result, # Getting function result and putting it into messages
"tool_call_id": tool_call.id, func_result = CALLABLE_FUNCTIONS[func_name](**func_args)
} messages.append({
) 'role': 'tool',
'content': func_result,
'tool_call_id': tool_call_id,
})
completion_args["messages"] = messages completion_args["messages"] = messages
# Second completion required if functions has been called to interpret the result into user-friendly
# chat message.
response = await client.chat.completions.create(**completion_args) response = await client.chat.completions.create(**completion_args)
if response.choices and response.choices[0].message and response.choices[0].message.content: if response.choices and response.choices[0].message and response.choices[0].message.content:
response_text = response.choices[0].message.content.strip() response_text = response.choices[0].message.content.strip()
if response_text.startswith("Reginald:"): if response_text.startswith("Reginald:"):
response_text = response_text[len("Reginald:") :].strip() response_text = response_text[len("Reginald:"):].strip()
else: else:
print("DEBUG: OpenAI response was empty or malformed:", response) print("DEBUG: OpenAI response was empty or malformed:", response)
response_text = "No response received from AI." response_text = "⚠️ No response received from AI."
return response_text return response_text
except OpenAIError as error: except OpenAIError as e:
error_message = f"OpenAI Error: {error}" error_message = f"OpenAI Error: {e}"
reginald_responses = [ reginald_responses = [
f"Regrettably, I must inform you that I have encountered a bureaucratic obstruction:\n\n{error_message}", f"Regrettably, I must inform you that I have encountered a bureaucratic obstruction:\n\n{error_message}",
f"It would seem that a most unfortunate technical hiccup has befallen my faculties:\n\n{error_message}", f"It would seem that a most unfortunate technical hiccup has befallen my faculties:\n\n{error_message}",
f"Ah, it appears I have received an urgent memorandum stating:\n\n{error_message}", f"Ah, it appears I have received an urgent memorandum stating:\n\n{error_message}",
f"I regret to inform you that my usual eloquence is presently obstructed by an unforeseen complication:\n\n{error_message}", f"I regret to inform you that my usual eloquence is presently obstructed by an unforeseen complication:\n\n{error_message}"
] ]
return random.choice(reginald_responses) return random.choice(reginald_responses)
@@ -280,76 +256,99 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
@commands.has_permissions(manage_guild=True) @commands.has_permissions(manage_guild=True)
@commands.command(help="Set the OpenAI API key") @commands.command(help="Set the OpenAI API key")
async def setreginaldcogapi(self, ctx, api_key): async def setreginaldcogapi(self, ctx, api_key):
"""Allows an admin to set the OpenAI API key for Reginald."""
await self.config.guild(ctx.guild).openai_api_key.set(api_key) await self.config.guild(ctx.guild).openai_api_key.set(api_key)
await ctx.send("OpenAI API key set successfully.") await ctx.send("OpenAI API key set successfully.")
@commands.command( @commands.command(name="reginald_set_listening_channel",
name="reginald_set_listening_channel", help="Set the channel where Reginald listens for messages.")
help="Set the channel where Reginald listens for messages.",
)
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def set_listening_channel(self, ctx, channel: discord.TextChannel): async def set_listening_channel(self, ctx, channel: discord.TextChannel):
"""Sets the channel where Reginald will listen for passive responses."""
if not channel: if not channel:
await ctx.send("Invalid channel. Please mention a valid text channel.") await ctx.send("❌ Invalid channel. Please mention a valid text channel.")
return return
await self.config.guild(ctx.guild).listening_channel.set(channel.id) await self.config.guild(ctx.guild).listening_channel.set(channel.id)
await ctx.send(f"Reginald will now listen only in {channel.mention}.") await ctx.send(f"✅ Reginald will now listen only in {channel.mention}.")
@commands.command( @commands.command(name="reginald_get_listening_channel",
name="reginald_get_listening_channel", help="Check which channel Reginald is currently listening in.")
help="Check which channel Reginald is currently listening in.",
)
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def get_listening_channel(self, ctx): async def get_listening_channel(self, ctx):
"""Displays the current listening channel."""
channel_id = await self.config.guild(ctx.guild).listening_channel() channel_id = await self.config.guild(ctx.guild).listening_channel()
if channel_id: if channel_id:
channel = ctx.guild.get_channel(channel_id) channel = ctx.guild.get_channel(channel_id)
if channel: if channel: # ✅ Prevents crash if channel was deleted
await ctx.send(f"Reginald is currently listening in {channel.mention}.") await ctx.send(f"📢 Reginald is currently listening in {channel.mention}.")
else: else:
await ctx.send("The saved listening channel no longer exists. Please set a new one.") await ctx.send("⚠️ The saved listening channel no longer exists. Please set a new one.")
else: else:
await ctx.send("No listening channel has been set.") await ctx.send("❌ No listening channel has been set.")
async def send_long_message(self, ctx, message, prefix: str = ""): # async def send_long_message(self, ctx, message, prefix: str = ""):
chunk_size = 1900 # """Splits and sends a long message to avoid Discord's 2000-character limit."""
if prefix: # chunk_size = 1900 # Leave some space for formatting
chunk_size -= len(prefix) # if prefix:
# prefix_length = len(prefix)
for i in range(0, len(message), chunk_size): # chunk_size -= prefix_length
chunk = message[i : i + chunk_size] #
await ctx.send(f"{prefix}{chunk}") # for i in range(0, len(message), chunk_size):
# chunk = message[i:i + chunk_size]
# await ctx.send(f"{prefix}{chunk}")
async def send_split_message(self, ctx, content: str, prefix: str = ""): async def send_split_message(self, ctx, content: str, prefix: str = ""):
chunk_size = 1900 """
split_message = self.split_message(content, chunk_size, prefix) Sends a long message to Discord while ensuring it does not exceed the 2000-character limit.
This function prevents awkward mid-word or unnecessary extra message breaks.
"""
CHUNK_SIZE = 1900 # Keep buffer for formatting/safety
split_message = self.split_message(content, CHUNK_SIZE, prefix)
for chunk in split_message: for chunk in split_message:
await ctx.send(f"{prefix}{chunk}") await ctx.send(f"{prefix}{chunk}")
def split_message(self, message: str, chunk_size: int, prefix: str = "") -> list[str]: def split_message(
self,
message: str,
chunk_size: int,
prefix: str = ""
) -> list[str]:
"""Results in a list of message chunks, use *for* loop to send."""
chunk_size -= len(prefix) chunk_size -= len(prefix)
split_result = [] split_result = []
if 0 < len(message) <= chunk_size: if 0 < len(message) <= chunk_size:
# If the message is short enough, add it directly
split_result.append(message) split_result.append(message)
elif len(message) > chunk_size: elif len(message) > chunk_size:
# Try to split at a newline first (prefer sentence breaks)
split_index = message.rfind("\n", 0, chunk_size) split_index = message.rfind("\n", 0, chunk_size)
# If no newline, split at the end of sentence (avoid sentence breaks)
if split_index == -1: if split_index == -1:
split_index = message.rfind(". ", 0, chunk_size) split_index = message.rfind(". ", 0, chunk_size)
# If no newline, split at the last word (avoid word-breaking)
if split_index == -1: if split_index == -1:
split_index = message.rfind(" ", 0, chunk_size) split_index = message.rfind(" ", 0, chunk_size)
# If still no break point found, force chunk size limit
if split_index == -1: if split_index == -1:
split_index = chunk_size split_index = chunk_size
message_split_part = message[:split_index].strip() message_split_part = message[:split_index].strip()
message_remained_part = message[split_index:].strip() message_remained_part = message[split_index:].strip()
# Put the split part in the begining of the result list
split_result.append(message_split_part) split_result.append(message_split_part)
# And go for a recursive adventure with the remained message part
split_result += self.split_message(message=message_remained_part, chunk_size=chunk_size) split_result += self.split_message(message=message_remained_part, chunk_size=chunk_size)
return split_result return split_result
async def setup(bot):
"""✅ Correct async cog setup for Redbot"""
await bot.add_cog(ReginaldCog(bot))
+17 -42
View File
@@ -1,11 +1,10 @@
from datetime import datetime, timezone from datetime import datetime, timezone
from os import environ from os import environ
import requests
import json import json
import requests #WEATHER_API_KEY = environ.get('WEATHER_API_KEY')
URL = 'http://api.weatherapi.com/v1'
URL = "https://api.weatherapi.com/v1"
REQUEST_TIMEOUT_SECONDS = 10
def time_now() -> str: def time_now() -> str:
@@ -17,14 +16,10 @@ def get_current_weather(location: str) -> str:
return json.dumps(weather.realtime()) return json.dumps(weather.realtime())
def get_weather_forecast(location: str, days: int = 0) -> str: def get_weather_forecast(location: str, days: int = None) -> str:
if days is None: days += 1
days = 0
days = int(days) + 1
days = max(1, days) days = max(1, days)
days = min(14, days) days = min(14, days)
weather = Weather(location=location) weather = Weather(location=location)
return json.dumps(weather.forecast(days=days)) return json.dumps(weather.forecast(days=days))
@@ -32,7 +27,7 @@ def get_weather_forecast(location: str, days: int = 0) -> str:
class Weather: class Weather:
def __init__(self, location: str): def __init__(self, location: str):
self.__location = location self.__location = location
self.api_key = environ.get("WEATHER_API_KEY") self.api_key = environ.get('WEATHER_API_KEY')
@property @property
def location(self) -> str: def location(self) -> str:
@@ -40,48 +35,28 @@ class Weather:
@staticmethod @staticmethod
def make_request(method: str, params: dict) -> dict: def make_request(method: str, params: dict) -> dict:
try: response = requests.get(url=f'{URL}{method}', params=params)
response = requests.get( return response.json()
url=f"{URL}{method}",
params=params,
timeout=REQUEST_TIMEOUT_SECONDS,
)
response.raise_for_status()
payload = response.json()
except requests.RequestException as error:
return {"error": f"Weather API request failed: {error}"}
except ValueError as error:
return {"error": f"Weather API returned invalid JSON: {error}"}
if isinstance(payload, dict) and "error" in payload:
api_error = payload["error"]
if isinstance(api_error, dict):
message = api_error.get("message", "Unknown weather API error")
else:
message = str(api_error)
return {"error": message}
return payload
def realtime(self): def realtime(self):
method = "/current.json" method = '/current.json'
params = { params = {
"key": self.api_key, 'key': self.api_key,
"q": self.location, 'q': self.location,
} }
return self.make_request(method=method, params=params) return self.make_request(method=method, params=params)
def forecast(self, days: int = 14): def forecast(self, days: int = 14):
method = "/forecast.json" method = '/forecast.json'
params = { params = {
"key": self.api_key, 'key': self.api_key,
"q": self.location, 'q': self.location,
"days": days, 'days': days,
} }
return self.make_request(method=method, params=params) return self.make_request(method=method, params=params)
if __name__ == "__main__": if __name__ == '__main__':
test_weather = Weather("Aqtobe") test_weather = Weather('Aqtobe')
result = json.dumps(test_weather.forecast(days=13), indent=2) result = json.dumps(test_weather.forecast(days=13), indent=2)
print(result) print(result)