๐Ÿ“ฆ Petrus-Han / ChatGPT-On-WeChat

๐Ÿ“„ main.ts ยท 51 lines
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
51import QRCode from "qrcode";
import { WechatyBuilder } from "wechaty";
import { ChatGPTBot } from "./chatgpt.js";

// Wechaty instance
const weChatBot = WechatyBuilder.build({
  name: "my-wechat-bot",
});
// ChatGPTBot instance
const chatGPTBot = new ChatGPTBot();

async function main() {
  weChatBot
    // scan QR code for login
    .on("scan", async (qrcode, status) => {
      const url = `https://wechaty.js.org/qrcode/${encodeURIComponent(qrcode)}`;
      console.log(`๐Ÿ’ก Scan QR Code to login: ${status}\n${url}`);
      console.log(
        await QRCode.toString(qrcode, { type: "terminal", small: true })
      );
    })
    // login to WeChat desktop account
    .on("login", async (user: any) => {
      console.log(`โœ… User ${user} has logged in`);
      chatGPTBot.setBotName(user.name());
      await chatGPTBot.startGPTBot();
    })
    // message handler
    .on("message", async (message: any) => {
      try {
        console.log(`๐Ÿ“จ ${message}`);
        // handle message for customized task handlers
        await chatGPTBot.onCustimzedTask(message);
        // handle message for chatGPT bot
        await chatGPTBot.onMessage(message);
      } catch (e) {
        console.error(`โŒ ${e}`);
      }
    });

  try {
    await weChatBot.start();
  } catch (e) {
    console.error(`โŒ Your Bot failed to start: ${e}`);
    console.log(
      "๐Ÿค” Can you login WeChat in browser? The bot works on the desktop WeChat"
    );
  }
}
main();