Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️: Refactor code for add more error log #62

Merged
merged 3 commits into from
Dec 8, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
💥♻️: Refact code to improve readable and change config file
  • Loading branch information
fuergaosi233 committed Dec 8, 2022
commit fd9d0497a414dd4bb3152b08fe0dd616c164aa89
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ Your config.yaml should be like this:
chatGPTAccountPool:
- email: <your email>
password: <your password>
botConfig:
- trigger_keywords: <empty or you trigger keywords>
# if you hope only some keywords can trigger chatgpt on private chat, you can set it like this:
chatPrivateTiggerKeyword: ""
```
⚠️ Trigger keywords must appear in the first position of the received message.
⚠️ Pls make sure your network can log in to OpenAI, and if you fail to login in try setting up a proxy or using SessionToken.
Expand Down
3 changes: 1 addition & 2 deletions config.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ chatGPTAccountPool:
- email: email
password: password
session_token: session_token
botConfig:
- trigger_keywords: trigger_keywords
chatPrivateTiggerKeyword: ""
125 changes: 75 additions & 50 deletions src/chatgpt.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ChatGPTAPI, ChatGPTConversation } from "chatgpt";
import { Message } from "wechaty";
import { MessageType } from "wechaty-puppet/src/schemas/message";
import { config } from "./config.js";
import { execa } from "execa";
import { Cache } from "./cache.js";
Expand Down Expand Up @@ -128,25 +129,34 @@ export class ChatGPTBot {
conversations = new Map<string, ChatGPTConversation>();
chatGPTPool = new ChatGPTPoole();
cache = new Cache("cache.json");
trigger_keywords = "";
chatPrivateTiggerKeyword = config.chatPrivateTiggerKeyword;
botName: string = "";
setBotName(botName: string) {
this.botName = botName;
}
get chatGroupTiggerKeyword(): string {
return `@${this.botName}`;
}
async startGPTBot() {
console.debug(`Start GPT Bot Config is:${config}`);
await this.chatGPTPool.startPools();
console.debug(`🤖️ Start GPT Bot Success, ready to handle message!`);
}
// TODO: Add reset conversation id and ping pong
async command(): Promise<void> {}
// remove more times conversation and mention
cleanMessage(text: string): string {
let realText = text;
const item = text.split("- - - - - - - - - - - - - - -");
cleanMessage(rawText: string, privateChat: boolean = false): string {
let text = rawText;
const item = rawText.split("- - - - - - - - - - - - - - -");
if (item.length > 1) {
realText = item[item.length - 1];
text = item[item.length - 1];
}
text = text.replace(
privateChat ? this.chatPrivateTiggerKeyword : this.chatGroupTiggerKeyword,
""
);
// remove more text via - - - - - - - - - - - - - - -
return realText;
return text;
}
async getGPTMessage(text: string, talkerId: string): Promise<string> {
return await this.chatGPTPool.sendMessage(text, talkerId);
Expand All @@ -167,60 +177,75 @@ export class ChatGPTBot {
await talker.say(msg);
}
}
async onMessage(message: Message) {
const talker = message.talker();
if (
// Check whether the ChatGPT processing can be triggered
tiggerGPTMessage(text: string, privateChat: boolean = false): boolean {
const chatPrivateTiggerKeyword = this.chatPrivateTiggerKeyword;
let triggered = false;
if (privateChat) {
triggered = chatPrivateTiggerKeyword
? text.includes(chatPrivateTiggerKeyword)
: true;
} else {
triggered = text.includes(this.chatGroupTiggerKeyword);
}
if (triggered) {
console.log(`🎯 Triggered ChatGPT: ${text}`);
}
return triggered;
}
// Filter out the message that does not need to be processed
isNonsense(
talker: ContactInterface,
messageType: MessageType,
text: string
): boolean {
return (
talker.self() ||
message.type() > 10 ||
messageType > 10 ||
talker.name() == "微信团队" ||
// 语音(视频)消息
message.text().includes("收到一条视频/语音聊天消息,请在手机上查看") ||
text.includes("收到一条视频/语音聊天消息,请在手机上查看") ||
// 红包消息
message.text().includes("收到红包,请在手机上查看") ||
text.includes("收到红包,请在手机上查看") ||
// 位置消息
message.text().includes("/cgi-bin/mmwebwx-bin/webwxgetpubliclinkimg")
) {
text.includes("/cgi-bin/mmwebwx-bin/webwxgetpubliclinkimg")
);
}

async onPrivateMessage(talker: ContactInterface, text: string) {
const talkerId = talker.id;
const gptMessage = await this.getGPTMessage(text, talkerId);
await this.trySay(talker, gptMessage);
}

async onGroupMessage(
talker: ContactInterface,
text: string,
room: RoomInterface
) {
const talkerId = talker.id;
const gptMessage = await this.getGPTMessage(text, talkerId);
const result = `${text}\n ------\n ${gptMessage}`;
await this.trySay(room, result);
}
async onMessage(message: Message) {
const talker = message.talker();
const rawText = message.text();
const room = message.room();
const messageType = message.type();
const privateChat = !room;
if (this.isNonsense(talker, messageType, rawText)) {
return;
}
const text = message.text();
const room = message.room();
if (!room) {
let canSend = false;
let trigger_keywords = this.trigger_keywords;
if (trigger_keywords) {
if (text.indexOf(trigger_keywords) == 0) {
//only if the keywords appear in the first position will they trigger a response
console.log(
`🎯 Hit GPT Enabled User by Trigger keywords:${trigger_keywords} , User:${talker.name()}`
);
canSend = true;
}
if (this.tiggerGPTMessage(rawText, privateChat)) {
const text = this.cleanMessage(rawText, privateChat);
if (privateChat) {
return await this.onPrivateMessage(talker, text);
} else {
console.log(`🎯 Hit GPT Enabled User: ${talker.name()}`);
canSend = true;
return await this.onGroupMessage(talker, text, room);
}

if (canSend) {
const response = await this.getGPTMessage(text, talker.id);
await this.trySay(talker, response);
}
return;
}
let realText = this.cleanMessage(text);
// The bot should reply mention message
if (!realText.includes(`@${this.botName}`)) {
} else {
return;
}
realText = text.replace(`@${this.botName}`, "");
const topic = await room.topic();
console.debug(
`receive message: ${realText} from ${talker.name()} in ${topic}, room: ${
room.id
}`
);
console.log(`Hit GPT Enabled Group: ${topic} in room: ${room.id}`);
const response = await this.getGPTMessage(realText, talker.id);
const result = `${realText}\n ------\n ${response}`;
await this.trySay(room, result);
}
}
10 changes: 10 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,14 @@ export const config: IConfig = {
configFile.chatGptRetryTimes ||
Number(process.env.CHAT_GPT_RETRY_TIMES) ||
3,

chatPrivateTiggerKeyword:
configFile.chatPrivateTiggerKeyword ||
// Try compatible with previous designs
(configFile?.botConfig as Array<Map<string, string>>).reduce(
(prev: string, curr: Map<string, string>) =>
curr.get("trigger_keywords") || "",
""
) ||
"",
};
1 change: 1 addition & 0 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@ export interface IConversationItem {
export interface IConfig {
chatGPTAccountPool: IAccount[];
chatGptRetryTimes: number;
chatPrivateTiggerKeyword: string;
}