UNPKG

koishi-plugin-adapter-matrix

Version:

Matrix Adapter for koishi

177 lines 7.47 kB
"use strict"; 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; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MatrixBot = void 0; const satori_1 = require("@satorijs/satori"); const http_1 = require("./http"); const modulator_1 = require("./modulator"); const Matrix = __importStar(require("./types")); const utils_1 = require("./utils"); class MatrixBot extends satori_1.Bot { constructor(ctx, config) { super(ctx, config); this.rooms = []; this.id = config.id || config.selfId; this.selfId = `@${this.id}:${this.config.host}`; this.userId = this.selfId; this.endpoint = (config.endpoint || `https://${config.host}`) + '/_matrix'; this.internal = new Matrix.Internal(this); ctx.plugin(http_1.HttpAdapter, this); } async initialize() { let user; try { user = await this.internal.register(this.id, this.config.asToken); } catch (e) { if (e.response.status !== 400 && e.data.errcode !== 'M_USER_IN_USE') throw e; } if (!user) user = await this.internal.login(this.id, this.config.asToken); this.http = this.ctx.http.extend({ ...this.config, endpoint: this.endpoint, headers: { 'Authorization': `Bearer ${user.access_token}`, }, }); if (this.config.name) { await this.internal.setDisplayName(this.userId, this.config.name); } if (this.config.avatar) { const { data, mime } = await this.http.file(this.config.avatar); await this.internal.setAvatar(this.userId, Buffer.from(data), mime); } Object.assign(this, await this.getSelf()); const sync = await this.syncRooms(); // dispatch invitiations if (!sync?.rooms?.invite) return; setTimeout(() => Object.entries(sync.rooms.invite).forEach(([roomId, room]) => { const event = room.invite_state.events.find(event => event.type === 'm.room.member' && event.content.membership === 'invite'); event.room_id = roomId; (0, utils_1.dispatchSession)(this, event); })); } async sendMessage(channelId, content, guildId) { return new modulator_1.MatrixModulator(this, channelId, guildId).send(content); } async sendPrivateMessage(channelId, content) { return new modulator_1.MatrixModulator(this, channelId).send(content); } async getMessage(channelId, messageId) { const event = await this.internal.getEvent(channelId, messageId); return await (0, utils_1.adaptMessage)(this, event); } async deleteMessage(channelId, messageId) { await this.internal.redactEvent(channelId, messageId); } async getSelf() { return await this.getUser(this.userId); } async getUser(userId) { const profile = await this.internal.getProfile(userId); let avatar; if (profile.avatar_url) avatar = this.internal.getAssetUrl(profile.avatar_url); return { userId, avatar, username: userId, nickname: profile.displayname, }; } async getFriendList() { return []; } async deleteFriend() { } async getGuild(guildId) { const events = await this.internal.getState(guildId); const guildName = events.find(event => event.type === 'm.room.name')?.content?.name; return { guildId, guildName }; } async getChannel(channelId) { const events = await this.internal.getState(channelId); const channelName = events.find(event => event.type === 'm.room.name')?.content?.name; return { channelId, channelName }; } async getGuildList() { const sync = await this.syncRooms(); const joined = sync?.rooms?.join; if (!joined) return []; const result = []; for (const [roomId, room] of Object.entries(joined)) { const create = room.state?.events?.find(event => event.type === 'm.room.create'); const space = create?.content?.type === 'm.space'; if (space) result.push(roomId); } return await Promise.all(result.map(this.getGuild.bind(this))); } async getChannelList(guildId) { const state = await this.internal.getState(guildId); const children = state .filter(event => event.type === 'm.space.child') .map(event => event.state_key) .filter(roomId => this.rooms.includes(roomId)); return await Promise.all(children.map(this.getChannel.bind(this))); } async handleFriendRequest() { } // as utils.ts commented, messageId is roomId async handleGuildRequest(messageId, approve, commit) { if (approve) { await this.internal.joinRoom(messageId, commit); } else { await this.internal.leaveRoom(messageId, commit); } this.syncRooms(); } // will be called after m.room.member received async syncRooms() { const sync = await this.internal.sync(true); if (!sync?.rooms?.join) return; this.rooms = Object.keys(sync.rooms.join); return sync; } } exports.MatrixBot = MatrixBot; (function (MatrixBot) { MatrixBot.Config = satori_1.Schema.object({ name: satori_1.Schema.string().description('机器人的名称,如果设置了将会在启动时为机器人更改。'), avatar: satori_1.Schema.string().description('机器人的头像地址,如果设置了将会在启动时为机器人更改。'), id: satori_1.Schema.string().description('机器人的 ID。机器人最后的用户名将会是 @${id}:${host}。').required(), host: satori_1.Schema.string().description('Matrix homeserver 域名。').required(), hsToken: satori_1.Schema.string().description('hs_token').role('secret').required(), asToken: satori_1.Schema.string().description('as_token').role('secret').required(), endpoint: satori_1.Schema.string().description('Matrix homeserver 地址。默认为 https://${host}。'), ...(0, satori_1.omit)(satori_1.Quester.Config.dict, ['endpoint']), }); })(MatrixBot = exports.MatrixBot || (exports.MatrixBot = {})); MatrixBot.prototype.platform = 'matrix'; //# sourceMappingURL=bot.js.map