Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
087566811a | ||
|
|
095bd828cf | ||
|
|
0387dafef8 | ||
|
|
0e2becc212 | ||
|
|
b69f169892 | ||
|
|
40b3b900ac | ||
|
|
73bf08843f | ||
|
|
d2edf0e60d | ||
|
|
bd4b05d2d4 | ||
|
|
eb7733be69 | ||
|
|
131999816b | ||
|
|
ff70196756 | ||
|
|
180c167a43 | ||
|
|
75af912bf5 | ||
|
|
a64a07511d | ||
|
|
9209cc568d | ||
|
|
7056315d5f | ||
|
|
b77dc31ea5 | ||
|
|
ad59a695af | ||
|
|
89b98fc5af | ||
|
|
97252a8062 | ||
|
|
0534ec6b15 | ||
|
|
11f39bb673 | ||
|
|
247e4417f5 | ||
|
|
bfe22e40ee | ||
|
|
59902085b3 | ||
|
|
3d59e45e7e |
@@ -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)
|
||||||
|
|||||||
@@ -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)
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
{
|
|
||||||
"convertable": true,
|
|
||||||
"units": {
|
|
||||||
"meter": {
|
|
||||||
"factor": 1,
|
|
||||||
"aliases": [
|
|
||||||
"meter",
|
|
||||||
"meters",
|
|
||||||
"m",
|
|
||||||
"m."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"kilometer": {
|
|
||||||
"factor": 1000,
|
|
||||||
"aliases": [
|
|
||||||
"kilometer",
|
|
||||||
"kilometers",
|
|
||||||
"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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"convertable": false
|
|
||||||
}
|
|
||||||
@@ -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])
|
|
||||||
@@ -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))
|
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
from dataclasses import dataclass, field, asdict
|
||||||
|
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 = field(default=None)
|
||||||
|
file_id: str = 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]
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
from dataclasses import dataclass, field, asdict
|
||||||
|
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,84 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from enum import Enum
|
||||||
|
from discord import Message
|
||||||
|
|
||||||
|
|
||||||
|
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, raw_message: object):
|
||||||
|
self.raw_message = raw_message
|
||||||
|
self.message: IClientMessage = None
|
||||||
|
|
||||||
|
def create_message(self) -> ClientMessage:
|
||||||
|
self.set_content() \
|
||||||
|
.set_author_name() \
|
||||||
|
.set_image_urls()
|
||||||
|
return self.message
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def set_content(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def set_author_name(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def set_image_urls(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DiscordMessageBuilder(IMessageBuilder):
|
||||||
|
def __init__(self, raw_message: Message):
|
||||||
|
self.raw_message = raw_message
|
||||||
|
self.message = ClientMessage()
|
||||||
|
|
||||||
|
def create_message(self) -> ClientMessage:
|
||||||
|
return super().create_message()
|
||||||
|
|
||||||
|
def set_author_name(self) -> 'DiscordMessageBuilder':
|
||||||
|
self.message.author_name = self.raw_message.author.name
|
||||||
|
return self
|
||||||
|
|
||||||
|
def set_content(self) -> 'DiscordMessageBuilder':
|
||||||
|
self.message.content = self.raw_message.content
|
||||||
|
return self
|
||||||
|
|
||||||
|
def set_image_urls(self) -> 'DiscordMessageBuilder':
|
||||||
|
self.message.image_urls = [
|
||||||
|
i.url
|
||||||
|
for i in self.raw_message.attachments
|
||||||
|
if i.content_type in ('image/jpeg', 'image/png', 'image/webp', 'image/gif')
|
||||||
|
]
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class MessengerTypes(Enum):
|
||||||
|
DISCORD = DiscordMessageBuilder
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
class TestAuthor:
|
||||||
|
name = 'John Doe'
|
||||||
|
|
||||||
|
|
||||||
|
class TestMessage:
|
||||||
|
content = 'Hello!'
|
||||||
|
author = TestAuthor()
|
||||||
|
|
||||||
|
|
||||||
|
message = DiscordMessageBuilder(raw_message=TestMessage).create_message()
|
||||||
|
print(message.__dict__)
|
||||||
+33
-33
@@ -16,7 +16,6 @@ from .weather import time_now, get_current_weather, get_weather_forecast
|
|||||||
from .tools_description import TOOLS
|
from .tools_description import TOOLS
|
||||||
from .debug_stuff import debug
|
from .debug_stuff import debug
|
||||||
|
|
||||||
|
|
||||||
CALLABLE_FUNCTIONS = {
|
CALLABLE_FUNCTIONS = {
|
||||||
# Dictionary with functions to call.
|
# Dictionary with functions to call.
|
||||||
# You can use globals()[func_name](**args) instead, but that's too implicit.
|
# You can use globals()[func_name](**args) instead, but that's too implicit.
|
||||||
@@ -71,7 +70,7 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
async def on_message(self, message):
|
async def on_message(self, message):
|
||||||
if message.author.bot or not message.guild:
|
if message.author.bot or not message.guild:
|
||||||
return # Ignore bots and DMs
|
return # Ignore bots and DMs
|
||||||
|
|
||||||
# ✅ Check if user is blacklisted
|
# ✅ Check if user is blacklisted
|
||||||
if await self.is_blacklisted(message.author):
|
if await self.is_blacklisted(message.author):
|
||||||
return # Ignore message if user is explicitly blacklisted
|
return # Ignore message if user is explicitly blacklisted
|
||||||
@@ -80,7 +79,6 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
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 # Ignore message if user has no permissions
|
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)
|
||||||
user_id = str(message.author.id)
|
user_id = str(message.author.id)
|
||||||
@@ -115,8 +113,8 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
await message.channel.send(random.choice(["Yes?", "How may I assist?", "You rang?"]))
|
await message.channel.send(random.choice(["Yes?", "How may I assist?", "You rang?"]))
|
||||||
return
|
return
|
||||||
explicit_invocation = True
|
explicit_invocation = True
|
||||||
|
|
||||||
# ✅ Passive Listening: Check if the message contains relevant keywords
|
# ✅ Passive Listening: Check if the message contains relevant keywords
|
||||||
elif self.should_reginald_interject(message_content):
|
elif self.should_reginald_interject(message_content):
|
||||||
prompt = message_content
|
prompt = message_content
|
||||||
explicit_invocation = False
|
explicit_invocation = False
|
||||||
@@ -124,11 +122,11 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
else:
|
else:
|
||||||
return # Ignore irrelevant messages
|
return # Ignore irrelevant messages
|
||||||
|
|
||||||
# ✅ Context Handling: Maintain conversation flow
|
# ✅ Context Handling: Maintain conversation flow
|
||||||
if memory and memory[-1]["user"] == user_name:
|
if memory and memory[-1]["user"] == user_name:
|
||||||
prompt = f"Continuation of the discussion:\n{prompt}"
|
prompt = f"Continuation of the discussion:\n{prompt}"
|
||||||
|
|
||||||
# ✅ Prepare context messages
|
# ✅ Prepare context messages
|
||||||
formatted_messages = [{"role": "system", "content": self.get_reginald_persona()}]
|
formatted_messages = [{"role": "system", "content": self.get_reginald_persona()}]
|
||||||
|
|
||||||
if user_profile:
|
if user_profile:
|
||||||
@@ -145,10 +143,10 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
"content": f"[{summary['timestamp']}] Topics: {', '.join(summary['topics'])}\n{summary['summary']}"
|
"content": f"[{summary['timestamp']}] Topics: {', '.join(summary['topics'])}\n{summary['summary']}"
|
||||||
})
|
})
|
||||||
|
|
||||||
formatted_messages += [{"role": "user", "content": f"{entry['user']}: {entry['content']}"} for entry in memory]
|
formatted_messages += [{"role": "user", "content": f"{entry['user']}: {entry['content']}"} for entry in
|
||||||
|
memory]
|
||||||
formatted_messages.append({"role": "user", "content": f"{user_name}: {prompt}"})
|
formatted_messages.append({"role": "user", "content": f"{user_name}: {prompt}"})
|
||||||
|
|
||||||
|
|
||||||
##################################################
|
##################################################
|
||||||
# #
|
# #
|
||||||
## Generate AI Response, put into response_text ##
|
## Generate AI Response, put into response_text ##
|
||||||
@@ -166,7 +164,8 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
memory.append({"user": "Reginald", "content": response_text})
|
memory.append({"user": "Reginald", "content": response_text})
|
||||||
|
|
||||||
if len(memory) > self.short_term_memory_limit:
|
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)])
|
summary = await self.summarize_memory(message, memory[:int(
|
||||||
|
self.short_term_memory_limit * self.summary_retention_ratio)])
|
||||||
mid_memory.setdefault(channel_id, []).append({
|
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),
|
||||||
@@ -174,20 +173,20 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
})
|
})
|
||||||
if len(mid_memory[channel_id]) > self.summary_retention_limit:
|
if len(mid_memory[channel_id]) > self.summary_retention_limit:
|
||||||
mid_memory[channel_id].pop(0)
|
mid_memory[channel_id].pop(0)
|
||||||
memory = memory[-(self.short_term_memory_limit - int(self.short_term_memory_limit * self.summary_retention_ratio)):]
|
memory = memory[-(self.short_term_memory_limit - int(
|
||||||
|
self.short_term_memory_limit * self.summary_retention_ratio)):]
|
||||||
|
|
||||||
short_memory[channel_id] = memory
|
short_memory[channel_id] = memory
|
||||||
|
|
||||||
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:
|
||||||
"""Determines if Reginald should respond to a message based on keywords."""
|
"""Determines if Reginald should respond to a message based on keywords."""
|
||||||
direct_invocation = {
|
direct_invocation = {
|
||||||
"reginald,"
|
"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)
|
||||||
|
|
||||||
@debug
|
@debug
|
||||||
@@ -227,8 +226,8 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
'content': func_result,
|
'content': func_result,
|
||||||
'tool_call_id': tool_call_id,
|
'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
|
# Second completion required if functions has been called to interpret the result into user-friendly
|
||||||
# chat message.
|
# chat message.
|
||||||
response = await client.chat.completions.create(**completion_args)
|
response = await client.chat.completions.create(**completion_args)
|
||||||
@@ -261,11 +260,12 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
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(name="reginald_set_listening_channel", help="Set the channel where Reginald listens for messages.")
|
@commands.command(name="reginald_set_listening_channel",
|
||||||
|
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."""
|
"""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
|
||||||
@@ -273,12 +273,13 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
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(name="reginald_get_listening_channel", help="Check which channel Reginald is currently listening in.")
|
@commands.command(name="reginald_get_listening_channel",
|
||||||
|
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."""
|
"""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: # ✅ Prevents crash if channel was deleted
|
if channel: # ✅ Prevents crash if channel was deleted
|
||||||
@@ -288,18 +289,17 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
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 = ""):
|
||||||
|
# """Splits and sends a long message to avoid Discord's 2000-character limit."""
|
||||||
|
# chunk_size = 1900 # Leave some space for formatting
|
||||||
|
# if prefix:
|
||||||
|
# prefix_length = len(prefix)
|
||||||
|
# chunk_size -= prefix_length
|
||||||
|
#
|
||||||
|
# for i in range(0, len(message), chunk_size):
|
||||||
|
# chunk = message[i:i + chunk_size]
|
||||||
|
# await ctx.send(f"{prefix}{chunk}")
|
||||||
|
|
||||||
async def send_long_message(self, ctx, message, prefix: str = ""):
|
|
||||||
"""Splits and sends a long message to avoid Discord's 2000-character limit."""
|
|
||||||
chunk_size = 1900 # Leave some space for formatting
|
|
||||||
if prefix:
|
|
||||||
prefix_length = len(prefix)
|
|
||||||
chunk_size -= prefix_length
|
|
||||||
|
|
||||||
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 = ""):
|
||||||
"""
|
"""
|
||||||
Sends a long message to Discord while ensuring it does not exceed the 2000-character limit.
|
Sends a long message to Discord while ensuring it does not exceed the 2000-character limit.
|
||||||
@@ -351,4 +351,4 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
|
|||||||
|
|
||||||
async def setup(bot):
|
async def setup(bot):
|
||||||
"""✅ Correct async cog setup for Redbot"""
|
"""✅ Correct async cog setup for Redbot"""
|
||||||
await bot.add_cog(ReginaldCog(bot))
|
await bot.add_cog(ReginaldCog(bot))
|
||||||
|
|||||||
Reference in New Issue
Block a user