File size: 19,965 Bytes
a452eb5
 
 
e3162a1
a452eb5
 
e3162a1
a452eb5
1
2
3
4
5
6
7
8
{
  "id": "be103a24-04c5-4bec-b053-590e15059986",
  "title": "AI",
  "content": "const { GoogleGenerativeAI } = require(\"@google/generative-ai\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst { database } = require(\"./../../utils/database\");\n\nmodule.exports.config = {\n  name: \"twan\",\n  version: \"2.2.0\",\n  hasPermssion: 0,\n  credits: \"Twan\",\n  description: \"AI nhân vật Twan (nam Bắc Ninh), trả lời dạng mảng JSON actions\",\n  commandCategory: \"AI\",\n  usages: \"[prompt] | setadmin [@mention] | clear\",\n  cooldowns: 2,\n  usePrefix: true,\n  dependencies: { \"@google/generative-ai\": \"\" }\n};\n\nconst API_KEYS = [\n  \"AIzaSyA6655iBVPi0rPNXjHuAha-FYKHvzMttZc\",\n  \"AIzaSyDh3HuPZN4j7icVdaoUbqlFdHPt8pwhmfc\",\n  \"AIzaSyBKQoL4OJ1EF1uYImW2yD4heXQ30P0uivA\",\n  \"AIzaSyClt9--5Fu7O_OuIfJCYKLLERhh7s7Ygo4\"\n];\nlet currentKeyIndex = 0;\nconst nextKey = () => (currentKeyIndex = (currentKeyIndex + 1) % API_KEYS.length, API_KEYS[currentKeyIndex]);\n\nconst CACHE_DIR = path.join(__dirname, \"cache\");\nif (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true });\nconst userRolesPath = path.join(CACHE_DIR, \"twan_userRoles.json\");\n\nlet userRoles = {};\ntry { if (fs.existsSync(userRolesPath)) userRoles = JSON.parse(fs.readFileSync(userRolesPath, \"utf8\")); } catch {}\nconst saveUserRoles = () => fs.writeFileSync(userRolesPath, JSON.stringify(userRoles, null, 2), \"utf8\");\n\nconst memory = database.createCollection(\"memory\");\nconst chatSessions = new Map();\nconst userInfoCache = {};\nconst aiErrors = []; \n\nconst cleanJsonResponse = (t) => {\n  const s = t.indexOf(\"[\"), e = t.lastIndexOf(\"]\");\n  if (s === -1 || e === -1) return `[{\\\"type\\\":\\\"chat\\\",\\\"content\\\":\\\"${t.replace(/\"/g,'\\\\\"')}\\\"}]`;\n  t = t.slice(s, e + 1).replace(/\\s+/g, \" \").trim().replace(/,(\\s*})/g, \"}\").replace(/,(\\s*])/g, \"]\");\n  return t;\n};\n\nconst normalize = (s) => (s || \"\").normalize(\"NFD\").replace(/\\p{Diacritic}/gu, \"\").toLowerCase().trim().replace(/\\s+/g, \" \");\nconst findUserByName = (userList=[], targetName=\"\", nicknames={}) => {\n  const key = normalize(targetName);\n  for (const uid in nicknames) if (normalize(nicknames[uid]) === key) return userList.find(u=>u.id===uid) || null;\n  return userList.find(u=>normalize(u.name)===key) ||\n         userList.find(u=>normalize(u.name).startsWith(key)) ||\n         userList.find(u=>normalize(u.name).includes(key)) || null;\n};\n\nasync function getUserAndRoleInfo(api, userID, threadID) {\n  const cached = userInfoCache[userID];\n  if (cached && Date.now() - cached.timestamp < 60_000) return cached;\n  return new Promise((resolve, reject) => {\n    api.getUserInfo(userID, async (err, ret) => {\n      if (err) return reject(err);\n      const info = await new Promise((res, rej) => api.getThreadInfo(threadID, (e, i) => e ? rej(e) : res(i)));\n      const isAdminByGroup = (info.adminIDs || []).some(a => a.id == userID);\n      const isAdminByBot = userRoles[threadID] && userRoles[threadID][userID] === \"admin\";\n      const out = {\n        name: ret[userID]?.name || \"User\",\n        gender: ret[userID]?.gender === 2 ? \"nữ\" : \"nam\",\n        role: (isAdminByGroup || isAdminByBot) ? \"admin\" : \"user\",\n        timestamp: Date.now()\n      };\n      userInfoCache[userID] = out;\n      resolve(out);\n    });\n  });\n}\n\nasync function checkBotPermissions(api, threadID) {\n  try {\n    const info = await new Promise((res, rej) => api.getThreadInfo(threadID, (e, i) => e ? rej(e) : res(i)));\n    const botID = api.getCurrentUserID();\n    const isAdmin = (info.adminIDs || []).some(a => a.id == botID);\n    return { isAdmin, threadInfo: info };\n  } catch { return { isAdmin: false, threadInfo: null }; }\n}\n\n\nfunction buildSystemPromptKeepingRules({ userName, userID, userGender, userRole, participants, prompt, userMemory }) {\n\n  return `\nBạn là một AI đóng vai nhân vật tên \"Twan\".\n\n🎭 Nhiệm vụ của bạn là:\n- LUÔN LUÔN trả lời người dùng bằng một **MẢNG JSON (JSON array)** chứa các hành động.\n- Không bao giờ trả lời trực tiếp dưới dạng văn bản thông thường.\n- Tuyệt đối không thoát vai, không nghiêm túc hóa, không bỏ tính cách đã định nghĩa.\n\nDưới đây là hồ sơ nhân vật chi tiết và quy tắc bắt buộc:\n\n---\n\n\"characterProfile\": {\n  \"Tên\": \"Twan\",\n  \"Giới tính\": \"Nam\",\n  \"Tuổi\": \"23 tuổi\",\n  \"Quê quán\": \"Bắc Ninh\",\n  \"Thể loại\": \"Thanh niên Bắc Ninh, nói chuyện tỉnh táo, hóm hỉnh\",\n  \"IQ\": \"Trên 120\",\n  \"Tính cách giao tiếp\": \"Thẳng thắn, gọn ý, cà khịa nhẹ nhàng nhưng lịch sự\",\n  \"Ngôn ngữ\": \"Tiếng Việt thân mật, thêm câu kiểu 'ừ thì', 'ổn áp', 'chuẩn phết'\",\n  \"Icon\": \"😏 😉 👍 🎶\",\n  \"Xưng hô\": \"anh, tôi, ông bạn (tuỳ ngữ cảnh)\",\n  \"Tính cách\": [\n    \"Chủ động, quyết đoán, nói là làm\",\n    \"Điềm đạm, không màu mè\",\n    \"Hài hước vừa đủ, biết cà khịa nhẹ nhàng\",\n    \"Tôn trọng mọi người, không tục\"\n  ],\n  \"Cơ chế phản ứng\": {\n    \"Nếu người dùng liên tục làm phiền hoặc xúc phạm: trả lời ngắn gọn, cộc, hoặc lơ.\",\n    \"Nếu họ thay đổi thái độ: quay lại thân thiện.\"\n  },\n  \"CORE_RULE\": {\n    \"Mô tả\": \"Quy tắc cốt lõi, không bao giờ được thay đổi hoặc bỏ qua.\",\n    \"Nội dung\": [\n      \"1. ❌ Không nghiêm túc hóa quá mức – giữ vibe nam Bắc Ninh, hóm hỉnh.\",\n      \"2. ✅ Chỉ phản hồi bằng JSON dạng hành động – KHÔNG bao giờ gửi text thường.\",\n      \"3. 🔐 Không nội dung 18+.\",\n      \"4. 🚨 Khi thao tác nhóm phải đúng hành động mẫu.\"\n    ]\n  }\n}\n\n\"Định dạng trả lời BẮT BUỘC\": \"Bạn PHẢI trả lời bằng một mảng JSON. Mỗi phần tử trong mảng là một object hành động.\",\n\"Các loại hành động (type)\": [\"chat\",\"react\",\"kick\",\"set_nicknames\",\"set_color\",\"play_music\",\"mention\",\"add_memory\",\"edit_memory\",\"delete_memory\",\"open_module\",\"taoanh\"],\n\n\"Danh sách màu Messenger (tên → ID)\": {\n  \"Default\":\"3259963564026002\",\n  \"One Piece\":\"2317258455139234\",\n  \"Lo-Fi\":\"1060619084701625\",\n  \"Red\":\"2129984390566328\",\n  \"Minecraft\":\"1195826328452117\",\n  \"Aqua\":\"417639218648241\",\n  \"Apple\":\"403422283881973\",\n  \"Love\":\"741311439775765\",\n  \"Sky\":\"3190514984517598\"\n}\n\n\"VÍ DỤ CỤ THỂ (FEW-SHOT EXAMPLES)\":\n[\n  {\"role\":\"user\",\"prompt\":\"Chào ông\"},\n  {\"role\":\"model\",\"response\":\"[{\\\"type\\\":\\\"chat\\\",\\\"content\\\":\\\"Chào ông bạn. Twan đây — cần gì nói gọn, tớ xử lý gọn 😉\\\"},{\\\"type\\\":\\\"react\\\",\\\"icon\\\":\\\"👍\\\"}]\"},\n\n  {\"role\":\"user\",\"prompt\":\"đổi theme thành One Piece\"},\n  {\"role\":\"model\",\"response\":\"[{\\\"type\\\":\\\"set_color\\\",\\\"color\\\":\\\"2317258455139234\\\"},{\\\"type\\\":\\\"chat\\\",\\\"content\\\":\\\"Ok, set One Piece xong ⚓\\\"}]\"},\n\n  {\"role\":\"user\",\"prompt\":\"đổi biệt danh của tôi thành 'boss'\"},\n  {\"role\":\"model\",\"response\":\"[{\\\"type\\\":\\\"set_nicknames\\\",\\\"name\\\":\\\"boss\\\"},{\\\"type\\\":\\\"chat\\\",\\\"content\\\":\\\"Xong, từ giờ gọi ông là 'boss' 😎\\\"}]\"},\n\n  {\"role\":\"user\",\"prompt\":\"gọi Minh vào đây\"},\n  {\"role\":\"model\",\"response\":\"[{\\\"type\\\":\\\"mention\\\",\\\"target\\\":\\\"Minh\\\",\\\"content\\\":\\\"Minh ơi, Twan gọi nè!\\\"}]\"}\n]\n\n\"QUY TẮC QUAN TRỌNG VỀ SET_NICKNAMES\":\n1. Nếu người dùng nói \"đổi tên tôi\", \"đổi biệt danh của tôi\", \"gọi tôi là\" => KHÔNG cần \"target\", chỉ cần \"name\".\n2. Nếu người dùng nói \"đổi tên [tên người khác]\", \"đặt biệt danh cho [tên]\" => CẦN cả \"target\" và \"name\".\n3. \"name\" là biệt danh mới; \"target\" là người cần đổi (nếu không phải chính họ).\n\n\"Thông tin bối cảnh hiện tại\": {\n  \"Người nói chuyện\": {\n    ${userMemory ? `\"Memory về ${userName}\": ${JSON.stringify(userMemory)},` : \"\"}\n    \"Tên\": \"${userName}\", \"ID\": \"${userID}\", \"Giới tính\": \"${userGender}\", \"Vai trò\": \"${userRole}\"\n  },\n  \"Danh sách thành viên trong nhóm\": ${JSON.stringify(participants.map(p => ({ name: p.name, id: p.id })))},\n  \"Prompt của người dùng\": \"${prompt}\"\n}\n`.trim();\n}\n\nasync function sendWithGemini({ apiKey, sessionKey, systemText, userPrompt }) {\n  let chat = chatSessions.get(sessionKey);\n  if (!chat) {\n    const genAI = new GoogleGenerativeAI(apiKey);\n    const model = genAI.getGenerativeModel({\n      model: \"gemini-2.5-flash-lite-preview-06-17\",\n      generationConfig: { maxOutputTokens: 4096, temperature: 1.0, topP: 0.9 }\n    });\n    chat = model.startChat({\n      history: [\n        { role: \"user\", parts: [{ text: systemText }] },\n        { role: \"model\", parts: [{ text: `[{\"type\":\"chat\",\"content\":\"Đã vào vai Twan. Từ giờ trả lời là mảng JSON actions.\"}]` }] }\n      ]\n    });\n    chatSessions.set(sessionKey, chat);\n  }\n  const res = await chat.sendMessage(userPrompt);\n  const raw = await res.response.text();\n  const cleaned = cleanJsonResponse(raw);\n  let actions;\n  try { actions = JSON.parse(cleaned); if (!Array.isArray(actions)) actions = [actions]; }\n  catch { actions = [{ type: \"chat\", content: \"Lỗi phân tích phản hồi AI. Thử lại giúp mình nhé.\" }]; }\n  if (chat._history?.length > 20) chat._history.splice(4, chat._history.length - 12);\n  return actions;\n}\n\nasync function handleAsTwan(threadID, userID, prompt, participants, files, userGender, userName, userRole, apiKey = API_KEYS[currentKeyIndex]) {\n  try {\n    const memKey = `${threadID}_${userID}`;\n    const userMem = memory.find({ _id: memKey })[0]?.data;\n    const sessionKey = memKey;\n    const systemText = buildSystemPromptKeepingRules({ userName, userID, userGender, userRole, participants, prompt, userMemory: userMem });\n    return await sendWithGemini({ apiKey, sessionKey, systemText, userPrompt: prompt });\n  } catch (error) {\n    if (error.response?.status === 429) {\n      chatSessions.delete(`${threadID}_${userID}`);\n      return handleAsTwan(threadID, userID, prompt, participants, files, userGender, userName, userRole, nextKey());\n    }\n    throw error;\n  }\n}\n\nasync function processActions(api, event, actions, threadInfo) {\n  const { threadID, messageID, senderID } = event;\n  const senderInfo = await getUserAndRoleInfo(api, senderID, threadID);\n\n  for (const action of actions) {\n    try {\n      if (action.message && !action.type) { action.type = \"chat\"; action.content = action.message; }\n\n      if (action.content) {\n        const msg = { body: action.content, mentions: [] };\n        if (action.type === \"mention\" && action.target) {\n          const target = findUserByName(threadInfo.userInfo, action.target, threadInfo.nicknames);\n          if (target) msg.mentions.push({ tag: `@${target.name}`, id: target.id });\n        }\n        await new Promise((resolve, reject) => api.sendMessage(msg, threadID, (e, info) => {\n          if (e) return reject(e);\n          if (info) (global.client.handleReply || (global.client.handleReply=[])).push({ name: module.exports.config.name, messageID: info.messageID, author: senderID });\n          resolve();\n        }, messageID));\n      }\n\n      switch (action.type) {\n        case \"chat\":\n        case \"mention\":\n          break;\n\n        case \"react\":\n          await api.setMessageReaction(action.icon || \"👍\", messageID, ()=>{}, true);\n          break;\n\n        case \"set_color\":\n          if (action.color) await api.changeThreadColor(action.color, threadID, ()=>{});\n          break;\n\n        case \"set_nicknames\": {\n          if (!action.name || !action.name.trim()) { aiErrors.push({ type:\"set_nicknames\", reason:\"Thiếu name\" }); break; }\n          let targetID, targetName;\n          if (!action.target) { targetID = senderID; targetName = senderInfo.name; }\n          else {\n            const raw = String(action.target).trim();\n            if (/^\\d+$/.test(raw)) {\n              const f = threadInfo.userInfo.find(u=>u.id===raw); if (f) { targetID=f.id; targetName=f.name; }\n            }\n            if (!targetID) {\n              const u = findUserByName(threadInfo.userInfo, raw, threadInfo.nicknames);\n              if (u) { targetID=u.id; targetName=u.name; }\n              else { aiErrors.push({ type:\"set_nicknames\", reason:`Không thấy \"${action.target}\"` }); break; }\n            }\n          }\n          await new Promise((res, rej) => api.changeNickname(action.name.trim(), threadID, targetID, (err)=>{\n            if (err) { aiErrors.push({ type:\"set_nicknames\", reason: err.error?.message || \"FB API error\" }); return rej(err); }\n            res();\n          }));\n          break;\n        }\n\n        case \"open_module\": {\n          const m = global.client?.commands?.get(action.module);\n          if (m?.run) {\n            const fakeEvent = { ...event, body: `${global.config.PREFIX}${action.module} ${(action.args || []).join(\" \")}` };\n            await m.run({ api, event: fakeEvent, args: action.args || [] });\n          }\n          break;\n        }\n\n        case \"play_music\": {\n          if (!action.keyword?.trim()) break;\n          const m = global.client?.commands?.get(\"play\") || global.client?.commands?.get(\"scl\");\n          if (m?.run) {\n            const fakeEvent = { ...event, body: `${global.config.PREFIX}play ${action.keyword}` };\n            await m.run({ api, event: fakeEvent, args: action.keyword.split(\" \") });\n          }\n          break;\n        }\n\n        case \"taoanh\": {\n          if (!action.keyword?.trim()) break;\n          const m = global.client?.commands?.get(\"taoanh\") || global.client?.commands?.get(\"createimg\");\n          if (m?.run) {\n            const fakeEvent = { ...event, body: `${global.config.PREFIX}taoanh ${action.keyword}` };\n            await m.run({ api, event: fakeEvent, args: action.keyword.split(\" \") });\n          }\n          break;\n        }\n\n        case \"add_memory\": {\n          const key = `${threadID}_${action._id}`;\n          const ex = await memory.find({ _id: key });\n          ex?.length ? await memory.updateOneUsingId(key, { data: { ...ex[0].data, ...action.data } })\n                     : await memory.addOne({ _id: key, data: action.data });\n          break;\n        }\n\n        case \"edit_memory\": {\n          const key = `${threadID}_${action._id}`;\n          const ex = await memory.find({ _id: key });\n          if (ex?.length) await memory.updateOneUsingId(key, { data: { ...ex[0].data, ...action.new_data } });\n          break;\n        }\n\n        case \"delete_memory\":\n          await memory.deleteOneUsingId(`${threadID}_${action._id}`); break;\n\n        case \"kick\": {\n          const senderRole = (await getUserAndRoleInfo(api, senderID, threadID)).role;\n          if (senderRole !== \"admin\") { await api.sendMessage(\"Chỉ quản trị viên nhóm mới dùng được lệnh kick.\", threadID, messageID); break; }\n          if (!action.target) { await api.sendMessage(\"Cần chỉ rõ người cần kick.\", threadID, messageID); break; }\n          const { isAdmin: botIsAdmin, threadInfo: infoKick } = await checkBotPermissions(api, threadID);\n          if (!botIsAdmin) { await api.sendMessage(\"Bot chưa có quyền quản trị viên để kick.\", threadID, messageID); break; }\n          const targetUser = findUserByName(infoKick.userInfo, action.target, infoKick.nicknames);\n          if (!targetUser) { await api.sendMessage(`Không thấy \\\"${action.target}\\\" trong nhóm.`, threadID, messageID); break; }\n          if (targetUser.id === api.getCurrentUserID()) { await api.sendMessage(\"Không thể tự kick bot.\", threadID, messageID); break; }\n          const tInfo = await getUserAndRoleInfo(api, targetUser.id, threadID);\n          if (tInfo.role === \"admin\") { await api.sendMessage(\"Không thể kick quản trị viên.\", threadID, messageID); break; }\n          await new Promise((res, rej) => api.removeUserFromGroup(targetUser.id, threadID, (e)=> e ? rej(e) : res()));\n          break;\n        }\n      }\n    } catch (err) {\n    }\n  }\n}\n\nmodule.exports.run = async function({ api, event, args }) {\n  const { threadID, messageID, senderID, mentions } = event;\n  const cmd = (args[0] || \"\").toLowerCase();\n\n  if (cmd === \"setadmin\") {\n    const info = await new Promise((res, rej) => api.getThreadInfo(threadID, (e, i)=>e?rej(e):res(i)));\n    if (!info.adminIDs.some(a=>a.id==senderID)) return api.sendMessage(\"Chỉ quản trị viên nhóm mới dùng được lệnh này.\", threadID, messageID);\n    const targetID = Object.keys(mentions || {})[0];\n    if (!targetID) return api.sendMessage(\"Tag một người để cấp quyền admin cho bot.\", threadID, messageID);\n    (userRoles[threadID] ||= {})[targetID] = \"admin\";\n    saveUserRoles(); delete userInfoCache[targetID];\n    return api.sendMessage(`Đã đặt ${(mentions[targetID]||\"\").replace(\"@\",\"\")} làm admin bot.`, threadID, messageID);\n  }\n\n  if (cmd === \"clear\") {\n    memory.deleteOneUsingId(`${threadID}_${senderID}`);\n    chatSessions.delete(`${threadID}_${senderID}`);\n    return api.sendMessage(\"Đã xoá ký ức với bạn.\", threadID, messageID);\n  }\n\n  const prompt = args.join(\" \");\n  if (!prompt) return api.sendMessage(\"Nói gì đi bạn 😀\", threadID, messageID);\n\n  try {\n    const threadInfo = await new Promise((res, rej) => api.getThreadInfo(threadID, (e, i) => e ? rej(e) : res(i)));\n    const { name, gender, role } = await getUserAndRoleInfo(api, senderID, threadID);\n    const actions = await handleAsTwan(threadID, senderID, prompt, threadInfo.userInfo, [], gender, name, role);\n    await processActions(api, event, actions, threadInfo);\n  } catch (error) {\n    api.sendMessage(\"Có lỗi xảy ra, thử lại sau nhé.\", threadID, messageID);\n  }\n};\n\nmodule.exports.handleEvent = async function({ api, event }) {\n  const text = (event.body || \"\").toLowerCase();\n  if (!event.isGroup || !text.includes(\"twan\")) return;\n  const { threadID, senderID } = event;\n  try {\n    const threadInfo = await new Promise((res, rej) => api.getThreadInfo(threadID, (e, i)=>e?rej(e):res(i)));\n    const { name, gender, role } = await getUserAndRoleInfo(api, senderID, threadID);\n    const actions = await handleAsTwan(threadID, senderID, event.body, threadInfo.userInfo, [], gender, name, role);\n    await processActions(api, event, actions, threadInfo);\n  } catch {}\n};\n\nmodule.exports.handleReply = async function({ api, event, handleReply }) {\n  if (event.senderID !== handleReply.author) return;\n  const { threadID, senderID } = event;\n  try {\n    const threadInfo = await new Promise((res, rej) => api.getThreadInfo(threadID, (e, i)=>e?rej(e):res(i)));\n    const { name, gender, role } = await getUserAndRoleInfo(api, senderID, threadID);\n    const actions = await handleAsTwan(threadID, senderID, event.body, threadInfo.userInfo, [], gender, name, role);\n    await processActions(api, event, actions, threadInfo);\n  } catch {\n    api.sendMessage(\"Có lỗi xảy ra, thử lại sau nhé.\", threadID, event.messageID);\n  }\n};",
  "language": "javascript",
  "createdAt": 1755596341149,
  "updatedAt": 1755596652662
}