Skip to content

Commit

Permalink
to: adding sheet command
Browse files Browse the repository at this point in the history
  • Loading branch information
Sma1lboy committed Sep 1, 2024
1 parent a87d100 commit f4d5bc0
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 62 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
"jobsPerMessage": 3,
"minsCheckInterval": 5,
"rooms": [
""
"测试多个群"
],
"googleSheet": false
"googleSheet": true
},
"dependencies": {
"@types/node-cron": "^3.0.11",
Expand All @@ -30,7 +30,7 @@
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"google-auth-library": "^9.14.0",
"google-spreadsheet": "^4.1.2",
"google-spreadsheet": "^4.1.3",
"node-cron": "^3.0.3",
"prettier": "^3.3.3",
"qrcode-terminal": "^0.12.0",
Expand Down
57 changes: 38 additions & 19 deletions src/command-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { InternshipJobProvider } from './providers/internship-job-provider';
import { NewGraduateJobProvider } from './providers/new-graduate-job-provider';
import { FileSystemService } from './file-system-service';
import { AnnotationType, Job, JobProvider, JobType, RoomsCacheFileNames } from './types';
import { GoogleSheetProvider } from './google-sheets-provider';
import { GoogleSheetDoc } from './google-sheets-provider';
import { jobWxBotConfig } from '../package.json';

interface Command {
Expand Down Expand Up @@ -131,44 +131,63 @@ export class CommandHandler {
},
},
{
name: 'sheet',
name: 'room-sheet',
aliases: [],
description: 'Get the excel sheet',
description: 'Get All Jobs posted in this chat room',
when: jobWxBotConfig.googleSheet,
execute: async (message: Message) => {
console.log('1. Function called, message:', message);

const room = message.room();
const roomTopic = await room?.topic();
if (!roomTopic || !room) return;
//read roomTopic from

console.log('2. Room and roomTopic:', { room, roomTopic });

if (!roomTopic || !room) {
console.log('Room or roomTopic is undefined, exiting function');
return;
}

let internJob: Job[] = [];
if (FileSystemService.fileExists(roomTopic, RoomsCacheFileNames.SENT_INTERN_JOBS)) {
internJob = FileSystemService.readJSON<Job[]>(
roomTopic,
RoomsCacheFileNames.SENT_INTERN_JOBS,
);
}

console.log('3. Intern jobs read:', internJob);

let newGradJob: Job[] = [];
if (FileSystemService.fileExists(roomTopic, RoomsCacheFileNames.SENT_NEW_GRAD_JOBS)) {
newGradJob = FileSystemService.readJSON<Job[]>(
roomTopic,
RoomsCacheFileNames.SENT_NEW_GRAD_JOBS,
);
}
const doc = GoogleSheetProvider.getInstance().doc;

console.log('4. New grad jobs read:', newGradJob);

const today = new Date().getTime();
const googleSheetDoc = new GoogleSheetDoc();
await googleSheetDoc.initialize(`${roomTopic} Job Posted Info - ${today}`);
const doc = googleSheetDoc.doc;
if (!doc) return;

await doc.loadInfo();
try {
let sheet = doc.sheetsByTitle['Intern'];
await sheet.clear();
sheet = doc.sheetsByTitle['New Grad'];
await sheet.clear();
} catch (error) {
console.error('there is no intern or new grad sheet');
}
await GoogleSheetProvider.getInstance().addJobSheet('Intern', internJob);
await GoogleSheetProvider.getInstance().addJobSheet('New Grad', newGradJob);
room.say(
`Generate google sheet success! Here is the link: https://docs.google.com/spreadsheets/d/${process.env.GOOGLE_SHEET_ID}`,
);

console.log('5. Google Sheet Doc created:', { googleSheetDoc, doc });

await googleSheetDoc.addJobSheet('Intern', internJob);
await googleSheetDoc.addJobSheet('New Grad', newGradJob);

console.log('9. Job sheets added');

doc.setPublicAccessLevel('reader');
let a = await doc.share('541898146chen@gmail.com');

console.log('10. Document shared, result:', a);
room.say('haohaohao');
},
},
];
Expand Down
101 changes: 67 additions & 34 deletions src/google-sheets-provider.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,89 @@
import { JWT } from 'google-auth-library';
import { GoogleSpreadsheet } from 'google-spreadsheet';
import { Job } from './types';

const SCOPES = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/drive',
];

export class GoogleSheetProvider {
private static instance: GoogleSheetProvider;

public static getInstance() {
if (!this.instance) {
this.instance = new GoogleSheetProvider();
}
return this.instance;
}
private docSheet: GoogleSpreadsheet;
export class GoogleSheetDoc {
private docSheet: GoogleSpreadsheet | undefined = undefined;
private auth: JWT;

private constructor() {
const auth = new JWT({
public constructor() {
this.auth = new JWT({
email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
key: process.env.GOOGLE_PRIVATE_KEY!.split(String.raw`\n`).join('\n'),
scopes: SCOPES,
});
this.docSheet = new GoogleSpreadsheet(process.env.GOOGLE_SHEET_ID!, auth);
}

public async initialize(title: string): Promise<void> {
try {
console.log('Initializing GoogleSheetDoc with title:', title);
this.docSheet = await GoogleSpreadsheet.createNewSpreadsheetDocument(this.auth, { title });
await this.docSheet.loadInfo();
await this.docSheet.addSheet({ title: 'Intern' });
await this.docSheet?.sheetsByIndex[0]?.delete();
console.log('New spreadsheet created successfully');
} catch (error) {
console.error('Error initializing GoogleSheetDoc:', error);
throw error;
}
}

public get doc() {
return this.docSheet;
}

public async addJobSheet(title: string, jobs: Job[]) {
await this.doc.loadInfo();
let sheet = this.doc.sheetsByTitle[title];
if (sheet) {
await sheet.clear();
await sheet.setHeaderRow(['Date Posted', 'Company', 'Role', 'Location', 'Application Link']);
} else {
sheet = await this.doc.addSheet({
title,
headerValues: ['Date Posted', 'Company', 'Role', 'Location', 'Application Link'],
});
if (!this.docSheet) {
console.error('Document sheet is not initialized');
return;
}

try {
console.log(`Adding job sheet: ${title}`);
await this.doc?.loadInfo();
let sheet = this.doc?.sheetsByTitle[title];

if (sheet) {
console.log('Clearing existing sheet');
await sheet.clear();
await sheet.setHeaderRow([
'Date Posted',
'Company',
'Role',
'Location',
'Application Link',
]);
} else {
console.log('Creating new sheet');
sheet = await this.doc?.addSheet({
title,
headerValues: ['Date Posted', 'Company', 'Role', 'Location', 'Application Link'],
});
}

let rows = jobs
.map((job) => ({
'Date Posted': job.datePosted,
Company: job.company,
Role: job.role,
Location: job.location,
'Application Link': job.applicationLink,
}))
.sort((a, b) => b['Date Posted'].localeCompare(a['Date Posted']));

console.log(`Adding ${rows.length} rows to the sheet`);
await sheet?.addRows(rows);
console.log('Rows added successfully');
} catch (error) {
console.error('Error in addJobSheet:', error);
throw error;
}
let rows = jobs
.map((job) => ({
'Date Posted': job.datePosted,
Company: job.company,
Role: job.role,
Location: job.location,
'Application Link': job.applicationLink,
}))
.sort((a, b) => b['Date Posted'].localeCompare(a['Date Posted']));

await sheet.addRows(rows);
}
}
21 changes: 15 additions & 6 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ axios@^1.1.3:
form-data "^4.0.0"
proxy-from-env "^1.1.0"

axios@^1.4.0, axios@^1.7.5:
axios@^1.7.5:
version "1.7.5"
resolved "https://registry.npmjs.org/axios/-/axios-1.7.5.tgz#21eed340eb5daf47d29b6e002424b3e88c8c54b1"
integrity sha512-fZu86yCo+svH3uqJ/yTdQ0QHpQu5oL+/QE+QPSv6BZSkDAoky9vytxp7u5qk83OJFS3kEBcesWni9WTZAv3tSw==
Expand All @@ -709,6 +709,15 @@ axios@^1.4.0, axios@^1.7.5:
form-data "^4.0.0"
proxy-from-env "^1.1.0"

axios@^1.7.6:
version "1.7.7"
resolved "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz#2f554296f9892a72ac8d8e4c5b79c14a91d0a47f"
integrity sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==
dependencies:
follow-redirects "^1.15.6"
form-data "^4.0.0"
proxy-from-env "^1.1.0"

balanced-match@^1.0.0:
version "1.0.2"
resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
Expand Down Expand Up @@ -1452,12 +1461,12 @@ google-protobuf@^3.18.0:
resolved "https://registry.npmjs.org/google-protobuf/-/google-protobuf-3.21.4.tgz#2f933e8b6e5e9f8edde66b7be0024b68f77da6c9"
integrity sha512-MnG7N936zcKTco4Jd2PX2U96Kf9PxygAPKBug+74LHzmHXmceN16MmRcdgZv+DGef/S9YvQAfRsNCn4cjf9yyQ==

google-spreadsheet@^4.1.2:
version "4.1.2"
resolved "https://registry.npmjs.org/google-spreadsheet/-/google-spreadsheet-4.1.2.tgz#92e30fdba7e0d78c55d50731528df7835d58bfee"
integrity sha512-HFBweDAkOcyC2qO9kmWESKbNuOcn+R7UzZN/tj5LLNxVv8FHmg113u0Ow+yaKwwIOt/NnDtPLuptAhaxTs0FYw==
google-spreadsheet@^4.1.3:
version "4.1.3"
resolved "https://registry.npmjs.org/google-spreadsheet/-/google-spreadsheet-4.1.3.tgz#9b0dc777b175ad90f1aaf22ce78753f271352a76"
integrity sha512-v/OBWYz8K40Vr3CMiPjo+iIhtri66MVzfCO4llDHJTsM5hI9PfMm64xjgvlRxd+/WHLMVvvlCEEYoNO7iMpJTQ==
dependencies:
axios "^1.4.0"
axios "^1.7.6"
lodash "^4.17.21"

graphemer@^1.4.0:
Expand Down

0 comments on commit f4d5bc0

Please sign in to comment.