Skip to content

Instantly share code, notes, and snippets.

@semateos
Created September 28, 2016 13:49
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 semateos/268fe38f699bc94aad03e0e82df3d60d to your computer and use it in GitHub Desktop.
Save semateos/268fe38f699bc94aad03e0e82df3d60d to your computer and use it in GitHub Desktop.
SuperScript startup with clean facts db
// This is the main Bot interface
var Promise = require('bluebird'),
superscript = require("superscript"),
mongoose = require("mongoose"),
fs = require("fs"),
facts = require("sfacts"),
rmdir = Promise.promisify( require('rimraf') ),
program = require('commander'),
parse = require("ss-parser")(),
util = require('util');
var config = require('./opsworks.js');
//mongoose.connect('mongodb://localhost/superscriptDB');
//websocket client to interact with Altered
var alteredClient = require('altered-api-client')(config);
var facts = require("sfacts");
//var factSystem = facts.explore("botfacts");
//var TopicSystem = require("superscript/lib/topics/index")(mongoose, factSystem);
// How should we reply to the user?
// direct - sents a DM
// atReply - sents a channel message with @username
// public sends a channel reply with no username
var replyType = "atReply";
var atReplyRE = /@\[(.*?)\]/;
//var slack = new Slack(token, true, true);
var botHandle = function(err, bot) {
alteredClient.login(function(err, data){
console.log('logged in to altered', alteredClient.user);
});
alteredClient.events.on('error', function(error) {
console.error("Error:");
console.log(error);
});
alteredClient.events.on('open', function(){
//console.log("Welcome to Slack. You are %s of %s", slack.self.name, slack.team.name);
});
alteredClient.events.on('close', function() {
console.warn("Disconnected");
});
alteredClient.events.on('new-notification', function(data) {
receiveData(alteredClient, bot, data);
});
};
var respond = function(client, bot, interaction){
var user = interaction.owner;
var room = interaction.room;
var message = interaction.body;
var match = message.match(atReplyRE);
message = message.replace(atReplyRE, '').trim();
if (message[0] == ':') {
message = message.substring(1).trim();
}
bot.reply(user, message, function(err, reply){
if(err){
console.log('reply error', err);
}
if (reply.string) {
var args = {
data: {body: reply.string, type: "say"}
};
if(reply.string[0] == '/'){
args = {
data: {body: reply.string.substring(1), type: "act"}
};
}
client.addInteraction(args, function(response){
console.log('sent interaction', response);
});
console.log('reply:', reply.string);
//channel.send(reply.string);
}else{
console.log('no reply', reply);
}
});
}
var receiveData = function(client, bot, data) {
try{
var interaction = data.info.interact;
console.log('incoming message:', interaction);
client.lastInteraction = interaction;
//temp hack - switch room to the originating room
if(client.user.currentAvatar.currentRoom != interaction.room){
var args = {
data: {currentRoom: interaction.room}
};
alteredClient.updateAvatar(args, function(response){
client.user.currentAvatar.currentRoom = interaction.room;
console.log('switched room', response);
respond(client, bot, interaction);
});
}else{
respond(client, bot, interaction);
}
}catch(e){
console.log('reply fail', e);
}
};
///////////////////////////
// Superscript Refresher //
///////////////////////////
/*
var Promise = require('bluebird'),
facts = require("sfacts"),
rmdir = Promise.promisify( require('rimraf') ),
program = require('commander'),
superscript = require('../index'),
fs = require("fs"),
mongoose = require('mongoose'),
util = require('util');
*/
var collectionsToRemove = ['users', 'topics', 'replies', 'gambits'];
program
.version('0.0.2')
.option('--facts [type]', 'Fact Directory', './systemDB')
.option('--host [type]', 'Mongo Host', 'localhost')
.option('--port [type]', 'Mongo Port', '27017')
.option('--mongo [type]', 'Mongo Database Name', 'superscriptDB')
.option('--mongoURI [type]', 'Mongo URI')
.option('--topic [type]', 'Topic Directory', './topics')
.option('--skip-remove-all', 'Skip removal of: ' + collectionsToRemove.join(', '))
.option('--flush-topics', 'Flush imported topics, implies --skip-remove-all')
.option('--preserve-random', 'When used with --flush-topics, it will not empty the random topic')
.parse(process.argv);
function removeAll (db) {
/**
* @param {Object} MongoDB instance
* @return {Promise} Resolved after listed collections are removed and the fact system directory has been recursively cleared
*/
if (program.skipRemoveAll || program.flushTopics) return;
return Promise.map(collectionsToRemove, function(collName) {
var coll = db.collection(collName);
return coll
.removeAsync({})
.then(isClear.bind(collName));
})
.then(function() {
// Delete the old fact system directory
return rmdir(program.facts)
});
}
function isClear () {
console.log(this + ' is clear');
return true;
}
function createFresh () {
/**
* @return {Promise} Resolves after all data from the Topics folder has been loaded into Mongodb
*/
// Generate Shared Fact System
// If not pre-generated, superscript will throw error on initialization
var factSystem = facts.create(program.facts),
parser = require('ss-parser')(factSystem),
loadDirectory = Promise.promisify( parser.loadDirectory, parser );
var options = {};
options['factSystem'] = factSystem;
options['mongoose'] = mongoose;
options['scope'] = {
client: alteredClient
}
function importAll (data) {
/**
* @param {Object} Parsed data from a .ss file
* @return {Promise} Resolved when import is complete
*/
// console.log('Importing', data);
return new Promise(function(resolve, reject) {
mongoose.connect(mongoURL)
new superscript(options, function(err, bot) {
if (!err) {
bot.topicSystem.importerData(data, resolve, program.flushTopics, program.preserveRandom);
botHandle(null, bot);
}else{
reject(err);
}
});
});
}
return loadDirectory(program.topic)
.then(importAll);
}
// Setup Mongo Client: accepts MONGO_URI from environment, and URI or components or defaults as provided in options.
var MongoClient = Promise.promisifyAll( require('mongodb') ).MongoClient,
mongoURL = process.env.MONGO_URI || program.mongoURI || util.format('mongodb://%s:%s/%s', program.host, program.port, program.mongo);
function startup () {
// DO ALL THE THINGS
MongoClient.connectAsync(mongoURL)
.then(removeAll)
.then(createFresh)
.catch(function(e) {
console.log(e);
})
.then(function(data) {
console.log('Everything imported');
return 0;
}, function(e) {
console.log('Import error', e);
});
//.then(process.exit);
}
// watch topics for changes
require('chokidar').watch('./topics', {ignored: /[\/\\]\./}).on('all', function(event, path) {
console.log(event, path);
switch (event) {
case 'change':
//startup();
process.exit();
break;
}
});
/*
server.superscript = new superscript(options, function(err, botInstance){
botHandle(null, botInstance);
});
*/
startup();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment