Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const CollabChatAPI = (()=>{
- const version = 1;
- const onMessage = (()=>{
- const messageCallbacks = [];
- // chat omits a persons name if they send consecutive messages, so the
- // last person who sent a message is stored here so that every message
- // object has a "from".
- let lastFrom = null;
- const observer = new MutationObserver(mutations => {
- mutations.forEach(mutation => {
- if (mutation.type != "childList") return;
- mutation.addedNodes.forEach(node => {
- if (node.tagName != "LI") return;
- // extract information
- lastFrom = $(".participant-name", node).text() || lastFrom;
- const contents = $(".activity-body", node).text();
- // construct message
- const message = {
- from: lastFrom,
- contents,
- };
- // call callbacks
- messageCallbacks.forEach(callback => callback(message));
- });
- })
- });
- // changing breakout group, minimizing the chat, etc, causes a new chat
- // element to be created, meaning the observer is now observing the old
- // chat. This loop lazily rebinds the observer to the current chat
- // every second.
- setInterval(()=>{
- observer.disconnect();
- const chatRoot = $("#chat-channel-history");
- if (chatRoot.length == 0) return;
- observer.observe(chatRoot[0], { childList: true });
- }, 1000);
- function onMessage(callback) {
- messageCallbacks.push(callback);
- }
- return onMessage;
- })();
- function sendMessage(message) {
- const messageInput = $("#message-input");
- if (messageInput.length == 0) {
- console.warn("CollabChatAPI attempted to sendMessage but no chat was open!");
- return false;
- }
- const pressEnter = $.Event("keypress");
- pressEnter.which = 13;
- messageInput.val(message);
- messageInput.trigger("change");
- messageInput.trigger(pressEnter);
- return true;
- }
- return {
- version,
- onMessage,
- sendMessage,
- };
- })();
- /*
- // send a message from your account
- CollabChatAPI.sendMessage("hello!");
- // do something when a new message is received:
- CollabChatAPI.onMessage(msg => {
- // do something with msg
- });
- // msg in onMessage is the following object
- {
- from: "John Bobington",
- contents: "Hey there!"
- }
- // example !roll command
- CollabChatAPI.onMessage(msg => {
- if (msg.contents.toLowerCase() == "!roll") {
- const roll = ~~(Math.random()*100);
- CollabChatAPI.sendMessage(`[bot] you rolled ${roll}!`);
- }
- });
- // example logging all messages
- CollabChatAPI.onMessage(console.log);
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement