forked from Meegul/GroupMeChatBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.js
54 lines (46 loc) · 1.88 KB
/
start.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
const port = process.env.PORT || 3000;
const botID = process.env.BOT_ID;
const url = "https://api.groupme.com/v3/bots/";
const groupID = process.env.GROUP_ID;
app.use(bodyParser.json());
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
app.post("/", (req, res) => {
postText = "";
const toSearchFor = "@giphy ";
const index = req.body.text.toLowerCase().indexOf(toSearchFor);
//If we found the string we're looking for get results and send them
if (index != -1) {
//Get the string we are searching for.
const toSearch = req.body.text.substring(index + toSearchFor.length);
//Get the total, encoded URL we're going to pass to Giphy to search
const giphyurl = `http://api.giphy.com/v1/gifs/search?limit=5&q=${encodeURIComponent(toSearch)}&api_key=dc6zaTOxFJmzC`;
request.get(giphyurl, (error, response, body) => {
const results = JSON.parse(body)["data"];
//Get up to the top five
const numTopResults = (results.length < 5) ? results.length : 5;
if (error || numTopResults === 0) {
sendMessage(botID, "Nothing found 😥");
} else {
const indexSelected = Math.floor(Math.random() * (numTopResults));
const selected = results[indexSelected].images.original.url;
console.log(`${toSearch}=>${selected}`);
sendMessage(botID, selected);
}
});
}
res.end();
});
function sendMessage(botID, text) {
const toSend = `${url}post?bot_id=${botID}&text=${encodeURIComponent(text)}`;
request.post(toSend, (error, response, body) => {
if (error) {
console.log(error);
}
});
}