本文整理汇总了TypeScript中matrix-appservice-bridge.Bridge.getIntent方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Bridge.getIntent方法的具体用法?TypeScript Bridge.getIntent怎么用?TypeScript Bridge.getIntent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matrix-appservice-bridge.Bridge
的用法示例。
在下文中一共展示了Bridge.getIntent方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: 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);
}
}
}
示例2: 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;
}
示例3: 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}`,
);
}
示例4: ApplyStateToChannel
private async ApplyStateToChannel(channelsState: IChannelState) {
const intent = this.bridge.getIntent();
for (const channelState of channelsState.mxChannels) {
let roomUpdated = false;
const remoteRoom = (await this.roomStore.getEntriesByMatrixId(channelState.mxid))[0];
if (channelState.name !== null) {
log.verbose(`Updating channelname for ${channelState.mxid} to "${channelState.name}"`);
await intent.setRoomName(channelState.mxid, channelState.name);
remoteRoom.remote.set("discord_name", channelState.name);
roomUpdated = true;
}
if (channelState.topic !== null) {
log.verbose(`Updating channeltopic for ${channelState.mxid} to "${channelState.topic}"`);
await intent.setRoomTopic(channelState.mxid, channelState.topic);
remoteRoom.remote.set("discord_topic", channelState.topic);
roomUpdated = true;
}
if (channelState.iconUrl !== null && channelState.iconId !== null) {
log.verbose(`Updating icon_url for ${channelState.mxid} to "${channelState.iconUrl}"`);
if (channelsState.iconMxcUrl === null) {
const iconMxc = await Util.UploadContentFromUrl(
channelState.iconUrl,
intent,
channelState.iconId,
);
channelsState.iconMxcUrl = iconMxc.mxcUrl;
}
await intent.setRoomAvatar(channelState.mxid, channelsState.iconMxcUrl);
remoteRoom.remote.set("discord_iconurl", channelState.iconUrl);
remoteRoom.remote.set("discord_iconurl_mxc", channelsState.iconMxcUrl);
roomUpdated = true;
}
if (channelState.removeIcon) {
log.verbose(`Clearing icon_url for ${channelState.mxid}`);
await intent.setRoomAvatar(channelState.mxid, null);
remoteRoom.remote.set("discord_iconurl", null);
remoteRoom.remote.set("discord_iconurl_mxc", null);
roomUpdated = true;
}
if (roomUpdated) {
await this.roomStore.upsertEntry(remoteRoom);
}
}
}
示例5: GetEmoji
public async GetEmoji(name: string, animated: boolean, id: string): Promise<string> {
if (!id.match(/^\d+$/)) {
throw new Error("Non-numerical ID");
}
const dbEmoji = await this.store.Get(DbEmoji, {emoji_id: id});
if (!dbEmoji) {
throw new Error("Couldn't fetch from store");
}
if (!dbEmoji.Result) {
const url = `https://cdn.discordapp.com/emojis/${id}${animated ? ".gif" : ".png"}`;
const intent = this.bridge.getIntent();
const mxcUrl = (await Util.UploadContentFromUrl(url, intent, name)).mxcUrl;
dbEmoji.EmojiId = id;
dbEmoji.Name = name;
dbEmoji.Animated = animated;
dbEmoji.MxcUrl = mxcUrl;
await this.store.Insert(dbEmoji);
}
return dbEmoji.MxcUrl;
}
示例6: DeleteDiscordMessage
private async DeleteDiscordMessage(msg: Discord.Message) {
log.info(`Got delete event for ${msg.id}`);
const storeEvent = await this.store.Get(DbEvent, {discord_id: msg.id});
if (!storeEvent || !storeEvent.Result) {
log.warn(`Could not redact because the event was not in the store.`);
return;
}
while (storeEvent.Next()) {
log.info(`Deleting discord msg ${storeEvent.DiscordId}`);
const intent = this.GetIntentFromDiscordMember(msg.author, msg.webhookID);
const matrixIds = storeEvent.MatrixId.split(";");
try {
await intent.getClient().redactEvent(matrixIds[1], matrixIds[0]);
} catch (ex) {
log.warn(`Failed to delete ${storeEvent.DiscordId}, retrying as bot`);
try {
await this.bridge.getIntent().getClient().redactEvent(matrixIds[1], matrixIds[0]);
} catch (ex) {
log.warn(`Failed to delete ${storeEvent.DiscordId}, giving up`);
}
}
}
}
示例7: StateEventToMessage
public StateEventToMessage(event: IMatrixEvent, channel: Discord.TextChannel): string | undefined {
const SUPPORTED_EVENTS = ["m.room.member", "m.room.name", "m.room.topic"];
if (!SUPPORTED_EVENTS.includes(event.type)) {
log.verbose(`${event.event_id} ${event.type} is not displayable.`);
return;
}
if (event.sender === this.bridge.getIntent().getClient().getUserId()) {
log.verbose(`${event.event_id} ${event.type} is by our bot user, ignoring.`);
return;
}
let msg = `\`${event.sender}\` `;
if (event.type === "m.room.name") {
msg += `set the name to \`${event.content!.name}\``;
} else if (event.type === "m.room.topic") {
msg += `set the topic to \`${event.content!.topic}\``;
} else if (event.type === "m.room.member") {
const membership = event.content!.membership;
if (membership === "join"
&& event.unsigned.prev_content === undefined) {
msg += `joined the room`;
} else if (membership === "invite") {
msg += `invited \`${event.state_key}\` to the room`;
} else if (membership === "leave" && event.state_key !== event.sender) {
msg += `kicked \`${event.state_key}\` from the room`;
} else if (membership === "leave") {
msg += `left the room`;
} else if (membership === "ban") {
msg += `banned \`${event.state_key}\` from the room`;
}
}
msg += " on Matrix.";
return msg;
}
示例8: 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;
}
示例9: handleChannelDeletionForRoom
private async handleChannelDeletionForRoom(
channel: Discord.TextChannel,
roomId: string,
entry: Entry): Promise<void> {
log.info(`Deleting ${channel.id} from ${roomId}.`);
const intent = await this.bridge.getIntent();
const options = this.config.channel.deleteOptions;
const plumbed = entry.remote.get("plumbed");
this.roomStore.upsertEntry(entry);
if (options.ghostsLeave) {
for (const member of channel.members.array()) {
try {
const mIntent = await this.bot.GetIntentFromDiscordMember(member);
mIntent.leave(roomId);
log.info(`${member.id} left ${roomId}.`);
} catch (e) {
log.warn(`Failed to make ${member.id} leave `);
}
}
}
if (options.namePrefix) {
try {
const name = await intent.getClient().getStateEvent(roomId, "m.room.name");
name.name = options.namePrefix + name.name;
await intent.getClient().setRoomName(roomId, name.name);
} catch (e) {
log.error(`Failed to set name of room ${roomId} ${e}`);
}
}
if (options.topicPrefix) {
try {
const topic = await intent.getClient().getStateEvent(roomId, "m.room.topic");
topic.topic = options.topicPrefix + topic.topic;
await intent.getClient().setRoomTopic(roomId, topic.topic);
} catch (e) {
log.error(`Failed to set topic of room ${roomId} ${e}`);
}
}
if (plumbed !== true) {
if (options.unsetRoomAlias) {
try {
const alias = `#_${entry.remote.roomId}:${this.config.bridge.domain}`;
const canonicalAlias = await intent.getClient().getStateEvent(roomId, "m.room.canonical_alias");
if (canonicalAlias.alias === alias) {
await intent.getClient().sendStateEvent(roomId, "m.room.canonical_alias", {});
}
await intent.getClient().deleteAlias(alias);
} catch (e) {
log.error(`Couldn't remove alias of ${roomId} ${e}`);
}
}
if (options.unlistFromDirectory) {
try {
await intent.getClient().setRoomDirectoryVisibility(roomId, "private");
} catch (e) {
log.error(`Couldn't remove ${roomId} from room directory ${e}`);
}
}
if (options.setInviteOnly) {
try {
await intent.getClient().sendStateEvent(roomId, "m.room.join_rules", {join_role: "invite"});
} catch (e) {
log.error(`Couldn't set ${roomId} to private ${e}`);
}
}
if (options.disableMessaging) {
try {
const state = await intent.getClient().getStateEvent(roomId, "m.room.power_levels");
state.events_default = POWER_LEVEL_MESSAGE_TALK;
await intent.getClient().sendStateEvent(roomId, "m.room.power_levels", state);
} catch (e) {
log.error(`Couldn't disable messaging for ${roomId} ${e}`);
}
}
}
// Unlist
// Remove entry
await this.roomStore.removeEntriesByMatrixRoomId(roomId);
}