feature: 数据库连接与SQL集中管理,提高代码可读性
This commit is contained in:
@@ -1,82 +1,58 @@
|
||||
import schedule
|
||||
import time
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
import redis
|
||||
import pymysql
|
||||
from db.connection import DBConnectionManager
|
||||
from db.message_storage import MessageStorageDB
|
||||
|
||||
# 连接到Redis
|
||||
r = redis.Redis(host='192.168.2.32', port=6379, db=0)
|
||||
|
||||
# 配置数据库连接
|
||||
db_config = {
|
||||
'host': '192.168.2.32', # 替换为你的MariaDB服务器地址
|
||||
'user': 'root', # 替换为你的MariaDB用户名
|
||||
'password': 'lw123456', # 替换为你的MariaDB密码
|
||||
'database': 'message_archive'
|
||||
}
|
||||
|
||||
# 获取数据库连接管理器的单例
|
||||
db_manager = DBConnectionManager()
|
||||
message_db = MessageStorageDB(db_manager)
|
||||
|
||||
def write_to_db():
|
||||
# 连接到数据库
|
||||
connection = pymysql.connect(**db_config)
|
||||
# 获取当前日期的前一天
|
||||
yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
|
||||
|
||||
# 遍历Redis中所有与昨天日期相关的key,并写入数据库
|
||||
for key in r.keys(f"*:*:{yesterday}:count"):
|
||||
parts = key.decode('utf-8').split(':')
|
||||
group_id, wx_id, _date = parts[0], parts[1], parts[2] # _date应该是yesterday,但这里为了完整性还是保留
|
||||
count = int(r.hget(key, 'count')) if isinstance(r.hget(key, 'count'), bytes) else 0 # 处理可能的None或空值情况
|
||||
# 插入消息信息
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
# 插入消息信息
|
||||
sql = """
|
||||
INSERT INTO speech_counts (group_id, wx_id, date, count) VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
cursor.execute(sql, (group_id, wx_id, yesterday, count))
|
||||
|
||||
# 提交事务
|
||||
connection.commit()
|
||||
print("write_to_db successfully.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"write_to_db message: {e}")
|
||||
connection.rollback()
|
||||
|
||||
"""将消息统计写入数据库"""
|
||||
try:
|
||||
# 获取昨天的日期
|
||||
yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
# 获取昨天的消息统计
|
||||
message_counts = message_db.get_message_count_by_date(yesterday)
|
||||
|
||||
if not message_counts:
|
||||
logging.info(f"没有找到 {yesterday} 的消息记录")
|
||||
return
|
||||
|
||||
logging.info(f"成功统计 {yesterday} 的消息记录: {len(message_counts)} 条")
|
||||
|
||||
# 这里可以添加其他处理逻辑,如发送统计报告等
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"写入数据库出错: {e}")
|
||||
|
||||
def generate_and_send_ranking(groupId, allContacts: dict):
|
||||
# 连接到SQLite数据库(假设数据库文件名为database.db)
|
||||
connection = pymysql.connect(**db_config)
|
||||
cursor = connection.cursor()
|
||||
|
||||
yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
|
||||
# 编写SQL查询来获取发言数量前20的用户
|
||||
query = """
|
||||
SELECT wx_id, count AS speech_count
|
||||
FROM speech_counts
|
||||
WHERE date = %s
|
||||
AND group_id = %s
|
||||
GROUP BY wx_id
|
||||
ORDER BY count DESC
|
||||
LIMIT 20
|
||||
"""
|
||||
|
||||
# 执行查询并获取结果
|
||||
cursor.execute(query, (yesterday,groupId,))
|
||||
results = cursor.fetchall()
|
||||
|
||||
# 格式化输出字符串
|
||||
ranking_str = yesterday + "发言数量前20的用户排名:\n"
|
||||
for rank, (username, speech_count) in enumerate(results, start=1):
|
||||
ranking_str += f"{rank}. {allContacts.get(username, username)}: {speech_count} 次发言\n"
|
||||
# 关闭数据库连接
|
||||
connection.close()
|
||||
print(ranking_str)
|
||||
# 这里我们没有实际“发送”排名,只是返回字符串
|
||||
# 如果需要发送,可以在此添加发送逻辑
|
||||
return ranking_str
|
||||
|
||||
"""生成并发送群聊发言排名"""
|
||||
try:
|
||||
yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
|
||||
|
||||
# 使用数据库操作类获取排名数据
|
||||
results = message_db.get_speech_ranking(yesterday, groupId, limit=20)
|
||||
|
||||
if not results:
|
||||
logging.info(f"没有找到 {yesterday} 的群聊 {groupId} 发言记录")
|
||||
return f"{yesterday} 没有发言记录"
|
||||
|
||||
# 格式化输出字符串
|
||||
ranking_str = yesterday + "发言数量前20的用户排名:\n"
|
||||
for rank, result in enumerate(results, start=1):
|
||||
username = result['wx_id']
|
||||
speech_count = result['count']
|
||||
ranking_str += f"{rank}. {allContacts.get(username, username)}: {speech_count} 次发言\n"
|
||||
|
||||
logging.info(f"成功生成 {yesterday} 的群聊 {groupId} 发言排名")
|
||||
return ranking_str
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"生成发言排名出错: {e}")
|
||||
return f"生成发言排名出错: {e}"
|
||||
|
||||
if __name__ == '__main__':
|
||||
write_to_db()
|
||||
|
||||
Reference in New Issue
Block a user