koishi-plugin-hellomorning
Version:
让你的bot每天定时打招呼/暖心话/新闻,或者更多!
401 lines (381 loc) • 13.3 kB
JavaScript
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,
apply: () => apply,
inject: () => inject,
name: () => name,
usage: () => usage
});
module.exports = __toCommonJS(src_exports);
var import_koishi_plugin_markdown = require("koishi-plugin-markdown");
// src/assetsUtil.ts
var import_koishi = require("koishi");
var hitokotoUrl1 = "https://v1.hitokoto.cn/";
var hitokotoUrl2 = "https://international.v1.hitokoto.cn/";
var newsUrl = "https://60s.viki.moe/?v2=1";
var newsImgUrl = "https://api.03c3.cn/api/zb";
var muoyuCalendarUrl = "https://api.vvhan.com/api/moyu";
var hitokotoTypeDict = {
动画: "a",
漫画: "b",
游戏: "c",
文学: "d",
原创: "e",
来自网络: "f",
其他: "g",
影视: "h",
诗词: "i",
网易云: "j",
哲学: "k",
抖机灵: "l"
};
var conf;
var http;
var hitokotoUrl;
var log;
async function assetsInit(ctx, config) {
conf = config;
http = ctx.http;
log = ctx.logger("helloMorningUtil");
hitokotoUrl = conf.hitokotOverseasUrl ? hitokotoUrl2 : hitokotoUrl1;
if (conf.debugModel) {
log.level = import_koishi.Logger.DEBUG;
} else {
log.level = import_koishi.Logger.INFO;
}
}
__name(assetsInit, "assetsInit");
async function getHitokoto() {
try {
const randomIndex = Math.floor(
Math.random() * conf.hitokotoTypeArray.length
);
const typeName = conf.hitokotoTypeArray[randomIndex];
const response = await http.get(hitokotoUrl, {
params: {
c: `${hitokotoTypeDict[typeName]}`
}
});
log.debug("hitokoto:", JSON.stringify(response));
log.debug(response);
return [response.hitokoto, response.from];
} catch (error) {
if (error.name === "ForbiddenError" || error.response && error.response.status === 403) {
log.error("hitokoto: 403 Forbidden");
return "";
}
log.error(error);
return "";
}
}
__name(getHitokoto, "getHitokoto");
async function getNewsText() {
try {
const response = await http.get(newsUrl);
log.debug("newsText:", response.data.news);
return response.data.news.join("\n");
} catch (error) {
log.error(error);
return "";
}
}
__name(getNewsText, "getNewsText");
async function getNewsImg() {
try {
const response = await http.get(newsImgUrl);
log.debug("newsImg:", response);
return import_koishi.h.image(response, "image/png");
} catch (error) {
log.error(error);
return "";
}
}
__name(getNewsImg, "getNewsImg");
async function getMuoyuImg() {
try {
const response = await http.get(muoyuCalendarUrl);
log.debug("muoyuImg:", response);
return import_koishi.h.image(response, "image/png");
} catch (error) {
log.error(error);
return "";
}
}
__name(getMuoyuImg, "getMuoyuImg");
// src/config.ts
var import_koishi2 = require("koishi");
var name = "hellomorning";
var inject = {
required: ["cron", "database"],
optional: ["rainbow"]
};
var usage = `
# 不只是一个定时打招呼插件!
### 定时发送:
每隔一分钟都发送一次:
分 时 日 周
-1,-1,-1,-1
每天早晨7点30分发送一次:
分 时 日 周
30,7,-1,-1
每周六12点发送一次:
分 时 日 周
0,12,-1, 6
高级定时功能可参考<a href="http://crontab.org/">cron</a>
不要设置不存在的时间哦
### 格式化输出:
**开启格式化输出会使单独设置的一言,新闻等开关失效**
可用转义(不区分大小写):
| 转义原字符 | 转义后|
|---|----|
|{hello} | 问候语|
|{hitokoto} | 一言|
|{newsImg} | 60s(图片)|
|{newsText} | 60s(文本)|
|{muoyuImg} | 摸鱼日历(图片)|
|{{}} | 转义大括号|
例:
\`\`\`
{hello}
{hitokoto}
\`\`\`
会输出类似:
\`\`\`
早上好,祝你度过美好的一天!!\(^▽^)/
(我是一句一言)
\`\`\`
### 其他:
已经安装服务还提示未加载不用管,能跑就行
启用全局广播时建议将全局设置的delay.broadcast设置为2000以上
`;
var Config = import_koishi2.Schema.intersect([
import_koishi2.Schema.object({
helloMessage: import_koishi2.Schema.string().role("textarea", { rows: [2, 4] }).default("早上好,祝你度过美好的一天!!\(^▽^)/").description(
"配置定时发送的自定义消息(支持markdown(主要用来嵌入自定义的图片))"
),
min: import_koishi2.Schema.number().default(50).max(59).min(-1).description("每小时的第几分钟(0-59)"),
hour: import_koishi2.Schema.number().default(7).max(23).min(-1).description("每天的第几小时(0-23)"),
dayOfMonth: import_koishi2.Schema.number().default(-1).max(31).min(-1).description("每个月的第几天(0-31)"),
weekDay: import_koishi2.Schema.number().default(-1).max(7).min(-1).description("周几(1-7)"),
advancedTimer: import_koishi2.Schema.boolean().default(false).description("该选项启用后上述基础定时设置将无效")
}).description("基础设置"),
import_koishi2.Schema.object({
isOutputFormat: import_koishi2.Schema.boolean().default(false).description("格式化输出格式")
}).description("格式化输出"),
import_koishi2.Schema.union([
import_koishi2.Schema.object({
isOutputFormat: import_koishi2.Schema.const(true).required(),
formatText: import_koishi2.Schema.string().role("textarea", { rows: [2, 4] }).default("")
}),
import_koishi2.Schema.object({})
]).description("格式化设置"),
import_koishi2.Schema.union([
import_koishi2.Schema.object({
advancedTimer: import_koishi2.Schema.const(true).required(),
cronTime: import_koishi2.Schema.string().description("cron").default("50 7 * * *")
}),
import_koishi2.Schema.object({})
]),
import_koishi2.Schema.object({
addHitokoto: import_koishi2.Schema.boolean().default(true).description("是否添加一言")
}).description("一言设置"),
import_koishi2.Schema.union([
import_koishi2.Schema.object({
addHitokoto: import_koishi2.Schema.const(true),
hitokotOverseasUrl: import_koishi2.Schema.boolean().default(false).description("启用一言海外API"),
hitokotoTypeArray: import_koishi2.Schema.array(
import_koishi2.Schema.union([
"动画",
"漫画",
"游戏",
"文学",
"原创",
"来自网络",
"其他",
"影视",
"诗词",
"网易云",
"哲学",
"抖机灵"
])
).default(["原创"]).description("配置一言的类型").role("select")
}),
import_koishi2.Schema.object({})
]),
import_koishi2.Schema.object({
addNews: import_koishi2.Schema.boolean().default(false).description("是否添加资讯")
}).description("资讯设置"),
import_koishi2.Schema.union([
import_koishi2.Schema.object({
addNews: import_koishi2.Schema.const(true).required(),
newsInterface: import_koishi2.Schema.union(["60s(文本)", "60s(图片)", "摸鱼日历(图片)"]).default("60s(图片)").description("资讯接口(每个内容都不同)")
}),
import_koishi2.Schema.object({})
]),
// Schema.object({
// addWeiyu: Schema.boolean().default(false).description('是否添加每日微语'),
// }).description('微语设置'),
import_koishi2.Schema.object({
broad: import_koishi2.Schema.boolean().default(true).description("在所有群聊广播,关闭后可指定群配置")
}).description("全局广播"),
import_koishi2.Schema.union([
import_koishi2.Schema.object({
broad: import_koishi2.Schema.const(false).required(),
broadArray: import_koishi2.Schema.array(
import_koishi2.Schema.object({
adapter: import_koishi2.Schema.string().default("onebot").description("适配器名"),
botId: import_koishi2.Schema.string().default("552487878").description("机器人账号"),
groupId: import_koishi2.Schema.string().default("1145141919").description("群组号")
})
).role("table")
}),
import_koishi2.Schema.object({})
]),
import_koishi2.Schema.object({
enableRainbow: import_koishi2.Schema.boolean().default(false).description("启用 hello-rainbow 服务")
}).description("资讯设置"),
import_koishi2.Schema.union([
import_koishi2.Schema.object({
enableRainbow: import_koishi2.Schema.const(true).required(),
city: import_koishi2.Schema.string().default("北京").description("城市名")
}),
import_koishi2.Schema.object({})
]),
import_koishi2.Schema.object({
debugModel: import_koishi2.Schema.boolean().default(false).description("开启后会输出详细日志")
}).description("调试模式")
]);
// src/index.ts
function apply(ctx, config) {
assetsInit(ctx, config);
const morntime = config.advancedTimer ? config.cronTime : `${formatValue(config.min)} ${formatValue(config.hour)} ${formatValue(
config.dayOfMonth
)} * ${formatValue(config.weekDay)}`;
ctx.command("hellomorning", "手动触发hellomorning发送到当前会话").action(() => getMorningMsg());
try {
ctx.cron(morntime, async () => {
ctx.emit("hellomorning/moring-event", null);
});
} catch (error) {
ctx.logger.error(error);
}
ctx.on("hellomorning/moring-event", async () => await sendMorningMsg());
async function sendMorningMsg() {
const outMsg = await getMorningMsg();
if (config.broad) await ctx.broadcast(outMsg);
else {
for (const broad of config.broadArray) {
ctx.bots[`${broad.adapter}:${broad.botId}`].sendMessage(
`${broad.groupId}`,
outMsg
);
ctx.sleep(2e3);
}
}
}
__name(sendMorningMsg, "sendMorningMsg");
async function getMorningMsg() {
let { isOutputFormat, formatText, helloMessage, addHitokoto, addNews } = config;
let outMsg = "";
if (!isOutputFormat) {
outMsg += (0, import_koishi_plugin_markdown.transform)(helloMessage);
if (addHitokoto) {
const hitokoto = await getHitokoto();
outMsg += hitokoto[0] + "\n ---" + hitokoto[1];
}
if (addNews) {
outMsg += await getNewsImg();
}
return await pushRainbowInfo(ctx, config, outMsg);
}
const regexList = [
/\{hello\}/gi,
/\{hitokoto\}/gi,
/\{newsText\}/gi,
/\{newsImg\}/gi,
/\{muoyuImg\}/gi
];
const indices = [];
regexList.forEach((regex) => {
for (let match of formatText.matchAll(regex)) {
indices.push({ regex: regex.source, index: match.index });
}
});
indices.sort((a, b) => a.index - b.index);
let sliptIndex = 0;
for (let i = 0; i < indices.length; i++) {
const regIndex = indices[i].index;
const strSlipt = formatText.slice(sliptIndex, regIndex);
if (strSlipt) outMsg += strSlipt;
switch (indices[i].regex) {
case "\\{hello\\}":
sliptIndex = regIndex + 7;
outMsg += (0, import_koishi_plugin_markdown.transform)(helloMessage);
break;
case "\\{hitokoto\\}":
sliptIndex = regIndex + 10;
const hitokoto = await getHitokoto();
if (hitokoto === "") break;
outMsg += hitokoto[0] + "\n ---" + hitokoto[1];
break;
case "\\{newsText\\}":
sliptIndex = regIndex + 10;
outMsg += await getNewsText();
break;
case "\\{newsImg\\}":
sliptIndex = regIndex + 9;
outMsg += await getNewsImg();
break;
case "\\{muoyuImg\\}":
sliptIndex = regIndex + 10;
outMsg += await getMuoyuImg();
break;
}
}
outMsg += formatText.slice(sliptIndex);
return await pushRainbowInfo(ctx, config, outMsg);
}
__name(getMorningMsg, "getMorningMsg");
}
__name(apply, "apply");
async function pushRainbowInfo(ctx, config, outMsg) {
let outElement = outMsg;
if (config.enableRainbow && ctx.rainbow) {
const rainbowInfo = await ctx.rainbow.getWeather(config.city, 3);
outElement += rainbowInfo;
}
return outElement;
}
__name(pushRainbowInfo, "pushRainbowInfo");
function formatValue(value) {
if (value && value === -1) return "*";
return value === -1 ? "*" : value.toString();
}
__name(formatValue, "formatValue");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Config,
apply,
inject,
name,
usage
});