bridgecord/WatchedGuild.js

81 lines
2 KiB
JavaScript
Raw Normal View History

const { EventEmitter } = require("events");
class WatchedGuild extends EventEmitter {
constructor() {
super();
this.knownWebhooks = new Map();
this.eventStack = [];
this.upstreamGuildId = null;
}
pushEvent(e) {
this.eventStack.push(e);
this.emit("pushed", e);
}
consumeEvent() {
return this.eventStack.pop();
}
consumeAll() {
const events = [...this.eventStack];
this.eventStack = [];
return events;
}
hasEvents() {
return this.eventStack.length > 0;
}
_pushMessageEvent(message) {
this.pushEvent({
eventType: "messageCreate",
message: message.toJSON()
});
}
discordConnect(bot) {
this.bot = bot;
this.bot.on("messageCreate", (message) => {
if (message.guildId !== this.upstreamGuildId)
return;
this._pushMessageEvent(message);
});
}
async discordSendMessage(messageContent, channelId, username, avatarURL=undefined) {
if (!this.bot)
throw new Error("Bot not connected");
let webhook = this.knownWebhooks.get(channelId);
if (!webhook) {
webhook = (await this.bot.getChannelWebhooks(channelId))
.filter(w => w.name == "well_known__bridge")[0];
if (!webhook)
webhook = await this.bot.createChannelWebhook(channelId, {
name: "well_known__bridge"
}, "This webhook was created by the bridge API bot.");
this.knownWebhooks.set(channelId, webhook);
}
await this.bot.executeWebhook(webhook.id, webhook.token, {
allowedMentions: {
everyone: false,
roles: false,
users: true
},
content: messageContent,
tts: false,
wait: true,
avatarURL,
username
});
}
}
module.exports = WatchedGuild;