Skip to content

Complete the merged labhours bot including graph and text interface #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions controllers/eventController.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,16 @@ const EventBotToken = process.env.EVENT_MANAGER_BOT_TOKEN;
export const handleAppMention = async (event) => {
const { text, channel, user, ts } = event;

const event_time = parseEventTime(text);
console.log('Event time:', event_time);
const emoji = parseEmoji(text);
try{
const event_time = parseEventTime(text);
console.log('Event time:', event_time);
const emoji = parseEmoji(text);

}
catch(error){
console.log(' Message is not meant for event');
return;
}

if (!event_time) {
console.log(' Message does not contain valid event time');
Expand Down
34 changes: 34 additions & 0 deletions controllers/graphsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {MyChart, TagChart} from '../services/graphs.js'


export const myGraph = async (req, res) => {
const myName = req.params.slackname;
const timeframe = req.params.timeframe;

let graph = await MyChart(myName, timeframe);

if (graph == null){
res.status(400).json({ error: 'Bad arguments' });
return;
}
res.type('image/png');
res.send(graph);

}


export const graphByTag = async (req, res) => {
const tag = req.params.tag;
const timeframe = req.params.timeframe;

let graph = await TagChart(tag, timeframe);

if (graph == null){
res.status(400).json({ error: 'Bad arguments' });
return;
}
res.type('image/png');
res.send(graph);

}

240 changes: 240 additions & 0 deletions controllers/labBot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
import express from 'express';
import axios from 'axios';
import dotenv from 'dotenv';
import { WebClient } from '@slack/web-api';
import { MyChart, TagChart, MyData, TagData } from '../services/graphs.js';

dotenv.config();
const slackClient = new WebClient(process.env.LAB_BOT_TOKEN);
const BotToken = process.env.LAB_BOT_TOKEN;

const LABOPENCLOSE_CHANNEL_ID = process.env.SLACK_CHANNEL_ID;

const messageOpen = "Bro lab is open";
const messageClose = "Bro lab is closed";
let currentBroStatus = true;

function reverseBroStatus() {
currentBroStatus = !currentBroStatus
return currentBroStatus ? messageOpen : messageClose
}

async function sendMessage(channelId, text) {
try {
await slackClient.chat.postMessage({
channel: channelId,
text: text,
});
} catch (error) {
console.error('Error posting message:', error);
}
}


async function uploadImage(channelId, imageBuffer) {
console.log(channelId)
try {
await slackClient.files.uploadV2({
file: imageBuffer,
filename: 'graph.png',
title: 'Labtime graph',
alt_text: 'Labtime graph',
channel_id: channelId,
});

return 1;
} catch (error) {
console.log(error)
return 0;
}
}


export const handleAppMention = async (event) => {
const { text, channel, user, ts } = event;

console.log(text);
console.log(channel);
console.log(user);
console.log(ts);


let msg_start = text.indexOf('>');
if (msg_start == -1) {
return;
}

let msg_text = text.substring(msg_start + 1).trim();

if (msg_text.toLowerCase() === "help") {
sendMessage(channel, `Commands:
@LabHours bot labtime <@user or @tag> <daily/weekly/monthly/alltime> -> Gives a graph of lab time
@LabHours bot help -> Displays this help menu`);
return;
}

else if (msg_text.toLowerCase() === "hi" || msg_text.toLowerCase() === "hello") {
sendMessage(channel, `Hi <@${user}>`);
return;
}

else if (msg_text.split(" ")[0] === "labtime") {

if (msg_text.split(" ")[1] === "graph") {

let split_text = msg_text.split(" ");
if (split_text[2].startsWith("<@")) {
let uid = split_text[2].substring(2, split_text[2].length - 1);
const result = await slackClient.users.info({ user: uid });

const slackname = result.user.profile.display_name;

if (!(["daily", "weekly", "monthly", "alltime"].includes(split_text[3].toLowerCase()))) {
sendMessage(channel, "Tell me a reasonable timeframe");
return;
}

let graph_buffer = await MyChart(slackname, split_text[3].toLowerCase());

if (graph_buffer == null) {
sendMessage(channel, "[ -_- ] something went wrong");
return;
}
if (!uploadImage(channel, graph_buffer)) {
sendMessage(channel, "[ -_- ] failed to upload image");
return;

}



}
else if (split_text[2].startsWith("@")) {
let tag = split_text[2].substring(1);

if (!(["daily", "weekly", "monthly", "alltime"].includes(split_text[3].toLowerCase()))) {
sendMessage(channel, "Tell me a reasonable timeframe");
return;
}

let graph_buffer = await TagChart(tag, split_text[3].toLowerCase());
if (graph_buffer == null) {
sendMessage(channel, "[ -_- ] something went wrong");
return;
}
if (!uploadImage(channel, graph_buffer)) {
sendMessage(channel, "[ -_- ] failed to upload image");
return;

}

}
}

if (msg_text.split(" ")[1] === "text"){
let split_text = msg_text.split(" ");
if (split_text[2].startsWith("<@")) {
let uid = split_text[2].substring(2, split_text[2].length - 1);
const result = await slackClient.users.info({ user: uid });

const slackname = result.user.profile.display_name;

if (!(["daily", "weekly", "monthly", "alltime"].includes(split_text[3].toLowerCase()))) {
sendMessage(channel, "Tell me a reasonable timeframe");
return;
}


let data_buffer = await MyData(slackname, split_text[3].toLowerCase());

if (data_buffer == null) {
sendMessage(channel, "[ -_- ] something went wrong");
return;
}
else{
sendMessage(channel, data_buffer)
}



}
else if (split_text[2].startsWith("@")) {
let tag = split_text[2].substring(1);

if (!(["daily", "weekly", "monthly", "alltime"].includes(split_text[3].toLowerCase()))) {
sendMessage(channel, "Tell me a reasonable timeframe");
return;
}

let data_buffer = await TagData(tag, split_text[3].toLowerCase());
if (data_buffer == null) {
sendMessage(channel, "[ -_- ] something went wrong");
return;
}
else{
sendMessage(channel, data_buffer)
return;

}

}

}



else {
sendMessage(channel, `Who is that?`);
return;
}
}
else {
sendMessage(channel, `kya bol rha hai bhai`);
return;
}


// @Bot "labtime" "@username or tag" "daily/weekly/monthly/alltime-"

};



export const printFromBro = async (req, res) => {
let message = reverseBroStatus();
console.log("Bro status changed to: " + message);
try {
const result = await postMessageToSlack(message);

return res.status(200).json({
success: true,
message: "Message posted to Slack successfully.",
slackResponse: result
});

} catch (error) {
console.error('Error posting message to Slack:', error);
return res.status(500).json({ error: 'Failed to post message to Slack' });
}
}


const postMessageToSlack = async (message) => {
let response = null;
try {
response = await axios.post(process.env.BASE_URL, {
"channel": LABOPENCLOSE_CHANNEL_ID,
"text": message,
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${SLACK_TOKEN}`,
},
});
} catch (error) {
console.error('Error posting message to Slack:', error);
}

return response.data;
}

5 changes: 2 additions & 3 deletions controllers/labHours.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { response } from 'express';
import pool from '../config/db.js'

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

try {
const initial = await pool.query(
'SELECT * FROM activeUsers WHERE (enroll_num)=($1)', [enroll_num]
'SELECT * FROM members_info WHERE (enrollment_num)=($1)', [enroll_num]
);

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


const response = await pool.query(
'UPDATE activeUsers SET labdata=($1) WHERE enroll_num = ($2)', [labData, enroll_num]
'UPDATE members_info SET labdata=($1) WHERE enrollment_num = ($2)', [labData, enroll_num]
);


Expand Down
26 changes: 15 additions & 11 deletions controllers/maintenance.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ import pool from '../config/db.js'


export async function doMaintenance(){
const initial = await pool.query(
'SELECT * FROM activeUsers'
const initial = await pool.query(
'SELECT * FROM members_info'
);




let date = new Date();

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

for (let i = 0; i < initial.rows.length; i++) {
const row = initial.rows[i];
const enrollNo = row['enroll_num'];
const enrollNo = row['enrollment_num'];
let labData = row['labdata'];

if (labData == null) {
labData = { 'logs': [], 'isInLab': false, 'labTime': 0, 'dayWise': {} };
}
console.log('pritimg labdaat')
console.log(labData)

if (!(datestr in labData.dayWise)) {
labData.dayWise[datestr] = 0;
}

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

await pool.query('TRUNCATE TABLE activeUsers');
await pool.query(
`UPDATE members_info
SET labdata = $1
WHERE enrollment_num = $2`,
[labData, enrollNo]
);

const query = `INSERT INTO activeUsers (enroll_num, labdata) VALUES ${placeholders.join(', ')}`;
await pool.query(query, values);


}

}


export const setupLogs = async(req, res) =>{
try{

Expand Down
Loading