当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript Bridge.getClientFactory方法代码示例

本文整理汇总了TypeScript中matrix-appservice-bridge.Bridge.getClientFactory方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Bridge.getClientFactory方法的具体用法?TypeScript Bridge.getClientFactory怎么用?TypeScript Bridge.getClientFactory使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matrix-appservice-bridge.Bridge的用法示例。


在下文中一共展示了Bridge.getClientFactory方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: 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

示例2: 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

示例3: EventToEmbed

    public async EventToEmbed(
        event: IMatrixEvent, channel: Discord.TextChannel, getReply: boolean = true,
    ): Promise<IMatrixEventProcessorResult> {
        const mxClient = this.bridge.getClientFactory().getClientAs();
        let profile: IMatrixEvent | null = null;
        try {
            profile = await mxClient.getStateEvent(event.room_id, "m.room.member", event.sender);
            if (!profile) {
                profile = await mxClient.getProfileInfo(event.sender);
            }
            if (!profile) {
                log.warn(`User ${event.sender} has no member state and no profile. That's odd.`);
            }
        } catch (err) {
            log.warn(`Trying to fetch member state or profile for ${event.sender} failed`, err);
        }

        const params = {
            mxClient,
            roomId: event.room_id,
            userId: event.sender,
        } as IMatrixMessageProcessorParams;
        if (profile) {
            params.displayname = profile.displayname;
        }

        let body: string = "";
        if (event.type !== "m.sticker") {
            body = await this.matrixMsgProcessor.FormatMessage(event.content as IMatrixMessage, channel.guild, params);
        }

        const messageEmbed = new Discord.RichEmbed();
        messageEmbed.setDescription(body);
        await this.SetEmbedAuthor(messageEmbed, event.sender, profile);
        const replyEmbed = getReply ? (await this.GetEmbedForReply(event, channel)) : undefined;
        if (replyEmbed && replyEmbed.fields) {
            for (let i = 0; i < replyEmbed.fields.length; i++) {
                const f = replyEmbed.fields[i];
                if (f.name === "ping") {
                    messageEmbed.description += `\n(${f.value})`;
                    replyEmbed.fields.splice(i, 1);
                    break;
                }
            }
        }
        return {
            messageEmbed,
            replyEmbed,
        };
    }
开发者ID:Half-Shot,项目名称:matrix-appservice-discord,代码行数:50,代码来源:matrixeventprocessor.ts

示例4: ProcessMatrixMsgEvent

    public async ProcessMatrixMsgEvent(event: IMatrixEvent, guildId: string, channelId: string): Promise<void> {
        const mxClient = this.bridge.getClientFactory().getClientAs();
        log.verbose(`Looking up ${guildId}_${channelId}`);
        const result = await this.LookupRoom(guildId, channelId, event.sender);
        const chan = result.channel;
        const botUser = result.botUser;

        const embedSet = await this.mxEventProcessor.EventToEmbed(event, chan);
        const embed = embedSet.messageEmbed;
        const opts: Discord.MessageOptions = {};
        const file = await this.mxEventProcessor.HandleAttachment(event, mxClient);
        if (typeof(file) === "string") {
            embed.description += " " + file;
        } else {
            opts.file = file;
        }

        let msg: Discord.Message | null | (Discord.Message | null)[] = null;
        let hook: Discord.Webhook | undefined;
        if (botUser) {
            const webhooks = await chan.fetchWebhooks();
            hook = webhooks.filterArray((h) => h.name === "_matrix").pop();
            // Create a new webhook if none already exists
            try {
                if (!hook) {
                    hook = await chan.createWebhook(
                        "_matrix",
                        MATRIX_ICON_URL,
                        "Matrix Bridge: Allow rich user messages");
                }
            } catch (err) {
                log.error("Unable to create \"_matrix\" webhook. ", err);
            }
        }
        try {
            if (!botUser) {
                opts.embed = embedSet.replyEmbed;
                msg = await chan.send(embed.description, opts);
            } else if (hook) {
                msg = await hook.send(embed.description, {
                    avatarURL: embed!.author!.icon_url,
                    embeds: embedSet.replyEmbed ? [embedSet.replyEmbed] : undefined,
                    files: opts.file ? [opts.file] : undefined,
                    username: embed!.author!.name,
                } as Discord.WebhookMessageOptions);
            } else {
                if (embedSet.replyEmbed) {
                    embed.addField("Replying to", embedSet.replyEmbed!.author!.name);
                    embed.addField("Reply text", embedSet.replyEmbed.description);
                }
                opts.embed = embed;
                msg = await chan.send("", opts);
            }
        } catch (err) {
            log.error("Couldn't send message. ", err);
        }
        if (!Array.isArray(msg)) {
            msg = [msg];
        }
        await Util.AsyncForEach(msg, async (m: Discord.Message) => {
            log.verbose("Sent ", 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;
            // Webhooks don't send guild info.
            evt.GuildId = guildId;
            evt.ChannelId = channelId;
            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);
            }
        }
        return;
    }
开发者ID:Half-Shot,项目名称:matrix-appservice-discord,代码行数:80,代码来源:bot.ts


注:本文中的matrix-appservice-bridge.Bridge.getClientFactory方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。