today.isangjeong/app/lib/instagram.ts

86 lines
No EOL
2.7 KiB
TypeScript

import path from 'path';
import { IgApiClient } from "igramapi";
const ig = new IgApiClient();
export async function Login() {
ig.state.generateDevice(process.env.IG_USERNAME!);
ig.state.appUserAgent
ig.request.end$.subscribe(async () => {
const serialized = await ig.state.serialize();
delete serialized.constants; // this deletes the version info, so you'll always use the version provided by the library
await Bun.write('./temp/session.json', JSON.stringify(serialized));
});
try {
let loggedInUser;
try {
if (await Bun.file('./temp/session.json').exists()) {
const sessionData = await Bun.file('./temp/session.json').json();
await ig.state.deserialize(sessionData);
loggedInUser = await ig.account.login(
process.env.IG_USERNAME!,
process.env.IG_PASSWORD!
);
} else {
loggedInUser = await ig.account.login(
process.env.IG_USERNAME!,
process.env.IG_PASSWORD!
);
await ig.simulate.preLoginFlow();
process.nextTick(async () => await ig.simulate.postLoginFlow());
}
} catch (error: any) {
if (error.name === "IgCheckpointError") {
console.error(
"Instagram checkpoint required. Please verify your account in the Instagram app or handle the challenge."
);
// Optionally, you can trigger challenge handling here
// await ig.challenge.auto(true); // Requesting sms-code or click "It was me" button
} else {
console.error("🔒 | Login failed:", error);
}
throw error;
}
const currentUser = await ig.account.currentUser();
return { loggedInUser, currentUser };
} catch (error) {
console.warn("⚠️ | Failed to load session data:", error);
}
}
export class Upload {
static async Post(filePath: string, caption: string) {
try {
const ImagePath = path.resolve(`${filePath}`);
const bunFile = Bun.file(ImagePath);
const ImageBuffer = Buffer.from(await bunFile.arrayBuffer());
await ig.publish.photo({
file: ImageBuffer,
caption: caption,
});
} catch (error) {
console.error("Error uploading post:", error);
}
}
static async Story(filePath: string, MLSV_YMD: string) {
try {
const ImagePath = path.resolve(`${filePath}`);
const bunFile = Bun.file(ImagePath);
const ImageBuffer = Buffer.from(await bunFile.arrayBuffer());
await ig.publish.story({
file: ImageBuffer,
caption: `#인천상정중학교 #상정중학교 #급식 \n${MLSV_YMD}일자 급식`,
});
} catch (error) {
console.error("Error uploading post:", error);
}
}
}