File size: 20,311 Bytes
dc69b75
 
 
 
 
 
7ea3e88
dc69b75
1
2
3
4
5
6
7
8
{
  "id": "71b63f50-0997-44f1-8f25-487f187bd6f7",
  "title": "count.js",
  "content": "const axios = require('axios');\nconst fs = require('fs');\nconst path = __dirname + '/count-by-threadd-2/';\nconst timeJoinGroupPath = __dirname + '/cache/timeJoinGroup.json';\nconst moment = require('moment-timezone');\n\nmodule.exports.Seikoconfig = {\n    name: \"count\",\n    aliases: [\"check\"],\n    version: \"1.0.1\",\n    role: 0,\n    author: \"DungUwU && Nghĩa\",\n    info: \"Check tương tác ngày/tuần/toàn bộ\",\n    Category: \"Box chat\",\n    cd: 5,\n    dependencies: {\n        \"fs\": \" \",\n        \"moment-timezone\": \" \"\n    }\n};\n\n// Bản đồ ánh xạ ngày trong tuần từ tiếng Anh sang tiếng Việt\nconst dayMap = {\n    'Monday': 'Thứ 2',\n    'Tuesday': 'Thứ 3',\n    'Wednesday': 'Thứ 4',\n    'Thursday': 'Thứ 5',\n    'Friday': 'Thứ 6',\n    'Saturday': 'Thứ 7',\n    'Sunday': 'Chủ nhật'\n};\n\nmodule.exports.onLoad = () => {\n  const fs = require('fs');\n  if (!fs.existsSync(path) || !fs.statSync(path).isDirectory()) {\n    fs.mkdirSync(path, { recursive: true });\n  }\n  if (!fs.existsSync(timeJoinGroupPath)) {\n    fs.writeFileSync(timeJoinGroupPath, JSON.stringify({}));\n  }\n  setInterval(() => {\n    const today = moment.tz(\"Asia/Ho_Chi_Minh\").day();\n    const checkttData = fs.readdirSync(path);\n    checkttData.forEach(file => {\n      try { var fileData = JSON.parse(fs.readFileSync(path + file)) } catch { return fs.unlinkSync(path+file) };\n      if (fileData.time != today) {\n        setTimeout(() => {\n          fileData = JSON.parse(fs.readFileSync(path + file));\n          if (fileData.time != today) {\n            fileData.time = today;\n            fs.writeFileSync(path + file, JSON.stringify(fileData, null, 4));\n          }\n        }, 60 * 1000);\n      }\n    })\n  }, 60 * 1000);\n}\n\nmodule.exports.onEvent = async function({ api, event, Threads }) {\n  try{\n  if (!event.isGroup) return;\n  if (global.Seiko.sending_top == true) return;\n  const fs = require('fs');\n  const { threadID, senderID } = event;\n  const today = moment.tz(\"Asia/Ho_Chi_Minh\").day();\n\n  if (!fs.existsSync(path + threadID + '.json')) {\n    var newObj = {\n      total: [],\n      week: [],\n      day: [],\n      time: today,\n      last: {\n        time: today,\n        day: [],\n        week: [],\n      },\n    };\n    fs.writeFileSync(path + threadID + '.json', JSON.stringify(newObj, null, 4));} else {\n      var newObj = JSON.parse(fs.readFileSync(path + threadID + '.json'));\n    }\n    //const threadInfo = await Threads.getInfo(threadID) || {};\n    const UserIDs = event.participantIDs || [];\n    if (true/*threadInfo.hasOwnProperty('isGroup') && threadInfo.isGtrue*/) {\n      //const UserIDs = event.participantIDs || [];\n      if (UserIDs.length!=0)for (let user of UserIDs) {\n        if (!newObj.last)newObj.last = {\n          time: today,\n          day: [],\n          week: [],\n        };\n        if (!newObj.last.week.find(item => item.id == user)) {\n          newObj.last.week.push({\n            id: user,\n            count: 0\n          });\n        }\n        if (!newObj.last.day.find(item => item.id == user)) {\n          newObj.last.day.push({\n            id: user,\n            count: 0\n          });\n        }\n        if (!newObj.total.find(item => item.id == user)) {\n          newObj.total.push({\n            id: user,\n            count: 0\n          });\n        }\n        if (!newObj.week.find(item => item.id == user)) {\n          newObj.week.push({\n            id: user,\n            count: 0\n          });\n        }\n        if (!newObj.day.find(item => item.id == user)) {\n          newObj.day.push({\n            id: user,\n            count: 0\n          });\n        }\n      }\n    };\n    fs.writeFileSync(path + threadID + '.json', JSON.stringify(newObj, null, 4));\n  \n  const threadData = JSON.parse(fs.readFileSync(path + threadID + '.json'));\n  if (threadData.time != today) {\n    global.Seiko.sending_top = true;\n    setTimeout(() => global.Seiko.sending_top = false, 5 * 60 * 1000);\n  }\n  const userData_week_index = threadData.week.findIndex(e => e.id == senderID);\n  const userData_day_index = threadData.day.findIndex(e => e.id == senderID);\n  const userData_total_index = threadData.total.findIndex(e => e.id == senderID);\n  if (userData_total_index == -1) {\n    threadData.total.push({\n      id: senderID,\n      count: 1,\n    });\n  } else threadData.total[userData_total_index].count++;\n  if (userData_week_index == -1) {\n    threadData.week.push({\n      id: senderID,\n      count: 1\n    });\n  } else threadData.week[userData_week_index].count++;\n  if (userData_day_index == -1) {\n    threadData.day.push({\n      id: senderID,\n      count: 1\n    });\n  } else threadData.day[userData_day_index].count++;\n  let p = event.participantIDs;\n    if (!!p && p.length > 0) {\n      p = p.map($=>$+'');\n      ['day','week','total'].forEach(t=>threadData[t] = threadData[t].filter($=>p.includes($.id+'')));\n    };\n  fs.writeFileSync(path + threadID + '.json', JSON.stringify(threadData, null, 4));\n\n  // Update user join dates\n//   let timeJoinGroup = JSON.parse(fs.readFileSync(timeJoinGroupPath));\n//   UserIDs.forEach(user => {\n//       if (!timeJoinGroup[threadID]) {\n//           timeJoinGroup[threadID] = {};\n//       }\n//       if (!timeJoinGroup[threadID][user]) {\n//           timeJoinGroup[threadID][user] = moment.tz(\"Asia/Ho_Chi_Minh\").format();\n//       }\n//   });\n//   fs.writeFileSync(timeJoinGroupPath, JSON.stringify(timeJoinGroup, null, 4));\n    // Cập nhật thông tin tham gia nhóm\n    let timeJoinGroup = JSON.parse(fs.readFileSync(timeJoinGroupPath));\n    if (!timeJoinGroup[threadID]) {\n        timeJoinGroup[threadID] = {};\n    }\n\n    // Thêm thời gian tham gia nhóm cho người dùng mới\n    UserIDs.forEach(user => {\n        if (!timeJoinGroup[threadID][user]) {\n            timeJoinGroup[threadID][user] = moment.tz(\"Asia/Ho_Chi_Minh\").format();\n        }\n    });\n\n    // Xóa thông tin thời gian tham gia nhóm của người dùng không còn trong danh sách\n    Object.keys(timeJoinGroup[threadID] || {}).forEach(user => {\n        if (!UserIDs.includes(user)) {\n            delete timeJoinGroup[threadID][user];\n        }\n    });\n\n    fs.writeFileSync(timeJoinGroupPath, JSON.stringify(timeJoinGroup, null, 4));\n  } catch(e){\n    console.error(e);\n  };\n}\n\nmodule.exports.onRun = async function({ api, event, args, Users, Threads }) {\n  await new Promise(resolve => setTimeout(resolve, 500));\n  const fs = require('fs');\n  const { threadID, messageID, senderID, mentions } = event;\n  let path_data = path + threadID + '.json';\n  if (!fs.existsSync(path_data)) {\n    return api.sendMessage(\"Chưa có dữ liệu\", threadID);\n  }\n  const threadData = JSON.parse(fs.readFileSync(path_data));\n  const query = args[0] ? args[0].toLowerCase() : '';\n\n  if (query == 'box') {\n  \ttry{\n\t    let body_ = event.args[0].replace(module.exports.config.name, '')+'box info';\n\t    let args_ = body_.split(' ');\n\t    \n\t    arguments[0].args = args_.slice(1);\n\t    arguments[0].event.args = args_;\n\t    arguments[0].event.body = body_;\n\t    \n\t    return require('./box.js').onRun(...Object.values(arguments));\n\t} catch(e)\n\t{ console.log(e); }\n  } else if (query == 'reset') {\n     let dataThread = (await Threads.getData(threadID)).threadInfo;\n    if (!dataThread.adminIDs.some(item => item.id == senderID)) return api.sendMessage('Bạn không đủ quyền hạn để sử dụng!', event.threadID, event.messageID);\n     fs.unlinkSync(path_data);\n     return api.sendMessage(`Đã xóa toàn bộ dữ liệu đếm tương tác của nhóm, hãy nhắn vài câu để tạo lại dữ liệu`, event.threadID);\n     } else if(query == 'locmen') {\n        let threadInfo = await api.getThreadInfo(threadID);\n        if(!threadInfo.adminIDs.some(e => e.id == senderID)) return api.sendMessage(\"Bạn không có quyền sử dụng lệnh này\", threadID);\n        if(!threadInfo.isGroup) return api.sendMessage(\"Chỉ có thể sử dụng trong nhóm\", threadID);\n        if(!threadInfo.adminIDs.some(e => e.id == api.getCurrentUserID())) return api.sendMessage(\"Bot cần qtv để thực hiện lệnh\", threadID);\n        if(!args[1] || isNaN(args[1])) return api.sendMessage(\"Error\", threadID);\n        let minCount = +args[1],\n            allUser = event.participantIDs;let id_rm = [];\n        for(let user of allUser) {\n            if(user == api.getCurrentUserID()) continue;\n            if(!threadData.total.some(e => e.id == user) || threadData.total.find(e => e.id == user).count <= minCount) {\n                await new Promise(resolve=>setTimeout(async () => {\n                    await api.removeUserFromGroup(user, threadID);\n                    id_rm.push(user);\n                    resolve(true);\n                }, 1000));\n            }\n        }\n        return api.sendMessage(`Đã xóa ${id_rm.length} thành viên ${minCount} tin nhắn\\n\\n${id_rm.map(($,i)=>`${i+1}. ${global.data.userName.get($)}`)}`, threadID);\n}\n////////////////////////////////\n  var x = threadData.total.sort((a, b) => b.count - a.count);\n  var o = [];\n  for (i = 0; i < x.length; i++) {\n    o.push({\n      rank: i + 1,\n      id: x[i].id,\n      count: x[i].count\n    })\n  }\n  /////////////////////////////////////////////////////////////\n  var header = '',\n    body = '',\n    footer = '',\n    msg = '',\n    count = 1,\n    storage = [],\n    data = 0;\n  if (query == 'all' || query == '-a') {\n    header = '[ Kiểm Tra Tất Cả Tin nhắn ]\\n─────────────────';\n    data = threadData.total;\n\n  } else if (query == 'week' || query == '-w') {\n    header = '==== 𝗖𝗛𝗘𝗖𝗞_𝗪𝗘𝗘𝗞 ====';\n    data = threadData.week;\n  } else if (query == 'day' || query == '-d') {\n    header = '==== 𝗖𝗛𝗘𝗖𝗞_𝗗𝗔𝗬 ====';\n    data = threadData.day;\n  } else {\n    data = threadData.total;\n  }\n  for (const item of data) {\n    const userName = await Users.getNameUser(item.id) || 'Facebook User';\n    const itemToPush = item;\n    itemToPush.name = userName;\n    storage.push(itemToPush);\n  };\n  let check = ['all', '-a', 'week', '-w', 'day', '-d'].some(e => e == query);\n  if (!check && Object.keys(mentions).length > 0) {\n    //storage = storage.filter(e => mentions.hasOwnProperty(e.id));\n  }\n  //sort by count from high to low if equal sort by name\n  storage.sort((a, b) => {\n    if (a.count > b.count) {\n      return -1;\n    }\n    else if (a.count < b.count) {\n      return 1;\n    } else {\n      return a.name.localeCompare(b.name);\n    }\n  });\n\n// Đọc dữ liệu thời gian tham gia nhóm\nlet timeJoinGroup = JSON.parse(fs.readFileSync(timeJoinGroupPath));\nif ((!check && Object.keys(mentions).length == 0) || (!check && Object.keys(mentions).length == 1) || (!check && event.type == 'message_reply')) {\n        const UID = event.messageReply ? event.messageReply.senderID : Object.keys(mentions)[0] ? Object.keys(mentions)[0] : senderID;\n      const uid = event.type == 'message_reply' ? event.messageReply.senderID: !!Object.keys(event.mentions)[0] ? Object.keys(event.mentions)[0]: !!args[0] ? args[0]: event.senderID;\n    const userRank = storage.findIndex(e => e.id == UID);\n    const userTotal = threadData.total.find(e => e.id == UID) ? threadData.total.find(e => e.id == UID).count : 0;\n    const userTotalWeek = threadData.week.find(e => e.id == UID) ? threadData.week.find(e => e.id == UID).count : 0;\n    const userRankWeek = threadData.week.sort((a, b) => b.count - a.count).findIndex(e => e.id == UID);\n    const userTotalDay = threadData.day.find(e => e.id == UID) ? threadData.day.find(e => e.id == UID).count : 0;\n    const userRankDay = threadData.day.sort((a, b) => b.count - a.count).findIndex(e => e.id == UID);\n    let count_day_last = threadData.last?.day?.find($=>$.id==UID)?.count||0;\n    let count_week_last = threadData.last?.week?.find($=>$.id==UID)?.count||0;\n    let interaction_rate_day = (userTotalDay/count_day_last)*100;\n    let interaction_rate_week = (userTotalWeek/count_week_last)*100;\n    const nameUID = storage[userRank].name || 'Facebook User';\n    let threadInfo = await api.getThreadInfo(event.threadID);\n    nameThread = threadInfo.threadName;\n\n    // Xác định thời gian tham gia nhóm\n    let joinDate = timeJoinGroup[threadID] && timeJoinGroup[threadID][UID];\n    let joinMoment = joinDate ? moment(joinDate) : moment();\n    let currentMoment = moment();\n    let daysJoined = joinDate ? currentMoment.diff(joinMoment, 'days') : 'N/A';\n    //let formattedJoinDate = joinDate ? joinMoment.format('HH:mm:ss - DD/MM/YYYY (dddd)') : 'N/A';\n    // Hàm để định dạng ngày tháng năm và thay đổi tên ngày\n    function formatJoinDate(joinDate) {\n        if (!joinDate) {\n            return 'N/A';\n        }\n\n        // Tạo đối tượng moment từ joinDate\n        const joinMoment = moment.parseZone(joinDate);\n\n        // Định dạng ngày tháng năm\n        let formattedDate = joinMoment.format('HH:mm:ss - DD/MM/YYYY (dddd)');\n\n        // Thay thế tên ngày trong kết quả định dạng\n        Object.keys(dayMap).forEach(day => {\n            if (formattedDate.includes(day)) {\n                formattedDate = formattedDate.replace(day, dayMap[day]);\n            }\n        });\n\n        return formattedDate;\n    }\n\n    var permission;\n    if (global.config.ADMINBOT.includes(UID)) permission = `Admin Bot`;\n    else if\n      (global.config.NDH.includes(UID))\n      permission = `Nguời Thuê Bot`; else if (threadInfo.adminIDs.some(i => i.id == UID)) permission = `Quản Trị Viên`; else permission = `Thành Viên`;\n    const target = UID == senderID ? 'Bạn' : nameUID;\n    if (userRank == -1) {\n      return api.sendMessage(`${target} chưa có dữ liệu`, threadID);\n    }\n  body += `\n✨  Tương tác của: ${nameUID}\n🪪   Chức Vụ: ${permission}\n📆  Tin Nhắn Trong Ngày: ${userTotalDay}\n📅  Tin Nhắn Trong Tuần: ${userTotalWeek}\n💬  Tổng Tin Nhắn: ${userTotal}\n🏆  Xếp Hạng: ${userRank + 1}/${storage.length}\n⏰  Thời gian tham gia nhóm: ${formatJoinDate(joinDate)}\n🕐  Đã tham gia được ${daysJoined} ngày\n👉  Lần cuối nhắn tin: ${moment().tz('Asia/Ho_Chi_Minh').format('HH:mm:ss')}\n\n📌 Thả cảm xúc \"❤️\" tin nhắn này để xem tổng tin nhắn nhóm.\n        `.replace(/^ +/gm, '');\n    console.log(storage.reduce((a, b) => a + b.count, 0))\n  } else {\n    console.log((storage.filter($ => $.id == senderID))[0].count)\n    body = storage.map(item => {\n      let count_day_last = threadData.last?.day?.find($=>$.id=item.id)?.count||0;\n    let count_week_last = threadData.last?.week?.find($=>$.id==item.id)?.count||0;\n    let interaction_rate_day = (item.count/count_day_last)*100;\n    let interaction_rate_week = (item.count/count_week_last)*100;\n    let rate = /^day|-d$/.test(query)?interaction_rate_day:/^week|-w$/.test(query)?interaction_rate_week:false;\n      return `${count++}. ${item.name} với ${item.count} tin nhắn`;\n    }).join('\\n');\n    const userTotalWeek = threadData.week.find(e => e.id == senderID) ? threadData.week.find(e => e.id == senderID).count : 0;\n    const userTotalDay = threadData.day.find(e => e.id == senderID) ? threadData.day.find(e => e.id == senderID).count : 0;\n    const tlttd = (userTotalDay / (storage.reduce((a, b) => a + b.count, 0))) * 100;\n    const tlttt = (userTotalWeek / (storage.reduce((a, b) => a + b.count, 0))) * 100\n    const tltt = (((storage.filter($ => $.id == senderID))[0].count) / (storage.reduce((a, b) => a + b.count, 0))) * 100\n    footer = `\\n💬 Tổng Tin Nhắn: ${storage.reduce((a, b) => a + b.count, 0)}`;\n  }\n\n  msg = `${header}\\n${body}\\n${footer}`;\n  return api.sendMessage(msg + '\\n' /*+ `→ Bạn hiện đang đứng ở hạng: ${(o.filter(id => id.id == senderID))[0]['rank']}` */ + `${query == 'all' || query == '-a' ? `🏆 Bạn hiện đang đứng ở hạng: ${(o.filter(id => id.id == senderID))[0]['rank']}\\n─────────────────\\n📌 Hướng dẫn lọc thành viên:\\n🍓 Reply (phản hồi) tin nhắn này theo số thứ tự để xóa thành viên ra khỏi nhóm.\\n🍓 ${global.config.PREFIX}${this.config.name} locmen + số tin nhắn để xóa thành viên ra khỏi nhóm.\\n🍓 ${global.config.PREFIX}${this.config.name} reset -> reset lại toàn bộ dữ liệu tin nhắn.\\n→ ${global.config.PREFIX}${this.config.name} box -> xem thông tin nhóm.` : \"\"}`, threadID, (error, info) => {\n\n    if (error) return console.log(error)\n    if (query == 'all' || query == '-a') {\n      global.Seiko.onReply.push({\n        name: this.config.name,\n        messageID: info.messageID,\n        tag: 'locmen',\n        thread: threadID,\n        author: senderID, storage,\n      })\n    }\n    global.Seiko.onReaction.push({\n      name: this.config.name,\n      messageID: info.messageID,\n      sid: senderID,\n    })\n  });\n  threadData = storage = null;\n}\nmodule.exports.onReply = async function({\n  api\n  , event\n  , args\n  , onReply\n  , client\n  , __GLOBAL\n  , permssion\n  , Threads\n  , Users\n  , Currencies\n}) {\n  try {\n    const { senderID } = event\n    let dataThread = (await Threads.getData(event.threadID)).threadInfo;\n    if (!dataThread.adminIDs.some(item => item.id == api.getCurrentUserID())) return api.sendMessage('Bot cần quyền quản trị viên!', event.threadID, event.messageID);\n    if (!dataThread.adminIDs.some(item => item.id == senderID)) return api.sendMessage('Bạn không đủ quyền hạn để lọc thành viên!', event.threadID, event.messageID);\n    const fs = require('fs')\n    \n    let split = event.body.split(\" \")\n\n    if (isNaN(split.join(''))) return api.sendMessage(`dữ liệu không hợp lệ!`, event.threadID);\n\n    let msg = [], count_err_rm = 0;\n    for (let $ of split) {\n      let id = onReply?.storage[$ - 1]?.id;\n\n      if (!!id)try {\n        await api.removeUserFromGroup(id, event.threadID);\n        msg.push(`${$}. ${global.data.userName.get(id)}`)\n      } catch (e) {++count_err_rm;continue};\n    };\n\n    api.sendMessage(`Đã xóa ${split.length-count_err_rm} người dùng thành công, thất bại ${count_err_rm}\\n\\n${msg.join('\\n')}`, onReply.thread)\n\n  } catch (e) {\n    console.log(e)\n  }\n}\nmodule.exports.onReaction = function({ event, Users, Threads, api, onReaction: _, Currencies }) {\n  const fs = require('fs')\n  if (event.userID != _.sid) return;\n  if (event.reaction != \"❤\") return; \n  api.unsendMessage(_.messageID)\n  let data = JSON.parse(fs.readFileSync(`${path}${event.threadID}.json`));\n  let sort = data.total.sort((a, b) => a.count < b.count ? 0 : -1);\n  api.sendMessage(`[ Kiểm Tra Tất Cả Tin nhắn ]\\n─────────────────\\n${sort.map(($, i) => `${i + 1}. ${global.data.userName.get($.id)} - ${$.count} tin.`).join('\\n')}\\n\\n💬Tổng tin nhắn: ${data.total.reduce((s, $) => s + $.count, 0)}\\n🏆 Bạn hiện đang đứng ở hạng: ${sort.findIndex($ => $.id == event.userID) + 1}\\n─────────────────\\n📌 Hướng dẫn lọc thành viên:\\n🍓 Reply (phản hồi) tin nhắn này theo số thứ tự để xóa thành viên ra khỏi nhóm.\\n🍓 ${global.config.PREFIX}count locmen + số tin nhắn để xóa thành viên ra khỏi nhóm.\\n🍓 ${global.config.PREFIX}count reset -> reset lại toàn bộ dữ liệu tin nhắn.\\n→ ${global.config.PREFIX}count box -> xem thông tin nhóm.`, event.threadID, (err, info) => global.Seiko.onReply.push({\n    name: this.config.name,\n    messageID: info.messageID,\n    tag: 'locmen',\n    thread: event.threadID,\n    author: event.senderID,\n    storage: sort,\n  })\n  );\n}",
  "language": "javascript",
  "createdAt": 1756699824223,
  "updatedAt": 1756699890994
}