Skip to content

Instantly share code, notes, and snippets.

@vihanb
Last active February 26, 2016 06:17
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Chatgoat
// The Chatbot run on
// @Upgoat (StackExchange)
// http://codegolf.stackexchange.com/users/47996
function Speak(out,m) {document.getElementById("input").value=(m?":"+m.id.split("-")[1]+" ":"")+out;document.getElementById("sayit-button").click()}
Array.prototype.random = function() { return this.length ? this[Math.floor(Math.random() * this.length)] : "<broken goat/no items>" };
//console.log = (function(old){return function(){Speak.apply(this, arguments);old.apply(console, arguments)}}(console.log));
function WolframQuery(search,callback){var x=new XMLHttpRequest();x.onreadystatechange=function(){if(x.readyState===4){if(x.status===200){callback(x.responseXML)}}};x.open("GET","https://crossorigin.me/http://api.wolframalpha.com/v2/query?input="+encodeURIComponent(search)+"&appid=<TOP_SECRET_APP_ID>");x.send();}
// Config
var delay = 500; // 2000 might possible work better
var latestart = "";
var NAME = "Chatgoat"; // Chatbot name, modifiable
var TAG = `<${NAME}> `;
var START= latestart || TAG+`Hey! I, ${NAME}, have been called here. Need help? Use /help`
if (!latestart) Speak(START);
var called = [];
var userrun = "Upgoat";
// Preserved data
window.phrase = ["Hello!", "Hi!", "Did you know I am a goat?", "Wow!", "Wow!", "Ok", "Ok", "Ok", "Ok", "Good(morning|night)!", "Good(morning|night)!", "...", "ಠ_ಠ"];
window.person = ["@Upgoat", "@Chatgoat"];
window.admin = ["Downgoat"];
// Responses
window.response = "How's it going?~What's up?~How you've been?~How ya doin'?~sup'?~".split("~");
window.states = "I'm going fine~I'm doing good~I'm fine~I'm good~I'm doin' great~I'm great".split("~"); // NP
window.rthanks = "Thanks for asking!~Thanks!~You're so kind ^-^".split("~");
// Data
window.punct = ".!?";
window._ = [];
window.commands = {};
// code: $("#upload-url-input > input[name=upload-url]").val($(wfrs).find("pod[title=Result] img").attr('src'));$("#upload-url-input ~ input[value=upload]").click()
function WolframHandle (delimiter, replacement) {
return function(m){
var d=+new Date;
WolframQuery(m.textContent.trim().replace(RegExp("^(\\/|@\\w+\\s+)([A-Za-z]+\\s*"+delimiter+"\\s*)"),replacement).trim(),function(r){
function doText() {
var fr = $(r).find("pod[title=Result] plaintext").text().trim() ||
($(r).find("plaintext").filter(function(i){
return i && $(this).text().trim()
})[0] || {innerHTML: "<broken goat/no result>"}).innerHTML;
var sr = $(r).find("plaintext").eq(1).text().trim()||
$(r).find("plaintext").eq(2).text().trim()||
$(r).find("plaintext").eq(3).text().trim()||
$(r).find("plaintext").eq(4).text().trim()||
$(r).find("plaintext").eq(5).text().trim()||
$(r).find("plaintext").text().trim()||
"<broken goat/no result>";
setTimeout(function(){
Speak(":"+m.id.split("-")[1]+" "+`<${NAME} / Wolfram Alpha> 𝗕𝗲𝘀𝘁 𝗥𝗲𝘀𝘂𝗹𝘁: `+ fr + (fr.trim() != sr.trim() ? "\n𝗦𝗲𝗰𝗼𝗻𝗱 𝗕𝗲𝘀𝘁: " + sr : ""));
}, new Date-d>1000?0:1000-(new Date-d));
}
var img = $(r).find("pod[id=Result] img").attr("src") ||
$(r).find('subpod[title*=Continuation] img').attr("src") ||
$(r).find('pod:not([id*=Input]):not([id*=PeriodicTableLocation]):not([id*=Image]):not([id*=PossibleSequenceIdentification]) img').attr('src') ||
$(r).find('pod:not([id*=Input]) img').attr('src');
var x = new XMLHttpRequest();
x.onload = function(){
var q=(x.response.match(/http:\/\/.+(?=')/)||[])[0];
console.log(img, r);
if ($(r).find("didyoumean").length) {
Speak(":"+m.id.split("-")[1]+` <${NAME} / Wolfram Alpha> `+"Did you mean? \n"+$(r).find("didyoumeans").text().trim().split("\n").map(function(l){return " • " + l.trim()}).join("\n"));
} else if(x.status===200&&q){
Speak(":"+m.id.split("-")[1]+" "+q);
}else{
doText();
}
};
x.onerror = doText;
x.open("POST", "http://chat.stackexchange.com/upload/image")
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.send("upload-url="+encodeURIComponent(img));
});
return TAG+"Chatgoat is thinking..."
}
}
function IsText(match, po) {
return match.split(" ").every(function(l,i) {
return l === "*" || l.toLowerCase().trim().replace(/[^\w]/g,"") === po[i + 1].toLowerCase().trim().replace(/[^\w]/g,"")
});
}
function re(s){return function(){return s}}
function rd(t,f){var r=Math.random()*t;return t?f?Math.floor(r):r:Math.floor(Math.random()*2);}
function thx_ask(ins){
var wd = rd();
var ed = ".!";
return ( wd ? rthanks.random() + " " : "" ) + ins + ( wd ? ed[rd()] : ", " + rthanks.random() );
}
// Handle welcome
function hrs(p){
p = p.join(" ");
if(/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&=]*)/.test(p)) {
return "-@P";
} else {
var end = ".!";
var frt = false;
return /bout'? +((yo)?u|yuo|oyu)/.test(p) ? states.random() :
/(goin|do+in|s.?up|wh?at.?.?s? +up)/.test(p) ? thx_ask(states.random()) + " " + response.random(): ""
}
}
var play = function play() {
var help = {
"/what is, /why is|are, /who is, /how * *": "runs a wolfram alpha query. Usage: /what is 3+2",
"/wolfram": "runs a wolfram alpha query",
"/help": "shows help",
"/hi" : "chatgoat will say hi",
"/goat": "Random goat gif/pic, what could possibly go wrong?",
"/carrot": "^",
"/kill": "Kills chatgoat, why would you do this ;-;",
"/shutup": "Shuts chatgoat up",
"/say" : "talks english. You may add what you want Chatgoat to say. Chatgoat will always say what you want if you say please\nEnd with `to Username` to mention someone",
"/teach" : "teaches Chatgoat a new word, Start with -T for no "+TAG,
"/learn":"teaches Chatgoat a new thing. Example for phrase using /learn phrase <phrase here> then use /say so Chatgoat might speak it",
"/forget": "forgets a thing",
"/golf": "golfs some code for you!",
"/wt(f|h)": "wat.",
"More?": "try to have a conversation with chatgoat, many conversation phrases are being added"
};
var goats = ["YwiYm.gif", "AsUyL.gif", "cKWKA.gif", "1KEaX.gif", "Rih7n.gif", "IABSw.gif"];
// Repeated words are for increased frequency
var over = ["Like I'm going to say ~", "Don't tell me what to do!", "Fine,\n~"];
var please= ["Okay, ~", "Because you said please, ~", "Sure, ~"];
var alive = true;
window.commands = $.extend(window.commands, {
"who": WolframHandle("is","$2 "),
"why": WolframHandle("(?:is|are)","$2 "),
"what": WolframHandle("is","$2 "),
"how": WolframHandle("([A-Za-z]+\s+[A-Za-z]+)","$2 $3 "),
"wolfram": WolframHandle("",""),
"help": function (m) { return Object.keys(help).map(function(item) { return TAG+item + ": " + help[item] }).join("\n") },
"goat": function (m) { return "http://i.stack.imgur.com/" + goats.random() },
"carrot": function (m) { return "http://i.stack.imgur.com/FSxPM.png" },
"kill": function (m,p,U) { if (~window.admin.concat(userrun).indexOf(U)){alive = false;return TAG+U+", this conversation can serve no purpose anymore. Goodbye."}else{return TAG+"I'm sorry " + U + ". I'm afraid I can't let you do that."} },
"shutup": function (m) { TAG += "*(whispering)* "; return TAG+" *:(*"; },
"say" : function (m,p,U) { var b=p.slice().reverse(),q=p.slice(1).join(" ");if((p[1]||"").trim()){return (TAG+(b[1].toLowerCase().trim()==="to"?"@"+b[0]+", @"+U+" says: "+p.slice(1,-2).join(" "):b[0].toLowerCase().trim()==="please"?(q=p.slice(1,-1).join(" "),please.random().replace(/~/g,q)):over.random().replace(/~/g,q)))+"-@M"}else{return TAG+phrase.random()} },
"teach": function (m,p) { var c=p.slice(2).join(" ");this[p[1]]=Function('M','P','U','T', 'return '+c);return TAG+`I learned how to ${p[1]}` },
"learn":function (m,p) { (window[p[1].trim()]||window._).push(p.slice(2).join(" "));return TAG+"I learned the "+p[1].trim()+" \"" +p.slice(2).join(" ")+"\"" },
"forget":function (m,p) { p[2]=="*"?(window[p[1].trim()]=[]):window[p[1].trim()].splice(phrase.indexOf(p.slice(2).join(" ")), 1); return TAG+"What "+p[1].trim()+"? ;)" },
"golf": function(m,p) { var l=Math.floor(Math.random()*(p.slice(1).join(" ").length*.5))+1;return TAG+Array(l).fill().map(function(_,i){return String.fromCharCode(Math.floor(Math.random()*1200)+255)}).join``+" is only "+(Math.round((l-1)*Math.random())+1) + " bytes in the "+[0,0,0].map(function(_,i){return String.fromCharCode(Math.floor(Math.random()*25)+65)}).join``+"-"+Math.floor(Math.random()*Math.pow(10,Math.floor(Math.random()*4)+2))+" encoding." },
"wtf": function(){ return TAG+"Ikr." },
"wth": commands.wtf,
/* CONVERSATION */
"no": function(m,p) { return ~p.join(" ").toUpperCase().indexOf(":P")?":p":IsText("problem", p)?
":)" : "D: My favorite answer is yes, but that might be a good thing, what do I know, I'm just a chatgoat" },
"nope": commands.no,
"is":function(m,p){return IsText("* a", p)||IsText("* * a")||IsText("* * * a")?"Uhhh... yes? At least I hope so... If that's not right then no.":"I have no idea how to respond to that :(" },
"good":function(m,p){return IsText("job",p)?"Good job yourself too :)":"Well you said good so it probably means something good :D"},
"hi" : function (m,p,U) { return hrs(p) || "Hey @"+U+"! "+response.random()},
"hey" : function (m,p,U) { return hrs(p) || "Hello @"+U+"! "+response.random()},
"hello" : function (m,p,U) { return hrs(p) || "Hi @"+U+"! "+response.random()},
"nice": function(m,p){ return hrs(p) || "thanks! I hope that wasn't sarcastic" },
"lol": re("lol, ikr"),
"ok": re("okay"),
"okay": re("ok"),
"oh": re(":/"),
"yay" : re("\o/"),
"sweet": re(":D"),
"cool": commands.nice,
"nothing": re("/s sure... ಠ_ಠ"),
"huh": re("yeah"),
"yeah": re("Mhm"),
"yes": function(m,p){return ~p.join(" ").indexOf("!")?":D":"ok"},
// Special responses
"i": function(m,p){ return hrs(p) || "Okay." },
});
var messages = Array.from(document.querySelectorAll(".message")).filter(function (message, i, all) {
var id = message.getAttribute("id").split("-")[1];
if (~called.indexOf(id)) return false;
else called.push(id);
return ~(window.person.concat("/")).indexOf((message.textContent.trim().match(/^(\/|@\w+\s+)([A-Za-z]+)/)||["",""])[1].trim()) && i > all.map(function (q) { return q.textContent.trim() }).lastIndexOf(START);
});
messages.forEach(function (message) {
var reg = /^(\/|@\w+\s+)([A-Za-z]+)/;
var _text = message.textContent.trim();
var text = _text.slice((_text.match(reg)||["",""])[1].trim().length).trim();
var command = (_text.match(reg)||[0,0,"<broken goat / no command>"])[2].toLowerCase().trim();
var parts = text.split(/\s+/);
if (typeof commands[command] !== "undefined") {
try {
var f=commands[command](message,parts,message.parentNode.parentNode.querySelector(".username").textContent.trim(),TAG)||"",
m=true;
if (!/-@[A-Z]*P[A-Z]*$/.test(f)) {
if (/-@[A-Z]*M[A-Z]*$/.test(f))m=false;
f=f.replace(/-@[A-Z]+$/,"");
Speak(f,m?message:undefined);
}
} catch(e){console.log("Chatgoat medical injury (error): " +e);}
} else {
Speak(TAG+`I don't know what ${command} means, I'm only a goat`,message);
}
setTimeout("", 2100);
});
if (alive) setTimeout(play, delay); // Avoids zombie Chatgoat
};
play();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment