onebots
Version:
基于icqq的多例oneBot实现
261 lines (260 loc) • 10 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _DingtalkAdapter_disposes;
Object.defineProperty(exports, "__esModule", { value: true });
const adapter_1 = require("../../adapter");
const onebot_1 = require("../../onebot");
const node_dd_bot_1 = require("node-dd-bot");
const path = __importStar(require("path"));
class DingtalkAdapter extends adapter_1.Adapter {
constructor(app, config) {
super(app, "dingtalk", config);
_DingtalkAdapter_disposes.set(this, new Map());
this.icon = `https://img.alicdn.com/imgextra/i4/O1CN01RtfAks1Xa6qJFAekm_!!6000000002939-2-tps-128-128.png`;
}
async startOneBot(oneBot) {
await this.setOnline(oneBot.uin);
const selfInfo = this.getBaseInfo(oneBot.uin);
oneBot.avatar = selfInfo.avatar;
oneBot.nickname = selfInfo.username;
const pkg = require(path.resolve(path.dirname(require.resolve("node-dd-bot")), "../package.json"));
oneBot.dependency = `node-dd-bot v${pkg.version}`;
const disposeArr = [];
const clean = () => {
while (disposeArr.length > 0) {
disposeArr.pop()();
}
oneBot.internal.stop();
};
const messageHandler = event => {
this.emit("message.receive", oneBot.uin, event);
};
oneBot.internal.on("message", messageHandler);
disposeArr.push(() => {
oneBot.internal.off("message", messageHandler);
});
return clean;
}
getBaseInfo(uin) {
const config = this.app.config[`${this.platform}.${uin}`].protocol;
return {
avatar: config.avatar || this.icon,
username: config.username || "钉钉机器人",
};
}
async setOnline(uin) {
const oneBot = this.getOneBot(uin);
await oneBot?.internal.start();
oneBot.status = onebot_1.OneBotStatus.Online;
}
async setOffline(uin) {
const oneBot = this.getOneBot(uin);
await oneBot?.internal.stop();
oneBot.status = onebot_1.OneBotStatus.OffLine;
}
createOneBot(uin, protocol, versions) {
const oneBot = super.createOneBot(uin, protocol, versions);
oneBot.internal = new node_dd_bot_1.Bot({
clientId: oneBot.uin,
log_level: this.app.config.log_level,
...protocol,
});
oneBot.status = onebot_1.OneBotStatus.Online;
return oneBot;
}
call(uin, version, method, args) {
const oneBot = this.oneBots.get(uin);
if (!oneBot) {
throw new Error(`未找到账号${uin}`);
}
if (typeof this[method] === "function")
return this[method](uin, version, args);
if (typeof oneBot.internal[method] !== "function")
throw onebot_1.OneBot.UnsupportedMethodError;
try {
return oneBot.internal[method](...(args || []));
}
catch (e) {
throw new Error(`call internal method error:${e.message}`);
}
}
async sendPrivateMessage(uin, version, args) {
const [user_id, message] = args;
const bot = this.getOneBot(uin);
const result = await bot.internal.sendPrivateMsg(user_id, message);
return {
message_id: version === "V11"
? bot.V11.transformToInt("message_id", `private:${user_id}:${result}`)
: `private:${user_id}:${result}`,
};
}
async sendGroupMessage(uin, version, args) {
const [group_id, message] = args;
const bot = this.getOneBot(uin);
const result = await bot.internal.sendGroupMsg(group_id, message);
return {
message_id: version === "V11"
? bot.V11.transformToInt("message_id", `group:${group_id}:${result}`)
: `group:${group_id}:${result}`,
};
}
deleteMessage(uin, message_id) {
const [from_type, from_id, ...msg_idArr] = message_id.split(":");
const bot = this.getOneBot(uin).internal;
switch (from_type) {
case "private":
return bot.recallPrivateMsg(from_id, msg_idArr.join(":"));
case "group":
return bot.recallGroupMsg(from_id, msg_idArr.join(":"));
case "direct":
throw new Error(`暂不支持撤回${from_type}类型的消息`);
case "guild":
throw new Error(`暂不支持撤回${from_type}类型的消息`);
}
}
fromSegment(onebot, version, segment) {
return []
.concat(segment)
.map(segment => {
if (version === "V12" && ["image", "video", "audio"].includes(segment.type))
return onebot.V12.transformMedia(segment);
return segment;
})
.map(item => {
if (typeof item === "string")
return item;
const { type, data } = item;
return {
type,
...data,
};
});
}
toSegment(version, message) {
return [].concat(message).map(item => {
if (typeof item !== "object")
return {
type: "text",
data: {
text: item + "",
},
};
const { type, ...data } = item;
return {
type,
data,
};
});
}
fromCqcode(version, message) {
const regExpMatchArray = message.match(/\[CQ:([a-z]+),(!])+]/g);
if (!regExpMatchArray)
return [
{
type: "text",
data: {
text: message,
},
},
];
const result = [];
for (const match of regExpMatchArray) {
const [type, ...valueArr] = match.substring(1, match.length - 1).split(",");
result.push({
type: type,
data: Object.fromEntries(valueArr.map(item => {
const [key, value] = item.split("=");
return [key, value];
})),
});
}
return result;
}
formatEventPayload(uin, version, event, data) {
const oneBot = this.getOneBot(uin);
const result = {
id: data.id || Math.random().toString(36).slice(2),
[version === "V12" ? "type" : "post_type"]: event,
version: version,
self: {
platform: "dingtalk",
user_id: data.self_id,
},
detail_type: data.message_type || data.notice_type || data.request_type,
platform: "dingtalk",
time: data.timestamp,
...data,
sender: {
...(data?.sender || {}),
},
user_id: data.user_id || data.sender?.user_id,
message_id: `${data.message_type}:${data.group_id || data.user_id}:${data.message_id}`,
};
delete result.bot;
if (event === "message") {
result.alt_message = result.raw_message || "";
}
if (version === "V11") {
oneBot.V11.transformStrToIntForObj(result, ["user_id", "group_id", "message_id"]);
}
return result;
}
async start(uin) {
const startOneBots = [...this.oneBots.values()].filter(oneBot => {
return uin ? oneBot.uin === uin : true;
});
for (const oneBot of startOneBots) {
__classPrivateFieldGet(this, _DingtalkAdapter_disposes, "f").set(oneBot.uin, await this.startOneBot(oneBot));
}
const { protocol } = this.config;
await super.start();
}
async stop(uin) {
const stopOneBots = [...this.oneBots.values()].filter(oneBot => {
return uin ? oneBot.uin === uin : true;
});
for (const oneBot of stopOneBots) {
const dispose = __classPrivateFieldGet(this, _DingtalkAdapter_disposes, "f").get(oneBot.uin);
if (dispose) {
dispose();
}
}
await super.stop();
}
getSelfInfo(uin, version) {
const oneBot = this.oneBots.get(uin);
return {
nickname: oneBot?.internal?.nickname,
status: onebot_1.OneBotStatus.Online,
};
}
}
_DingtalkAdapter_disposes = new WeakMap();
exports.default = DingtalkAdapter;