當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript matrix-appservice-bridge.Bridge類代碼示例

本文整理匯總了TypeScript中matrix-appservice-bridge.Bridge的典型用法代碼示例。如果您正苦於以下問題:TypeScript Bridge類的具體用法?TypeScript Bridge怎麽用?TypeScript Bridge使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Bridge類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: run

async function run() {
    try {
        await bridge.loadDatabases();
    } catch (e) {
        log.error(`Failed to load database`, e);
    }

    let rooms = await bridge.getRoomStore().getEntriesByRemoteRoomData({
        discord_type: "text",
    });
    rooms = rooms.filter((r) => r.remote.get("plumbed") !== true );
    const client = clientFactory.getClientAs();
    log.info(`Got ${rooms.length} rooms to set`);
    try {
        await Util.AsyncForEach(rooms, async (room) => {
            const guild = room.remote.get("discord_guild");
            const roomId = room.matrix.getId();
            try {
                await client.setRoomDirectoryVisibilityAppService(
                    guild,
                    roomId,
                    "public",
                );
                log.info(`Set ${roomId} to visible in ${guild}'s directory`);
            } catch (e) {
                log.error(`Failed to set ${roomId} to visible in ${guild}'s directory`, e);
            }
        });
    } catch (e) {
        log.error(`Failed to run script`, e);
    }
}
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:32,代碼來源:addRoomsToDirectory.ts

示例2: GetIntentFromDiscordMember

 public GetIntentFromDiscordMember(member: Discord.GuildMember | Discord.User, webhookID?: string): Intent {
     if (webhookID) {
         // webhookID and user IDs are the same, they are unique, so no need to prefix _webhook_
         const name = member instanceof Discord.User ? member.username : member.user.username;
         const nameId = new MatrixUser(`@${name}`).localpart;
         return this.bridge.getIntentFromLocalpart(`_discord_${webhookID}_${nameId}`);
     }
     return this.bridge.getIntentFromLocalpart(`_discord_${member.id}`);
 }
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:9,代碼來源:bot.ts

示例3: run

async function run() {
    try {
        await bridge.loadDatabases();
    } catch (e) {
        await discordstore.init();
    }
    bridge._clientFactory = clientFactory;
    bridge._botClient = bridge._clientFactory.getClientAs();
    bridge._botIntent = new Intent(bridge._botClient, bridge._botClient, { registered: true });
    await discordbot.ClientFactory.init();
    const client = await discordbot.ClientFactory.getClient();

    // first set update_icon to true if needed
    const mxRoomEntries = await bridge.getRoomStore().getEntriesByRemoteRoomData({
        update_name: true,
        update_topic: true,
    });

    const promiseList: Promise<void>[] = [];
    mxRoomEntries.forEach((entry) => {
        if (entry.remote.get("plumbed")) {
            return; // skipping plumbed rooms
        }
        const updateIcon = entry.remote.get("update_icon");
        if (updateIcon !== undefined && updateIcon !== null) {
            return; // skipping because something was set manually
        }
        entry.remote.set("update_icon", true);
        promiseList.push(bridge.getRoomStore().upsertEntry(entry));
    });
    await Promise.all(promiseList);

    // now it is time to actually run the updates
    const promiseList2: Promise<void>[] = [];

    let curDelay = config.limits.roomGhostJoinDelay; // we'll just re-use this
    client.guilds.forEach((guild) => {
        promiseList2.push((async () => {
            await Bluebird.delay(curDelay);
            try {
                await discordbot.ChannelSyncroniser.OnGuildUpdate(guild, true);
            } catch (err) {
                log.warn(`Couldn't update rooms of guild ${guild.id}`, err);
            }
        })());
        curDelay += config.limits.roomGhostJoinDelay;
    });
    try {
        await Promise.all(promiseList2);
    } catch (err) {
        log.error(err);
    }
    process.exit(0);
}
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:54,代碼來源:chanfix.ts

示例4: GetEmbedForReply

    public async GetEmbedForReply(
        event: IMatrixEvent,
        channel: Discord.TextChannel,
    ): Promise<Discord.RichEmbed|undefined> {
        if (!event.content) {
            event.content = {};
        }

        const relatesTo = event.content["m.relates_to"];
        let eventId = "";
        if (relatesTo && relatesTo["m.in_reply_to"]) {
            eventId = relatesTo["m.in_reply_to"].event_id;
        } else {
            return;
        }

        const intent = this.bridge.getIntent();
        // Try to get the event.
        try {
            const sourceEvent = await intent.getEvent(event.room_id, eventId);
            sourceEvent.content.body = sourceEvent.content.body  || "Reply with unknown content";
            const replyEmbed = (await this.EventToEmbed(sourceEvent, channel, false)).messageEmbed;

            // if we reply to a discord member, ping them!
            if (this.bridge.getBot().isRemoteUser(sourceEvent.sender)) {
                const uid = new MatrixUser(sourceEvent.sender.replace("@", "")).localpart.substring("_discord".length);
                replyEmbed.addField("ping", `<@${uid}>`);
            }

            replyEmbed.setTimestamp(new Date(sourceEvent.origin_server_ts));

            if (this.HasAttachment(sourceEvent)) {
                const mxClient = this.bridge.getClientFactory().getClientAs();
                const url = mxClient.mxcUrlToHttp(sourceEvent.content.url);
                if (["m.image", "m.sticker"].includes(sourceEvent.content.msgtype as string)
                    || sourceEvent.type === "m.sticker") {
                    // we have an image reply
                    replyEmbed.setImage(url);
                } else {
                    const name = this.GetFilenameForMediaEvent(sourceEvent.content);
                    replyEmbed.description = `[${name}](${url})`;
                }
            }
            return replyEmbed;
        } catch (ex) {
            log.warn("Failed to handle reply, showing a unknown embed:", ex);
        }
        // For some reason we failed to get the event, so using fallback.
        const embed = new Discord.RichEmbed();
        embed.setDescription("Reply with unknown content");
        embed.setAuthor("Unknown");
        return embed;
    }
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:53,代碼來源:matrixeventprocessor.ts

示例5: SetEmbedAuthor

    private async SetEmbedAuthor(embed: Discord.RichEmbed, sender: string, profile?: IMatrixEvent | null) {
        const intent = this.bridge.getIntent();
        let displayName = sender;
        let avatarUrl;

        // Are they a discord user.
        if (this.bridge.getBot().isRemoteUser(sender)) {
            const localpart = new MatrixUser(sender.replace("@", "")).localpart;
            const userOrMember = await this.discord.GetDiscordUserOrMember(localpart.substring("_discord".length));
            if (userOrMember instanceof Discord.User) {
                embed.setAuthor(
                    userOrMember.username,
                    userOrMember.avatarURL,
                );
                return;
            } else if (userOrMember instanceof Discord.GuildMember) {
                embed.setAuthor(
                    userOrMember.displayName,
                    userOrMember.user.avatarURL,
                );
                return;
            }
            // Let it fall through.
        }
        if (!profile) {
            try {
                profile = await intent.getProfileInfo(sender);
            } catch (ex) {
                log.warn(`Failed to fetch profile for ${sender}`, ex);
            }
        }

        if (profile) {
            if (profile.displayname &&
                profile.displayname.length >= MIN_NAME_LENGTH &&
                profile.displayname.length <= MAX_NAME_LENGTH) {
                displayName = profile.displayname;
            }

            if (profile.avatar_url) {
                const mxClient = this.bridge.getClientFactory().getClientAs();
                avatarUrl = mxClient.mxcUrlToHttp(profile.avatar_url, DISCORD_AVATAR_WIDTH, DISCORD_AVATAR_HEIGHT);
            }
        }
        embed.setAuthor(
            displayName.substr(0, MAX_NAME_LENGTH),
            avatarUrl,
            `https://matrix.to/#/${sender}`,
        );
    }
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:50,代碼來源:matrixeventprocessor.ts

示例6: GetRoomIdsFromGuild

 public async GetRoomIdsFromGuild(guild: Discord.Guild, member?: Discord.GuildMember): Promise<string[]> {
     if (member) {
         let rooms: string[] = [];
         await Util.AsyncForEach(guild.channels.array(), async (channel) => {
             if (channel.type !== "text" || !channel.members.has(member.id)) {
                 return;
             }
             try {
                 rooms = rooms.concat(await this.channelSync.GetRoomIdsFromChannel(channel));
             } catch (e) { } // no bridged rooms for this channel
         });
         if (rooms.length === 0) {
             log.verbose(`No rooms were found for this guild and member (guild:${guild.id} member:${member.id})`);
             throw new Error("Room(s) not found.");
         }
         return rooms;
     } else {
         const rooms = await this.bridge.getRoomStore().getEntriesByRemoteRoomData({
             discord_guild: guild.id,
         });
         if (rooms.length === 0) {
             log.verbose(`Couldn't find room(s) for guild id:${guild.id}.`);
             throw new Error("Room(s) not found.");
         }
         return rooms.map((room) => room.matrix.getId());
     }
 }
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:27,代碼來源:bot.ts

示例7: ProcessMatrixStateEvent

 public async ProcessMatrixStateEvent(event: IMatrixEvent): Promise<void> {
     log.verbose(`Got state event from ${event.room_id} ${event.type}`);
     const channel = await this.GetChannelFromRoomId(event.room_id) as Discord.TextChannel;
     const msg = this.mxEventProcessor.StateEventToMessage(event, channel);
     if (!msg) {
         return;
     }
     let res = await channel.send(msg);
     if (!Array.isArray(res)) {
         res = [res];
     }
     await Util.AsyncForEach(res, async (m: Discord.Message) => {
         log.verbose("Sent (state msg) ", m.id);
         this.sentMessages.push(m.id);
         this.lastEventIds[event.room_id] = event.event_id;
         const evt = new DbEvent();
         evt.MatrixId = `${event.event_id};${event.room_id}`;
         evt.DiscordId = m.id;
         evt.GuildId = channel.guild.id;
         evt.ChannelId = channel.id;
         await this.store.Insert(evt);
     });
     if (!this.config.bridge.disableReadReceipts) {
         try {
             await this.bridge.getIntent().sendReadReceipt(event.room_id, event.event_id);
         } catch (err) {
             log.error(`Failed to send read receipt for ${event}. `, err);
         }
     }
 }
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:30,代碼來源:bot.ts

示例8: run

async function run() {
    try {
        await bridge.loadDatabases();
    } catch (e) {
        await discordstore.init();
    }
    const userSync = new UserSyncroniser(bridge, config, discordbot);
    bridge._clientFactory = clientFactory;
    await discordbot.ClientFactory.init();
    const client = await discordbot.ClientFactory.getClient();

    const promiseList: Promise<void>[] = [];
    let curDelay = config.limits.roomGhostJoinDelay;
    try {
        client.guilds.forEach((guild) => {
            guild.members.forEach((member) => {
                if (member.id === client.user.id) {
                    return;
                }
                promiseList.push((async () => {
                    await Bluebird.delay(curDelay);
                    let currentSchedule = JOIN_ROOM_SCHEDULE[0];
                    const doJoin = async () => {
                        await Util.DelayedPromise(currentSchedule);
                        await userSync.OnUpdateGuildMember(member, true);
                    };
                    const errorHandler = async (err) => {
                        log.error(`Error joining rooms for ${member.id}`);
                        log.error(err);
                        const idx = JOIN_ROOM_SCHEDULE.indexOf(currentSchedule);
                        if (idx === JOIN_ROOM_SCHEDULE.length - 1) {
                            log.warn(`Cannot join rooms for ${member.id}`);
                            throw new Error(err);
                        } else {
                            currentSchedule = JOIN_ROOM_SCHEDULE[idx + 1];
                            try {
                                await doJoin();
                            } catch (e) {
                                await errorHandler(e);
                            }
                        }
                    };
                    try {
                        await doJoin();
                    } catch (e) {
                        await errorHandler(e);
                    }
                })());
                curDelay += config.limits.roomGhostJoinDelay;
            });
        });

        await Promise.all(promiseList);
    } catch (err) {
        log.error(err);
    }
    process.exit(0);
}
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:58,代碼來源:ghostfix.ts

示例9:

 mxRoomEntries.forEach((entry) => {
     if (entry.remote.get("plumbed")) {
         return; // skipping plumbed rooms
     }
     const updateIcon = entry.remote.get("update_icon");
     if (updateIcon !== undefined && updateIcon !== null) {
         return; // skipping because something was set manually
     }
     entry.remote.set("update_icon", true);
     promiseList.push(bridge.getRoomStore().upsertEntry(entry));
 });
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:11,代碼來源:chanfix.ts

示例10: GetRoomIdsFromChannel

 public async GetRoomIdsFromChannel(channel: Discord.Channel): Promise<string[]> {
     if (!this.roomStore) {
         this.roomStore = this.bridge.getRoomStore();
     }
     const rooms = await this.roomStore.getEntriesByRemoteRoomData({
         discord_channel: channel.id,
     });
     if (rooms.length === 0) {
         log.verbose(`Couldn't find room(s) for channel ${channel.id}.`);
         return Promise.reject("Room(s) not found.");
     }
     return rooms.map((room) => room.matrix.getId() as string);
 }
開發者ID:Half-Shot,項目名稱:matrix-appservice-discord,代碼行數:13,代碼來源:channelsyncroniser.ts


注:本文中的matrix-appservice-bridge.Bridge類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。