Skip to content

Commit 5ac6f2b

Browse files
Merge pull request #8 from mdgspace/graphs
Complete the merged labhours bot including graph and text interface
2 parents 55fb1d0 + dc233a6 commit 5ac6f2b

File tree

13 files changed

+1506
-86
lines changed

13 files changed

+1506
-86
lines changed

controllers/eventController.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,16 @@ const EventBotToken = process.env.EVENT_MANAGER_BOT_TOKEN;
1515
export const handleAppMention = async (event) => {
1616
const { text, channel, user, ts } = event;
1717

18-
const event_time = parseEventTime(text);
19-
console.log('Event time:', event_time);
20-
const emoji = parseEmoji(text);
18+
try{
19+
const event_time = parseEventTime(text);
20+
console.log('Event time:', event_time);
21+
const emoji = parseEmoji(text);
22+
23+
}
24+
catch(error){
25+
console.log(' Message is not meant for event');
26+
return;
27+
}
2128

2229
if (!event_time) {
2330
console.log(' Message does not contain valid event time');

controllers/graphsController.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import {MyChart, TagChart} from '../services/graphs.js'
2+
3+
4+
export const myGraph = async (req, res) => {
5+
const myName = req.params.slackname;
6+
const timeframe = req.params.timeframe;
7+
8+
let graph = await MyChart(myName, timeframe);
9+
10+
if (graph == null){
11+
res.status(400).json({ error: 'Bad arguments' });
12+
return;
13+
}
14+
res.type('image/png');
15+
res.send(graph);
16+
17+
}
18+
19+
20+
export const graphByTag = async (req, res) => {
21+
const tag = req.params.tag;
22+
const timeframe = req.params.timeframe;
23+
24+
let graph = await TagChart(tag, timeframe);
25+
26+
if (graph == null){
27+
res.status(400).json({ error: 'Bad arguments' });
28+
return;
29+
}
30+
res.type('image/png');
31+
res.send(graph);
32+
33+
}
34+

controllers/labBot.js

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
import express from 'express';
2+
import axios from 'axios';
3+
import dotenv from 'dotenv';
4+
import { WebClient } from '@slack/web-api';
5+
import { MyChart, TagChart, MyData, TagData } from '../services/graphs.js';
6+
7+
dotenv.config();
8+
const slackClient = new WebClient(process.env.LAB_BOT_TOKEN);
9+
const BotToken = process.env.LAB_BOT_TOKEN;
10+
11+
const LABOPENCLOSE_CHANNEL_ID = process.env.SLACK_CHANNEL_ID;
12+
13+
const messageOpen = "Bro lab is open";
14+
const messageClose = "Bro lab is closed";
15+
let currentBroStatus = true;
16+
17+
function reverseBroStatus() {
18+
currentBroStatus = !currentBroStatus
19+
return currentBroStatus ? messageOpen : messageClose
20+
}
21+
22+
async function sendMessage(channelId, text) {
23+
try {
24+
await slackClient.chat.postMessage({
25+
channel: channelId,
26+
text: text,
27+
});
28+
} catch (error) {
29+
console.error('Error posting message:', error);
30+
}
31+
}
32+
33+
34+
async function uploadImage(channelId, imageBuffer) {
35+
console.log(channelId)
36+
try {
37+
await slackClient.files.uploadV2({
38+
file: imageBuffer,
39+
filename: 'graph.png',
40+
title: 'Labtime graph',
41+
alt_text: 'Labtime graph',
42+
channel_id: channelId,
43+
});
44+
45+
return 1;
46+
} catch (error) {
47+
console.log(error)
48+
return 0;
49+
}
50+
}
51+
52+
53+
export const handleAppMention = async (event) => {
54+
const { text, channel, user, ts } = event;
55+
56+
console.log(text);
57+
console.log(channel);
58+
console.log(user);
59+
console.log(ts);
60+
61+
62+
let msg_start = text.indexOf('>');
63+
if (msg_start == -1) {
64+
return;
65+
}
66+
67+
let msg_text = text.substring(msg_start + 1).trim();
68+
69+
if (msg_text.toLowerCase() === "help") {
70+
sendMessage(channel, `Commands:
71+
@LabHours bot labtime <@user or @tag> <daily/weekly/monthly/alltime> -> Gives a graph of lab time
72+
@LabHours bot help -> Displays this help menu`);
73+
return;
74+
}
75+
76+
else if (msg_text.toLowerCase() === "hi" || msg_text.toLowerCase() === "hello") {
77+
sendMessage(channel, `Hi <@${user}>`);
78+
return;
79+
}
80+
81+
else if (msg_text.split(" ")[0] === "labtime") {
82+
83+
if (msg_text.split(" ")[1] === "graph") {
84+
85+
let split_text = msg_text.split(" ");
86+
if (split_text[2].startsWith("<@")) {
87+
let uid = split_text[2].substring(2, split_text[2].length - 1);
88+
const result = await slackClient.users.info({ user: uid });
89+
90+
const slackname = result.user.profile.display_name;
91+
92+
if (!(["daily", "weekly", "monthly", "alltime"].includes(split_text[3].toLowerCase()))) {
93+
sendMessage(channel, "Tell me a reasonable timeframe");
94+
return;
95+
}
96+
97+
let graph_buffer = await MyChart(slackname, split_text[3].toLowerCase());
98+
99+
if (graph_buffer == null) {
100+
sendMessage(channel, "[ -_- ] something went wrong");
101+
return;
102+
}
103+
if (!uploadImage(channel, graph_buffer)) {
104+
sendMessage(channel, "[ -_- ] failed to upload image");
105+
return;
106+
107+
}
108+
109+
110+
111+
}
112+
else if (split_text[2].startsWith("@")) {
113+
let tag = split_text[2].substring(1);
114+
115+
if (!(["daily", "weekly", "monthly", "alltime"].includes(split_text[3].toLowerCase()))) {
116+
sendMessage(channel, "Tell me a reasonable timeframe");
117+
return;
118+
}
119+
120+
let graph_buffer = await TagChart(tag, split_text[3].toLowerCase());
121+
if (graph_buffer == null) {
122+
sendMessage(channel, "[ -_- ] something went wrong");
123+
return;
124+
}
125+
if (!uploadImage(channel, graph_buffer)) {
126+
sendMessage(channel, "[ -_- ] failed to upload image");
127+
return;
128+
129+
}
130+
131+
}
132+
}
133+
134+
if (msg_text.split(" ")[1] === "text"){
135+
let split_text = msg_text.split(" ");
136+
if (split_text[2].startsWith("<@")) {
137+
let uid = split_text[2].substring(2, split_text[2].length - 1);
138+
const result = await slackClient.users.info({ user: uid });
139+
140+
const slackname = result.user.profile.display_name;
141+
142+
if (!(["daily", "weekly", "monthly", "alltime"].includes(split_text[3].toLowerCase()))) {
143+
sendMessage(channel, "Tell me a reasonable timeframe");
144+
return;
145+
}
146+
147+
148+
let data_buffer = await MyData(slackname, split_text[3].toLowerCase());
149+
150+
if (data_buffer == null) {
151+
sendMessage(channel, "[ -_- ] something went wrong");
152+
return;
153+
}
154+
else{
155+
sendMessage(channel, data_buffer)
156+
}
157+
158+
159+
160+
}
161+
else if (split_text[2].startsWith("@")) {
162+
let tag = split_text[2].substring(1);
163+
164+
if (!(["daily", "weekly", "monthly", "alltime"].includes(split_text[3].toLowerCase()))) {
165+
sendMessage(channel, "Tell me a reasonable timeframe");
166+
return;
167+
}
168+
169+
let data_buffer = await TagData(tag, split_text[3].toLowerCase());
170+
if (data_buffer == null) {
171+
sendMessage(channel, "[ -_- ] something went wrong");
172+
return;
173+
}
174+
else{
175+
sendMessage(channel, data_buffer)
176+
return;
177+
178+
}
179+
180+
}
181+
182+
}
183+
184+
185+
186+
else {
187+
sendMessage(channel, `Who is that?`);
188+
return;
189+
}
190+
}
191+
else {
192+
sendMessage(channel, `kya bol rha hai bhai`);
193+
return;
194+
}
195+
196+
197+
// @Bot "labtime" "@username or tag" "daily/weekly/monthly/alltime-"
198+
199+
};
200+
201+
202+
203+
export const printFromBro = async (req, res) => {
204+
let message = reverseBroStatus();
205+
console.log("Bro status changed to: " + message);
206+
try {
207+
const result = await postMessageToSlack(message);
208+
209+
return res.status(200).json({
210+
success: true,
211+
message: "Message posted to Slack successfully.",
212+
slackResponse: result
213+
});
214+
215+
} catch (error) {
216+
console.error('Error posting message to Slack:', error);
217+
return res.status(500).json({ error: 'Failed to post message to Slack' });
218+
}
219+
}
220+
221+
222+
const postMessageToSlack = async (message) => {
223+
let response = null;
224+
try {
225+
response = await axios.post(process.env.BASE_URL, {
226+
"channel": LABOPENCLOSE_CHANNEL_ID,
227+
"text": message,
228+
}, {
229+
headers: {
230+
'Content-Type': 'application/json',
231+
'Authorization': `Bearer ${SLACK_TOKEN}`,
232+
},
233+
});
234+
} catch (error) {
235+
console.error('Error posting message to Slack:', error);
236+
}
237+
238+
return response.data;
239+
}
240+

controllers/labHours.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { response } from 'express';
21
import pool from '../config/db.js'
32

43
const SAC_CLOSING_HOUR = 2.0
@@ -11,7 +10,7 @@ export const toggleInOut = async (req, res) => {
1110

1211
try {
1312
const initial = await pool.query(
14-
'SELECT * FROM activeUsers WHERE (enroll_num)=($1)', [enroll_num]
13+
'SELECT * FROM members_info WHERE (enrollment_num)=($1)', [enroll_num]
1514
);
1615

1716
let initStatus = initial.rows[0];
@@ -161,7 +160,7 @@ export const toggleInOut = async (req, res) => {
161160

162161

163162
const response = await pool.query(
164-
'UPDATE activeUsers SET labdata=($1) WHERE enroll_num = ($2)', [labData, enroll_num]
163+
'UPDATE members_info SET labdata=($1) WHERE enrollment_num = ($2)', [labData, enroll_num]
165164
);
166165

167166

controllers/maintenance.js

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@ import pool from '../config/db.js'
22

33

44
export async function doMaintenance(){
5-
const initial = await pool.query(
6-
'SELECT * FROM activeUsers'
5+
const initial = await pool.query(
6+
'SELECT * FROM members_info'
77
);
88

9-
10-
9+
1110
let date = new Date();
1211

1312
const dd = String(date.getDate()).padStart(2, '0');
@@ -22,30 +21,35 @@ export async function doMaintenance(){
2221

2322
for (let i = 0; i < initial.rows.length; i++) {
2423
const row = initial.rows[i];
25-
const enrollNo = row['enroll_num'];
24+
const enrollNo = row['enrollment_num'];
2625
let labData = row['labdata'];
2726

2827
if (labData == null) {
2928
labData = { 'logs': [], 'isInLab': false, 'labTime': 0, 'dayWise': {} };
3029
}
31-
console.log('pritimg labdaat')
32-
console.log(labData)
30+
3331
if (!(datestr in labData.dayWise)) {
3432
labData.dayWise[datestr] = 0;
3533
}
3634

3735
values.push(enrollNo, JSON.stringify(labData));
3836
const idx = i * 2;
3937
placeholders.push(`($${idx + 1}, $${idx + 2})`);
40-
}
4138

42-
await pool.query('TRUNCATE TABLE activeUsers');
39+
await pool.query(
40+
`UPDATE members_info
41+
SET labdata = $1
42+
WHERE enrollment_num = $2`,
43+
[labData, enrollNo]
44+
);
4345

44-
const query = `INSERT INTO activeUsers (enroll_num, labdata) VALUES ${placeholders.join(', ')}`;
45-
await pool.query(query, values);
46+
47+
48+
}
4649

4750
}
4851

52+
4953
export const setupLogs = async(req, res) =>{
5054
try{
5155

0 commit comments

Comments
 (0)