Skip to content

Instantly share code, notes, and snippets.

@luggage66
Forked from rlemon/canned.js
Created April 20, 2018 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luggage66/68e6be12c307e8d88b303b9e8b35dcc4 to your computer and use it in GitHub Desktop.
Save luggage66/68e6be12c307e8d88b303b9e8b35dcc4 to your computer and use it in GitHub Desktop.
const KEYWORD_MAP = {};
/*
KEYWORD_MAP[<user_id>][<term>] returns the reply
*/
KEYWORD_MAP[774078] = {
'jesus': 'http://i.imgur.com/V1kcfEU.jpg'
};
KEYWORD_MAP[617762] = {
'BAM!' : 'SPACE GUN!'
};
function keywordParser(node) {
if( !node.classList.contains('message') || node.classList.contains('pending') ) {
return;
}
const sig = node.parentNode.parentNode.querySelector('a.signature');
if( !sig ) {
return;
}
const [,,userId] = sig.getAttribute('href').split('/');
if( !(Number(userId) in KEYWORD_MAP) ) {
return;
}
const text = node.textContent;
// right now we only trigger on the first found word.
const matchedKey = Object.keys(KEYWORD_MAP[userId]).find(key => text.includes(key));
if( !matchedKey ) {
return;
}
const reply = KEYWORD_MAP[userId][matchedKey];
const [,messageId] = node.id.split('-');
sendMessage(messageId, reply);
}
function sendMessage(messageId, reply) {
const [roomid] = /\d+/.exec(location);
fetch(`https://chat.stackoverflow.com/chats/${roomid}/messages/new`, {
credentials: 'same-origin',
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
body: `fkey=${fkey().fkey}&text=:${messageId} ${reply}`
}).catch( error => {
console.log(error);
setTimeout(() => {
sendMessage(messageId, reply);
}, 1000);
});
}
DOMObserver.addParser(keywordParser, '.user-container .message');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment