-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (57 loc) · 1.78 KB
/
index.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
55
56
57
58
59
60
61
62
63
64
65
66
67
require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const axios = require("axios");
const redis = require("redis");
const http = require("http");
const socketIo = require("socket.io");
const redisClient = redis.createClient();
const connectDB = require("./config/db");
const Chat = require("./models/Chat");
const { TELEGRAM_API, URI, WEBHOOK_URL } = require("./constants");
app.set("view engine", "ejs");
connectDB();
const server = http.createServer(app);
const io = socketIo(server);
app.use(bodyParser.json());
const init = async () => {
const res = await axios.get(`${TELEGRAM_API}/setWebhook?url=${WEBHOOK_URL}`);
console.log(res.data);
};
// Send all previous messages to the client on connection
io.on("connection", async (socket) => {
const chats = await Chat.find();
socket.emit("messageList", chats);
});
app.post(URI, async (req, res) => {
console.log(req.body);
const message = req.body.message.text;
const firstName = req.body.message.from.first_name;
redisClient.on("connect", () => {
console.log("Redis client connected");
redisClient.lPush("chats", message, (error, result) => {
if (error) {
console.log(error);
} else {
console.log(`Message: ${message} added to queue. Result: ${result}`);
}
});
});
const chat = new Chat({
chat: message,
name: firstName,
});
await chat.save();
io.emit("message", { name: firstName, chat: message });
res.send("Message added to queue.");
});
const PORT = process.env.PORT || 5000;
app.get("/", async (req, res) => {
const chats = await Chat.find();
res.render("index", { chats });
});
server.listen(PORT, async () => {
console.log(`Server is running on port ${PORT}.`);
await init();
});