UNPKG

koishi-plugin-yutang-ohayo

Version:

抄袭的早安插件,数据存储到数据库的早安

390 lines (364 loc) 15.3 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name2 in all) __defProp(target, name2, { get: all[name2], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { Config: () => Config, DailyTask: () => DailyTask, Tools: () => Tools, apply: () => apply, inject: () => inject, logger: () => logger, name: () => name, usage: () => usage }); module.exports = __toCommonJS(src_exports); var import_koishi = require("koishi"); var inject = { require: ["database"] }; var name = "yutang-ohayo"; var logger = new import_koishi.Logger("yutang-ohayo"); var Config = import_koishi.Schema.object({ enableOhayoImage: import_koishi.Schema.boolean().default(true).description("是否在早安时发送图片"), enableOyasumiImage: import_koishi.Schema.boolean().default(true).description("是否在晚安时发送图片"), ohayoImageHours: import_koishi.Schema.tuple([import_koishi.Schema.number(), import_koishi.Schema.number()]).default([6, 12]).description("早安发送图片的时间范围(小时,6 - 12,其余时间均为晚安)"), oyasumiImageHours: import_koishi.Schema.tuple([import_koishi.Schema.number(), import_koishi.Schema.number()]).default([18, 6]).description("晚安发送图片的时间范围(小时)") }); var usage = `# 💐⭐️早上好!!!⭐️💐 ## 早安问候插件 ## 自定义是否返回图片,避免刷屏`; var oyasumiMessages = ["oyasumi", "哦呀斯密", "晚安", "晚安啦", "好梦", "睡个好觉", "晚安,做个好梦"]; var aisatsuURL = "https://api.lolimi.cn/API/image-zw/api.php"; var ohayoMemo = {}; var Tools = class { static { __name(this, "Tools"); } // 获取随机整数 static getRandomInt(min, max) { if (min > max) [min, max] = [max, min]; return Math.floor(Math.random() * (max - min + 1) + min); } // 随机选择元素 static roll(args) { return args[this.getRandomInt(0, args.length - 1)]; } // 删除自身@标签 static deleteSelfAdd(content, id) { const start = content.indexOf("<at"), end = content.indexOf("/>"); if (start !== -1 && end !== -1) { const sId = content.indexOf('id="'), eId = content.indexOf('" ') === -1 ? content.indexOf('"/') : content.indexOf('" '); if (sId !== -1 && eId !== -1 && content.slice(sId + 4, eId) === id) { content = content.slice(end + 3); } } return content; } }; var DailyTask = class { static { __name(this, "DailyTask"); } static clearIntervalId = null; // 初始化每日任务(凌晨自动清空记录) static init() { const now = /* @__PURE__ */ new Date(), midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0); const delay = midnight.getTime() - now.getTime(); setTimeout(() => { ohayoMemo = {}; this.clearIntervalId = setInterval(() => ohayoMemo = {}, 864e5); }, delay); } // 停止任务 static stop() { this.clearIntervalId && clearInterval(this.clearIntervalId); } }; function isOhayo(message) { const keywords = ["早", "早上好", "ohayo", "哦哈哟", "zao", "起床", "起了", "醒了", "早安", "早尚郝", "枣尚郝", "枣"]; const regex = new RegExp(keywords.join("|"), "i"); return regex.test(message); } __name(isOhayo, "isOhayo"); function isOyasumi(message) { const keywords = ["晚", "wan", "oyasumi", "哦呀斯密", "睡觉", "睡了", "眠了", "晚安", "好梦", "睡个好觉", "晚安", "晚安"]; const regex = new RegExp(keywords.join("|"), "i"); return regex.test(message); } __name(isOyasumi, "isOyasumi"); // 定义早安消息数组 const ohayoMessages = ["早上好", "早安", "ohayo", "哦哈哟"]; function apply(ctx, config) { ctx.model.extend( "morning_night_record", { id: "unsigned", userId: "string", username: "string", groupId: "string", messageType: "string", timestamp: "timestamp", count: "integer" }, { primary: "id", autoInc: true } ); const processedMessages = /* @__PURE__ */ new Set(); // 记录每个 Bot 处理过的消息 ID const botMessageCache = new Map(); ctx.on("message", async (session) => { // 获取当前 Bot 的 ID const botId = session.bot?.id; if (!botId) return; // 检查当前 Bot 是否已经处理过该消息 if (!botMessageCache.has(botId)) { botMessageCache.set(botId, new Set()); } const botProcessedMessages = botMessageCache.get(botId); if (session.userId !== session.selfId && !botProcessedMessages.has(session.messageId)) { if (isOhayo(session.content)) { botProcessedMessages.add(session.messageId); // 传递群 ID 到早安命令 const result = await session.execute("早安", { groupId: session.guildId }); if (result) await session.send(result); } if (isOyasumi(session.content)) { botProcessedMessages.add(session.messageId); // 传递群 ID 到晚安命令 const result = await session.execute("晚安", { groupId: session.guildId }); if (result) await session.send(result); } } }); // 补充早安命令 ctx.command("早安", "发送早安问候并记录起床时间").action(async ({ session, options }) => { try { const now = /* @__PURE__ */ new Date(); const hour = now.getHours(); const minute = now.getMinutes(); const userState = ohayoMemo[session.userId] || { hasOhayo: false, hasOyasumi: false }; const groupId = options?.groupId || session.guildId || ""; if (userState.hasOhayo) { const reply = "今天已经道过早安啦~"; await session.send(reply); return reply; } userState.hasOhayo = true; userState.ohayoTime = now; ohayoMemo[session.userId] = userState; let reply = `${Tools.roll(ohayoMessages)},现在是 ${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")},你是今天第${Object.keys(ohayoMemo).length}个起床的哦~`; if (groupId === "633373584") { reply = getSpecialOhayoReply(hour, reply); } else if (groupId === "738988912") { reply = "你好!测试群专用早安~"; } else { reply += getTimeSegmentReply(hour); } await session.send(reply); const [startHour, endHour] = config.ohayoImageHours; const isInRange = endHour > startHour ? hour >= startHour && hour < endHour : hour >= startHour || hour < endHour; if (config.enableOhayoImage && isInRange) { await session.send((0, import_koishi.h)("image", { src: aisatsuURL })); } const [existingRecord] = await ctx.database.get("morning_night_record", { userId: session.userId, groupId: session.guildId || "", messageType: "ohayo" }); if (existingRecord) { await ctx.database.set("morning_night_record", { id: existingRecord.id }, { count: existingRecord.count + 1, timestamp: now }); } else { await ctx.database.create("morning_night_record", { userId: session.userId, username: session.username, groupId: session.guildId || "", messageType: "ohayo", timestamp: now, count: 1 }); } return reply; } catch (error) { logger.error("早安命令执行出错:", error); const errorReply = "执行早安命令时出现错误,请稍后再试。"; await session.send(errorReply); return errorReply; } }); ctx.command("晚安", "发送晚安问候并记录睡眠时间").action(async ({ session, options }) => { try { const now = /* @__PURE__ */ new Date(); const hour = now.getHours(); const minute = now.getMinutes(); const userState = ohayoMemo[session.userId]; const groupId = options?.groupId || session.guildId || ""; if (userState && userState.hasOyasumi) { const reply = "今天已经道过晚安啦~"; await session.send(reply); return reply; } let reply; if (!userState || !userState.hasOhayo) { reply = handleNoOhayoGoodnight(session, hour, minute); } else { userState.hasOyasumi = true; userState.oyasumiTime = now; const wakeSeconds = Math.floor((now.getTime() - userState.ohayoTime.getTime()) / 1e3); const hoursAwake = Math.floor(wakeSeconds / 3600); const minutesAwake = Math.floor(wakeSeconds % 3600 / 60); const secondsAwake = wakeSeconds % 60; reply = `${Tools.roll(oyasumiMessages)},现在是 ${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")},你今天清醒了 ${hoursAwake}小时${minutesAwake}${secondsAwake}秒~`; if (groupId === "633373584") { reply = getSpecialOyasumiReply(hour, reply); } else if (groupId === "738988912") { reply = "你好!测试群专用晚安~"; } else { reply += getNightTimeAdvice(hour); } } await session.send(reply); const [startHour, endHour] = config.oyasumiImageHours; const isInRange = endHour > startHour ? hour >= startHour && hour < endHour : hour >= startHour || hour < endHour; if (config.enableOyasumiImage && isInRange) { await session.send((0, import_koishi.h)("image", { src: aisatsuURL })); } const [existingRecord] = await ctx.database.get("morning_night_record", { userId: session.userId, groupId: session.guildId || "", messageType: "oyasumi" }); if (existingRecord) { await ctx.database.set("morning_night_record", { id: existingRecord.id }, { count: existingRecord.count + 1 // 不更新时间,保留首次记录的时间 // timestamp: now }); } else { await ctx.database.create("morning_night_record", { userId: session.userId, username: session.username, groupId: session.guildId || "", messageType: "oyasumi", timestamp: now, count: 1 }); } return reply; } catch (error) { logger.error("晚安命令执行出错:", error); const errorReply = "执行晚安命令时出现错误,请稍后再试。"; await session.send(errorReply); return errorReply; } }); ctx.command("查询早晚安次数", "查询早安和晚安的发送次数").alias("早晚安次数").action(async ({ session }) => { const userId = session.userId; const groupId = session.guildId || ""; const [ohayoRecord] = await ctx.database.get("morning_night_record", { userId, groupId, messageType: "ohayo" }); const ohayoCount = ohayoRecord ? ohayoRecord.count : 0; const [oyasumiRecord] = await ctx.database.get("morning_night_record", { userId, groupId, messageType: "oyasumi" }); const oyasumiCount = oyasumiRecord ? oyasumiRecord.count : 0; return `你在本群发送早安的次数为 ${ohayoCount} 次,发送晚安的次数为 ${oyasumiCount} 次。`; }); ctx.command("报时", "获取当前时间信息").action(async ({ session }) => { const now = /* @__PURE__ */ new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, "0"); const day = String(now.getDate()).padStart(2, "0"); const hour = String(now.getHours()).padStart(2, "0"); const minute = String(now.getMinutes()).padStart(2, "0"); const second = String(now.getSeconds()).padStart(2, "0"); const timeString = `${year}-${month}-${day} ${hour}:${minute}:${second}`; return `当前时间是:${timeString}`; }); logger.info("Ohayo 插件启动成功"); } function getSpecialOyasumiReply(hour, baseMsg) { switch (true) { case hour < 6: return baseMsg + " 芥子小伙伴,熬夜伤身,快睡个好觉!"; case hour < 12: return baseMsg + " 这个点睡,定好闹钟别迟到!"; case hour < 18: return baseMsg + " 下午就睡啦,小憩恢复精力~ 才有动力去看栗川芥的视频!"; default: return baseMsg + " 芥粉晚安!做个美梦~"; } } // 非特定群的默认回复 switch (true) { case hour < 6: return baseMsg + " 我最亲爱的芥粉!可不要熬夜哦~ 早点休息呀!"; case hour < 12: return baseMsg + " 起床第一件事是大喊我爱栗川芥!今天也要元气满满哦~"; case hour < 18: return baseMsg + " 都下午啦,是不是可以去看看栗川芥的视频呢?记得多喝水哦~"; default: return baseMsg + " 已经是晚上了,看看芥子的视频入眠吧!好梦~"; } } __name(getSpecialOhayoReply, "getSpecialOhayoReply"); function getTimeSegmentReply(hour) { switch (true) { case hour < 6: return " 你起得真早哇,或者你还没睡?不要熬夜哦~"; case hour < 12: return " 祝你有一个愉快的早晨~"; case hour < 18: return " 都下午啦,起床后想做些什么呢?"; default: return " 已经是晚上了,这么晚起床是想直接睡觉吗?"; } } __name(getTimeSegmentReply, "getTimeSegmentReply"); // 非特定群的默认回复 switch (true) { case hour < 6: return " 熬夜对身不好哦,下次早点睡~ 做个甜甜的梦~"; case hour < 12: return " 这个点道晚安,你不会是选在上课时间睡觉吧?记得定好闹钟哦~"; case hour < 18: return " 现在睡觉有点早呢,要不要再玩一会儿?不过累了就好好休息~"; default: return " 要保持精致睡眠哦~ 明天见啦~"; } __name(getNightTimeAdvice, "getNightTimeAdvice"); __name(apply, "apply"); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Config, DailyTask, Tools, apply, inject, logger, name, usage });