mirror of
https://github.com/alterware/aw-bot.git
synced 2025-12-13 04:57:51 +00:00
chore: do not store text in memory
This commit is contained in:
@@ -1 +1 @@
|
||||
from .load_db import load_chat_messages_from_db
|
||||
from .load_db import load_chat_messages_from_db, read_random_message_from_collection
|
||||
|
||||
@@ -54,7 +54,7 @@ def write_deleted_message_to_collection(
|
||||
return []
|
||||
|
||||
|
||||
def read_message_from_collection(
|
||||
def read_messages_from_collection(
|
||||
database="discord_bot",
|
||||
collection="messages",
|
||||
):
|
||||
@@ -91,10 +91,55 @@ def read_message_from_collection(
|
||||
return []
|
||||
|
||||
|
||||
def read_random_message_from_collection(
|
||||
database="discord_bot",
|
||||
collection="messages",
|
||||
):
|
||||
"""
|
||||
Loads a random chat message from MongoDB.
|
||||
|
||||
Args:
|
||||
database (str): Name of the MongoDB database
|
||||
collection (str): Name of the collection
|
||||
|
||||
Returns:
|
||||
str or None: random message string, or None if collection is empty
|
||||
"""
|
||||
mongo_uri = get_mongodb_uri()
|
||||
|
||||
try:
|
||||
with MongoClient(mongo_uri) as client:
|
||||
db = client[database]
|
||||
col = db[collection]
|
||||
|
||||
logger.debug(
|
||||
f"Connecting to MongoDB at {mongo_uri}, DB='{database}', Collection='{collection}'"
|
||||
)
|
||||
|
||||
# Use aggregation with $sample to get a random document
|
||||
pipeline = [{"$sample": {"size": 1}}]
|
||||
|
||||
cursor = col.aggregate(pipeline)
|
||||
# almost random
|
||||
random_docs = list(cursor)
|
||||
|
||||
if random_docs and "message" in random_docs[0]:
|
||||
message = random_docs[0]["message"]
|
||||
logger.info(f"Loaded random message from MongoDB: {message[:100]}...")
|
||||
return message
|
||||
|
||||
logger.warning("No messages found in collection")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load random message from MongoDB: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def load_chat_messages_from_db():
|
||||
messages = []
|
||||
|
||||
messages = read_message_from_collection()
|
||||
messages = read_messages_from_collection()
|
||||
if not messages:
|
||||
logger.warning("messages collection is empty after loading from MongoDB!")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user