Skip to content

Instantly share code, notes, and snippets.

@tnlin
Forked from DingWeizhe/寶寶.js
Created April 29, 2016 08:24
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 tnlin/c56fce892d7ec5deb02f5a68df7f218e to your computer and use it in GitHub Desktop.
Save tnlin/c56fce892d7ec5deb02f5a68df7f218e to your computer and use it in GitHub Desktop.
var fs = require('fs'),
http = require('http'),
https = require('https'),
express = require('express'),
token = '',
bodyParser = require('body-parser'),
request = require('request');
var port = 443;
var options = {
ca: fs.readFileSync('ssl.crt/1_root_bundle.crt'),
key: fs.readFileSync('ssl.key/2_chat.ntut.cc.key'),
cert: fs.readFileSync('ssl.crt/2_chat.ntut.cc.crt')
};
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({
extended: true
}));
var server = https.createServer(options, app).listen(port, function() {
console.log("Express server listening on port " + port);
});
function sendTextMessage(sender, text) {
var messageData = {
text: text
};
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: token
},
method: 'POST',
json: {
recipient: {
id: sender
},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
app.use('/', express.static('public'));
app.get('/webhook', function(req, res) {
if (req.query['hub.verify_token'] === token) {
res.send(req.query['hub.challenge']);
} else {
res.send('Error, wrong validation token');
}
});
app.post('/', function(req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
var text = "";
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, boubou(text));
}
}
res.sendStatus(200);
});
function boubou(text) {
match = text.match(/寶寶[還你妳]?(知道|喜歡|討厭|愛吃)(.*)嗎[\??]?/i);
if (match) {
var verb = match[1]
var word = match[2]
return "寶寶" + verb + word + ",只是寶寶不說";
}
match = text.match(/寶寶[還你妳]好嗎[\??]?/i);
if (match) {
return "寶寶心裡苦,只是寶寶不說";
}
match = text.match(/.*[好太真很]?(可怕|恐怖|詭異|奇怪)啊?.*/i);
if (match) {
return "嚇死寶寶了";
}
return "寶寶聽不懂";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment