加入聊天记录入库动作

This commit is contained in:
liuwei
2025-02-06 11:47:04 +08:00
parent 3354782204
commit c8b59eb788
3 changed files with 67 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
CREATE DATABASE message_archive charset utf8mb4;
USE message_archive;
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
timestamp VARCHAR(20) NOT NULL,
sender VARCHAR(255) NOT NULL,
content TEXT NULL,
message_type VARCHAR(50) NULL,
attachment_url VARCHAR(512) DEFAULT NULL
);

View File

@@ -0,0 +1,46 @@
import pymysql
# 配置数据库连接
db_config = {
'host': '192.168.2.32', # 替换为你的MariaDB服务器地址
'user': 'root', # 替换为你的MariaDB用户名
'password': 'lw123456', # 替换为你的MariaDB密码
'database': 'message_archive'
}
def archive_message(timestamp_str, sender, content, message_type, attachment_url=None):
# 连接到数据库
connection = pymysql.connect(**db_config)
try:
with connection.cursor() as cursor:
# 插入消息信息
sql = """
INSERT INTO messages (timestamp, sender, content, message_type, attachment_url)
VALUES (%s, %s, %s, %s, %s)
"""
cursor.execute(sql, (timestamp_str, sender, content, message_type, attachment_url))
# 提交事务
connection.commit()
print("Message archived successfully.")
except Exception as e:
print(f"Error archiving message: {e}")
connection.rollback()
finally:
# 关闭连接
connection.close()
# 示例用法
if __name__ == "__main__":
timestamp_str = "2025-02-06 11:15:28"
sender = "XXX"
content = "This is a test message with a string timestamp."
message_type = "text"
attachment_url = "http://example.com/attachment.pdf" # 可以为None如果没有附件
archive_message(timestamp_str, sender, content, message_type, attachment_url)

View File

@@ -6,6 +6,7 @@ import time
import xml.etree.ElementTree as ET
from queue import Empty
from threading import Thread
from datetime import datetime, timedelta
from base.func_epic import is_friday, get_free
from base.func_zhipu import ZhiPu
@@ -27,6 +28,7 @@ __version__ = "39.2.4.0"
from message_report.process_message import process_message
from message_report.write_db import write_to_db, generate_and_send_ranking
from message_storage.message_to_db import archive_message
class Robot(Job):
@@ -158,6 +160,12 @@ class Robot(Job):
except Exception as e:
self.LOG.error(f"process_message error: {e}")
# 聊天记录入库动作:
try:
archive_message(datetime.now(),msg.sender,msg.content,msg.type,msg.extra)
except Exception as e:
self.LOG.error(f"archive_message error: {e}")
# 如果在群里被 @
if msg.roomid not in self.config.GROUPS: # 不在配置的响应的群列表里,忽略
return