-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.js
204 lines (169 loc) · 6.24 KB
/
lib.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
const fs = require("fs").promises;
const path = require("path");
const process = require("process");
const { google } = require("googleapis");
const { chromium } = require("playwright");
const { Configuration, OpenAIApi } = require("openai");
require("dotenv").config();
const TOKEN_PATH = path.join(process.cwd(), "token.json");
const starterText = process.env.STARTER_TEXT;
const email = process.env.EMAIL ? process.env.EMAIL : "[email protected]";
const password = process.env.PASSWORD ? process.env.PASSWORD : "password123";
const topicName = process.env.TOPIC_NAME
? process.env.TOPIC_NAME
: "topic_name";
const configuration = new Configuration({
apiKey: process.env.API_KEY,
});
const openai = new OpenAIApi(configuration);
async function performPlaywrightMessage(link) {
console.log(`💃 Visiting ${link}`);
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto(link);
if (await page.isVisible("text='Accept all'")) {
await page.getByRole("button", { name: "Accept all" }).click();
}
const listingText = await page
.locator("div#ad_description_text")
.allTextContents();
const listingString = JSON.stringify(listingText);
await page
.locator("#rhs_column")
.getByRole("link", { name: "Send Message" })
.click();
if (await page.isVisible("text='Please sign in here.'")) {
await page.getByRole("link", { name: "Please sign in here." }).click();
await page.locator("#login_email_username").click();
await page.locator("#login_email_username").fill(email);
await page.locator("#login_basic #login_password").click();
await page.locator("#login_basic #login_password").fill(password);
await page.getByRole("button", { name: "Login" }).click();
}
await page
.getByRole("button", { name: "Yes, I have read the Security Advice" })
.click();
await page
.getByPlaceholder(
"Write your message with a personal touch and detailed information and refer to the Ad description. You can mention your availability to visit the flat and additional contact information such as your mobile phone number, where appropriate."
)
.click();
console.log("🎇Generating ChatGPT reponse...");
const gptResponse = await generateGptResponse(listingString);
const formattedResponse = gptResponse.replace(/"/g, "");
console.log("🎇Done!");
await page
.getByPlaceholder(
"Write your message with a personal touch and detailed information and refer to the Ad description. You can mention your availability to visit the flat and additional contact information such as your mobile phone number, where appropriate."
)
.fill(formattedResponse);
await page.getByRole("button", { name: "Send message" }).click();
await browser.close();
console.log("🍏 Message successfully sent!");
}
async function loadSavedCredentialsIfExist() {
try {
const content = await fs.readFile(TOKEN_PATH);
const credentials = JSON.parse(content);
return google.auth.fromJSON(credentials);
} catch (err) {
return null;
}
}
function getLatestMessageId(entries) {
const latestMessage = entries.reduce((acc, obj) => {
if (obj.id > acc.id) {
return obj;
}
return acc;
});
return latestMessage.messages[0].id;
}
function unicodeBase64Decode(text) {
text = text.replace(/\s+/g, "").replace(/\-/g, "+").replace(/\_/g, "/");
return decodeURIComponent(
Array.prototype.map
.call(atob(text), function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);
}
function logCompleteJsonObject(jsonObject) {
const base = jsonObject.payload.parts.filter(
(part) => part.mimeType === "text/plain"
)[0].body.data;
const decodedText = unicodeBase64Decode(base);
const regex = /https?:\/\/[^\s?]+[?&]campaign=suchauftrag_detail\b/g;
const links = decodedText.match(regex);
if (links && links.length >= 1) {
links.forEach(async (link) => {
try {
await performPlaywrightMessage(link);
} catch (error) {
console.log(error);
}
});
} else {
console.log("No link found.");
}
}
async function parseHistoryResponse(jsonObject) {
let cred = await loadSavedCredentialsIfExist();
const entries = jsonObject.history.filter((entry) => entry.messagesAdded);
const messageId = getLatestMessageId(entries);
await getMessage(cred, messageId);
}
async function resub(auth) {
const gmail = google.gmail({ version: "v1", auth });
const res = await gmail.users.watch({
userId: "me",
requestBody: {
labelIds: ["INBOX"],
topicName,
},
});
console.log(res);
}
async function getMessage(auth, messageId) {
const gmail = google.gmail({ version: "v1", auth });
const res = await gmail.users.messages.get({
userId: "me",
id: messageId,
});
logCompleteJsonObject(res.data);
}
async function getHistory(auth, historyId) {
const gmail = google.gmail({ version: "v1", auth });
const res = await gmail.users.history.list({
userId: "me",
startHistoryId: historyId,
});
parseHistoryResponse(res.data);
}
async function tryToSendMessage() {
let cred = await loadSavedCredentialsIfExist();
let historyId = 19977;
await getHistory(cred, historyId);
}
let generateGptResponse = async (listingText) => {
const prompt = `
Can you spice up the following text: "${starterText}" The updated text should explain why I would fit in the flatshare with the following listing text: "${listingText}". Add some emojies as well. Mention that my semester is from September to March, so a stay for that perioud would be ideal (but Im always flexible)! And if the listing is written in German, the answer should be in German as well. And if the listing says I need to say a specific word, start the whole text with that word!
`;
const turboMessage = [
{ role: "system", content: `I am applying to a flatshare listing.` },
{ role: "user", content: prompt },
];
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: turboMessage,
max_tokens: 1000,
temperature: 0.2,
});
return response.data.choices[0].message.content;
};
(async () => {
let cred = await loadSavedCredentialsIfExist();
await resub(cred);
})();
module.exports = { tryToSendMessage };