481 lines
18 KiB
Python
481 lines
18 KiB
Python
import random
|
||
from datetime import datetime
|
||
import pymysql
|
||
|
||
from game_task.game_chatgpt_qa import game_question_json, game_answer_json
|
||
|
||
# 数据库连接配置
|
||
db_config = {
|
||
'host': '192.168.2.32',
|
||
'user': 'root',
|
||
'password': 'lw123456',
|
||
'database': 'message_archive',
|
||
'charset': 'utf8mb4',
|
||
'cursorclass': pymysql.cursors.DictCursor
|
||
}
|
||
|
||
|
||
# 连接数据库
|
||
def get_db_connection():
|
||
return pymysql.connect(**db_config)
|
||
|
||
|
||
# 添加群聊
|
||
def add_group(group_id, player_id):
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
try:
|
||
cursor.execute(
|
||
"INSERT INTO t_encyclopedia_groups (group_id) VALUES (%s)",
|
||
(group_id,)
|
||
)
|
||
conn.commit()
|
||
message = f"🎉 群 {group_id} 已就位,准备开燥!"
|
||
return {"message": message, "player_id": player_id}
|
||
except pymysql.err.IntegrityError:
|
||
message = f"🌟 群 {group_id} 早就蓄势待发啦!"
|
||
return {"message": message, "player_id": player_id}
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
|
||
# 获取所有群聊ID
|
||
def get_group_ids():
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
try:
|
||
cursor.execute("SELECT group_id FROM t_encyclopedia_groups")
|
||
return [row['group_id'] for row in cursor.fetchall()]
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
|
||
# 确保游戏启动(自动初始化群聊和玩家)
|
||
def ensure_game_started(group_id, player_id, player_name="未知玩家"):
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
try:
|
||
# 检查并添加群聊
|
||
cursor.execute("SELECT group_id FROM t_encyclopedia_groups WHERE group_id = %s", (group_id,))
|
||
if not cursor.fetchone():
|
||
add_group(group_id, player_id)
|
||
|
||
# 检查并添加玩家
|
||
cursor.execute(
|
||
"SELECT player_name FROM t_encyclopedia_players WHERE group_id = %s AND player_id = %s",
|
||
(group_id, player_id)
|
||
)
|
||
existing_player = cursor.fetchone()
|
||
if not existing_player:
|
||
cursor.execute(
|
||
"INSERT INTO t_encyclopedia_players (player_id, group_id, player_name) VALUES (%s, %s, %s)",
|
||
(player_id, group_id, player_name)
|
||
)
|
||
conn.commit()
|
||
message = (
|
||
f"🎉 哇塞,{player_name} 你来啦!\n"
|
||
f"🌟 群 {group_id} 瞬间燃爆!\n"
|
||
f"🎈 快来接任务,秀翻全场!指令: /t"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
return {"message": None, "player_id": player_id}
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
|
||
# 随机分配任务
|
||
def assign_random_task(group_id, player_id=None):
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
try:
|
||
cursor.execute("SELECT player_id, player_name FROM t_encyclopedia_players WHERE group_id = %s", (group_id,))
|
||
players = cursor.fetchall()
|
||
if not players:
|
||
message = (
|
||
f"😔 哎呀,群 {group_id} 静悄悄\n"
|
||
f"🌟 快拉小伙伴来嗨吧!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
|
||
if player_id:
|
||
player_dict = {p['player_id']: p['player_name'] for p in players}
|
||
if player_id not in player_dict:
|
||
message = (
|
||
f"😅 嘿,{player_id} 你谁啊?\n"
|
||
f"🌟 先用 /s 报名,不然没法玩哦!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
holder_id = player_id
|
||
holder_name = player_dict[player_id]
|
||
else:
|
||
holder = random.choice(players)
|
||
holder_id = holder['player_id']
|
||
holder_name = holder['player_name']
|
||
|
||
task = game_question_json("请出题!")
|
||
category = task["category"]
|
||
question = task["question"]
|
||
answer = task["answer"]
|
||
score = int(task["score"])
|
||
description = task.get("description", "")
|
||
|
||
cursor.execute(
|
||
"INSERT INTO t_encyclopedia_active_tasks (group_id, question, answer, score, description, holder_id) VALUES (%s, %s, %s, %s, %s, %s)",
|
||
(group_id, question, answer, score, description, holder_id)
|
||
)
|
||
conn.commit()
|
||
|
||
cursor.execute(
|
||
"SELECT active_task_id FROM t_encyclopedia_active_tasks WHERE group_id = %s AND question = %s AND holder_id = %s ORDER BY assigned_at DESC LIMIT 1",
|
||
(group_id, question, holder_id)
|
||
)
|
||
active_task_id = cursor.fetchone()['active_task_id']
|
||
|
||
if player_id:
|
||
message = (
|
||
f"🎁 {holder_name},你的专属任务闪亮登场!\n"
|
||
f"🎀 任务ID: {active_task_id}\n"
|
||
f"🎈 问题:[{category}]{question}\n"
|
||
f"🌼 积分:{score}\n"
|
||
f"🌈 快上答案:/a {active_task_id} 答案"
|
||
)
|
||
else:
|
||
message = (
|
||
f"🎁 新任务来袭,够不够刺激?\n"
|
||
f"🎀 任务ID: {active_task_id}\n"
|
||
f"🌟 幸运鹅:{holder_name}\n"
|
||
f"🎈 问题:[{category}]{question}\n"
|
||
f"🌼 积分:{score}\n"
|
||
f"🌈 抢答格式:/a {active_task_id} 答案"
|
||
)
|
||
return {"message": message, "player_id": holder_id}
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
|
||
# 提交答案并计分
|
||
def submit_answer(group_id, player_id, task_id, answer):
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
try:
|
||
cursor.execute("SELECT player_name FROM t_encyclopedia_players WHERE group_id = %s AND player_id = %s",
|
||
(group_id, player_id))
|
||
player_row = cursor.fetchone()
|
||
if not player_row:
|
||
message = (
|
||
f"😅 嘿,{player_id} 你是路人甲吗?\n"
|
||
f"🌟 用 /s 先加入群 {group_id} 吧!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
|
||
player_name = player_row['player_name']
|
||
|
||
if not task_id.isdigit():
|
||
message = (
|
||
f"😅 喂,任务ID得是数字好吗?\n"
|
||
f"🌟 比如:1\n"
|
||
f"🎈 别瞎搞,重新来!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
|
||
active_task_id = int(task_id)
|
||
|
||
cursor.execute(
|
||
"SELECT question, answer, score, holder_id, status FROM t_encyclopedia_active_tasks WHERE group_id = %s AND active_task_id = %s",
|
||
(group_id, active_task_id)
|
||
)
|
||
task_data = cursor.fetchone()
|
||
if not task_data:
|
||
message = (
|
||
f"😔 哎哟,任务 task_{active_task_id} 不翼而飞啦!\n"
|
||
f"🌼 可能被别人抢先一步咯!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
|
||
if task_data['status'] == 'completed':
|
||
message = (
|
||
f"😄 哈哈,你慢了一步!\n"
|
||
f"🌟 任务 task_{active_task_id} 已经完结\n"
|
||
f"🎈 快去抢新任务吧!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
|
||
question, correct_answer_db, top_score, holder_id, _ = task_data['question'], task_data['answer'].lower(), \
|
||
task_data['score'], task_data['holder_id'], task_data['status']
|
||
|
||
cursor.execute("SELECT player_name FROM t_encyclopedia_players WHERE group_id = %s AND player_id = %s",
|
||
(group_id, holder_id))
|
||
holder_name = cursor.fetchone()['player_name']
|
||
|
||
answer_json = {"question": question, "top_score": str(top_score), "answer": answer}
|
||
result = game_answer_json(answer_json)
|
||
points = int(result["score"])
|
||
description = result["description"]
|
||
is_correct = points > 0
|
||
|
||
if is_correct:
|
||
cursor.execute(
|
||
"UPDATE t_encyclopedia_players SET points = points + %s WHERE group_id = %s AND player_id = %s",
|
||
(points, group_id, player_id)
|
||
)
|
||
cursor.execute(
|
||
"UPDATE t_encyclopedia_active_tasks SET status = 'completed' WHERE group_id = %s AND active_task_id = %s",
|
||
(group_id, active_task_id)
|
||
)
|
||
if player_id == holder_id:
|
||
message = (
|
||
f"🎉 {player_name} 你是天才吗?\n"
|
||
f"🌟 任务:{question}\n"
|
||
f"🎈 答对啦,简直无敌!\n"
|
||
f"🌈 奖励:{points} 分\n"
|
||
f"🎀 彩蛋:{description}"
|
||
)
|
||
else:
|
||
message = (
|
||
f"🎉 {player_name} 抢答王上线!\n"
|
||
f"🌟 任务:{question}\n"
|
||
f"🎈 原主:{holder_name} 被你截胡啦!\n"
|
||
f"🌈 狂揽 {points} 分,太骚了!\n"
|
||
f"🎀 彩蛋:{description}"
|
||
)
|
||
else:
|
||
cursor.execute(
|
||
"UPDATE t_encyclopedia_players SET points = GREATEST(points - 1, 0) WHERE group_id = %s AND player_id = %s",
|
||
(group_id, player_id)
|
||
)
|
||
points = -1
|
||
message = (
|
||
f"😅 {player_name} 你这是要笑死我吗?\n"
|
||
f"🌼 任务:{question}\n"
|
||
f"🎈 你答:{answer}\n"
|
||
f"🌟 正确答案:{correct_answer_db}\n"
|
||
f"🌈 扣 1 分,别哭哦!\n"
|
||
f"🎀 提示:{description}\n"
|
||
f"🌟 任务ID: {active_task_id} 还能抢救一下!"
|
||
)
|
||
|
||
cursor.execute(
|
||
"INSERT INTO t_encyclopedia_task_history (group_id, active_task_id, player_id, answer, is_correct, points_earned) VALUES (%s, %s, %s, %s, %s, %s)",
|
||
(group_id, active_task_id, player_id, answer, is_correct, points)
|
||
)
|
||
conn.commit()
|
||
|
||
return {"message": message, "player_id": player_id}
|
||
except ValueError as e:
|
||
print(f"submit_answer:{e}")
|
||
message = (
|
||
f"😅 喂,任务ID得是数字懂吗?\n"
|
||
f"🌟 比如:1\n"
|
||
f"🎈 重来,别皮!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
except Exception as e:
|
||
print(f"submit_answer:{e}")
|
||
message = (
|
||
f"😅 出错了,任务ID得是数字哦!\n"
|
||
f"🌟 比如:1\n"
|
||
f"🎈 再试一次吧!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
|
||
# 显示排行榜
|
||
def show_rank(group_id, player_id):
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
try:
|
||
cursor.execute(
|
||
"SELECT player_name, points FROM t_encyclopedia_players WHERE group_id = %s ORDER BY points DESC LIMIT 10",
|
||
(group_id,)
|
||
)
|
||
ranks = cursor.fetchall()
|
||
if not ranks:
|
||
message = (
|
||
f"😔 群 {group_id} 冷冷清清\n"
|
||
f"🌟 快来一起燥起来吧!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
rank_text = f"🎉 群 {group_id} 排行榜(Top 10)来啦!\n"
|
||
for i, row in enumerate(ranks, 1):
|
||
rank_text += f"🐓 {i}. {row['player_name']}: {row['points']} 分\n"
|
||
return {"message": rank_text, "player_id": player_id}
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
|
||
# 显示当前活跃任务
|
||
def show_active_tasks(group_id, player_id):
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
try:
|
||
cursor.execute("""
|
||
SELECT a.active_task_id, a.question, p.player_name, p.player_id
|
||
FROM t_encyclopedia_active_tasks a
|
||
JOIN t_encyclopedia_players p ON a.holder_id = p.player_id AND a.group_id = p.group_id
|
||
WHERE a.group_id = %s AND a.status = 'pending'
|
||
""", (group_id,))
|
||
tasks = cursor.fetchall()
|
||
if not tasks:
|
||
message = (
|
||
f"😄 群 {group_id} 现在一片祥和\n"
|
||
f"🌟 没任务?快用 /t 搞一个!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
task_text = f"🎉 群 {group_id} 活跃任务速递:\n"
|
||
for task in tasks:
|
||
task_text += (
|
||
f"🌈 任务ID: task_{task['active_task_id']}\n"
|
||
f"🎀 问题:{task['question']}\n"
|
||
f"🌼 大佬:{task['player_name']}\n"
|
||
)
|
||
return {"message": task_text, "player_id": player_id}
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
|
||
# 列举所有未完成任务
|
||
def list_uncompleted_tasks(group_id, player_id):
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
try:
|
||
cursor.execute("""
|
||
SELECT a.active_task_id, a.question, p.player_name, p.player_id
|
||
FROM t_encyclopedia_active_tasks a
|
||
JOIN t_encyclopedia_players p ON a.holder_id = p.player_id AND a.group_id = p.group_id
|
||
WHERE a.group_id = %s AND a.status = 'pending'
|
||
""", (group_id,))
|
||
tasks = cursor.fetchall()
|
||
if not tasks:
|
||
message = (
|
||
f"😄 群 {group_id} 全员开挂?\n"
|
||
f"🌟 没未完成任务,快用 /t 再战!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
task_text = f"🎉 群 {group_id} 未完成任务大曝光:\n"
|
||
for task in tasks:
|
||
task_text += (
|
||
f"🌈 任务ID: task_{task['active_task_id']}\n"
|
||
f"🎀 问题:{task['question']}\n"
|
||
f"🌼 主人:{task['player_name']}\n"
|
||
)
|
||
return {"message": task_text, "player_id": player_id}
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
|
||
# 定时任务:整点触发,排除23:00-08:00
|
||
def run_random_task_assignment(group_id):
|
||
current_hour = datetime.now().hour
|
||
if current_hour >= 23 or current_hour < 9:
|
||
message = (
|
||
f"😴 现在 {current_hour}:00,小伙伴们都睡啦\n"
|
||
f"🌙 9点到22点再来嗨吧!"
|
||
)
|
||
print(f"{datetime.now()} 群 {group_id} 当前时间 {current_hour}:00 在23:00-08:00区间,跳过任务发放")
|
||
return {"message": message, "player_id": None}
|
||
result = assign_random_task(group_id)
|
||
print(f"{datetime.now()} {result['message']}")
|
||
return result
|
||
|
||
|
||
# 处理群聊消息
|
||
def game_process_message(group_id, player_id, message, player_name="未知玩家"):
|
||
init_result = ensure_game_started(group_id, player_id, player_name)
|
||
init_message = init_result["message"]
|
||
player_id = init_result["player_id"]
|
||
|
||
if message == "/s": # 可选:显式加入游戏
|
||
if init_message:
|
||
return {"message": init_message, "player_id": player_id}
|
||
message = (
|
||
f"😄 嘿,{player_name} 你来啦!\n"
|
||
f"🌼 已加入群 {group_id} 的狂欢\n"
|
||
f"🎶 快用 /t 开干吧!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
elif message == "/ts": # 查看活跃任务
|
||
if init_message:
|
||
message = init_message + "\n🌟 用 /ts 看看当前任务吧!"
|
||
return {"message": message, "player_id": player_id}
|
||
return show_active_tasks(group_id, player_id)
|
||
elif message == "/l": # 列出未完成任务
|
||
if init_message:
|
||
message = init_message + "\n🌟 用 /l 查未完成任务哦!"
|
||
return {"message": message, "player_id": player_id}
|
||
return list_uncompleted_tasks(group_id, player_id)
|
||
elif message.startswith("/a"): # 提交答案
|
||
if init_message:
|
||
message = init_message + "\n🌟 用 /a [任务ID] [答案] 放大招吧!"
|
||
return {"message": message, "player_id": player_id}
|
||
parts = message.split(" ", 2)
|
||
if len(parts) < 3:
|
||
message = (
|
||
f"😅 喂,格式不对啊!\n"
|
||
f"🌟 正确姿势:/a [任务ID] [答案]\n"
|
||
f"🎈 比如:/a 1 钒"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
task_id, answer = parts[1], parts[2]
|
||
return submit_answer(group_id, player_id, task_id, answer)
|
||
elif message == "/r": # 查看排行榜
|
||
if init_message:
|
||
message = init_message + "\n🌟 用 /r 看看谁是大佬!"
|
||
return {"message": message, "player_id": player_id}
|
||
return show_rank(group_id, player_id)
|
||
elif message == "/ag": # 可选:手动添加群聊
|
||
if init_message:
|
||
return {"message": init_message, "player_id": player_id}
|
||
return add_group(group_id, player_id)
|
||
elif message == "/t": # 获取任务
|
||
if init_message:
|
||
message = init_message + "\n🌟 已为你准备好任务,快接招!"
|
||
return {"message": message, "player_id": player_id}
|
||
current_hour = datetime.now().hour
|
||
if current_hour >= 23 or current_hour < 9:
|
||
message = (
|
||
f"😴 现在 {current_hour}:00\n"
|
||
f"🌙 太晚啦,大家都睡了!\n"
|
||
f"🌞 9点到22点再来嗨吧!"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
return assign_random_task(group_id, player_id)
|
||
else:
|
||
message = (
|
||
f"😄 嘿,二货!\n"
|
||
f"🌟 指令玩错啦!\n"
|
||
f"🎈 快试试这些:\n"
|
||
f"🌈 /s - 加入狂欢(可选)\n"
|
||
f"🎀 /ts - 看活跃任务\n"
|
||
f"🌼 /l - 未完成任务\n"
|
||
f"🌟 /a [任务ID] [答案] - 提交答案\n"
|
||
f"🎈 /ag - 加群(可选)\n"
|
||
f"🌈 /t - 抢任务\n"
|
||
f"🎀 /r - 谁是大佬"
|
||
)
|
||
return {"message": message, "player_id": player_id}
|
||
|
||
|
||
# 设置定时任务
|
||
def setup_schedule():
|
||
group_ids = get_group_ids()
|
||
for gid in group_ids:
|
||
run_random_task_assignment(group_id=gid)
|
||
|
||
|
||
# 主程序
|
||
if __name__ == "__main__":
|
||
# 测试用例
|
||
print(game_process_message("45317011307@chatroom", "Jyunere", "/t")) # 新用户获取任务
|
||
print(game_process_message("45317011307@chatroom", "Jyunere", "/a 18 罗马斗兽场")) # 提交答案
|
||
print(game_process_message("45317011307@chatroom", "Jyunere", "/r")) # 查看排行榜
|