-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
105 lines (87 loc) · 3.42 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Declaring variables and destructuring to get important values
const express = require('express');
const TelegramBot = require('node-telegram-bot-api')
const { getEmailBody } = require('./functions')
const { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
const { port, myChatId, telegramBotToken, oa_clientId, oa_clientSecret, oa_redirectUri, oa_accessType, refreshtime } = require('dotenv').config().parsed
// Declaring instances for express, telegram_bot and oauth2
const app = express();
const bot = new TelegramBot(telegramBotToken, { polling: true });
const oauth2Client = new OAuth2Client({
clientId: oa_clientId,
clientSecret: oa_clientSecret,
redirectUri: oa_redirectUri,
});
// Create a URL for user consent
const consentUrl = oauth2Client.generateAuthUrl({
access_type: oa_accessType,
scope: ['https://www.googleapis.com/auth/gmail.readonly'],
});
// Redirect the user to the Google OAuth consent page
app.get('/auth', (req, res) => {
res.redirect(consentUrl);
});
// Handle the callback with the authorization code
app.get('/callback', async (req, res) => {
const code = req.query.code;
try {
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
res.send('Authentication successful. You can now monitor your Gmail account.');
console.log("Authentication Successful")
} catch (error) {
console.error('Authentication error:', error);
res.status(500).send('Authentication error. Check the console for details.');
}
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
// Set up the Gmail API
const gmail = google.gmail({
version: 'v1',
auth: oauth2Client,
});
// Function to check for new emails
async function checkForNewEmails() {
try {
const response = await gmail.users.messages.list({
userId: 'me',
q: 'is:unread', // Modify the query as needed
});
const messages = response.data.messages;
if (messages && messages.length > 0) {
// Perform your desired actions for new emails
for (const message of messages) {
const messageId = message.id;
const email = await gmail.users.messages.get({
userId: 'me',
id: messageId,
format: 'full', // Get the full email content
});
// Send a message
bot.sendMessage(myChatId, `New Mail \nSubject | ${email.data.subject || "No Subject"}\nBody | ${getEmailBody(email.data)}`)
.then(() => {
console.log('Message sent successfully.');
})
.catch((error) => {
console.error('Error sending message:', error);
});
}
} else {
/* bot.sendMessage(myChatId, `No new mails`)
.then(() => {
console.log('Message sent successfully.');
})
.catch((error) => {
console.error('Error sending message:', error);
});
*/
console.log('No new emails.');
}
} catch (error) {
console.error('Error checking for new emails:', error);
}
}
setInterval(checkForNewEmails, refreshtime * 60 * 1000); // 5 minutes