wangrongding / wechat-bot

🤖一个基于 WeChaty 结合 OpenAi ChatGPT / Kimi / 讯飞等Ai服务实现的微信机器人 ,可以用来帮助你自动回复微信消息,或者管理微信群/好友,检测僵尸粉等...
MIT License
4.96k stars 710 forks source link

:fire: 优化代码,增加群聊和私人分支的走向 #16

Closed yangbuyiya closed 1 year ago

yangbuyiya commented 1 year ago

优化代码,增加群聊和私人分支的走向。

如果需要分片消息请使用下面代码


// 定义机器人的名称
let botName = "@lzys522";

/**
* 消息发送
* @param message
* @returns {Promise<void>}
  */
  async function onMessage(message) {
  const talker = message.talker();
  const isText = message.type() === bot.Message.Type.Text; // 消息类型是否为文本
  if (talker.self() || message.type() > 10 || talker.name() == "微信团队" && isText) {
  return;
  }
  const text = message.text();
  const room = message.room();
  if (!room) {
  console.log(`Chat GPT Enabled User: ${talker.name()}`);
  const response = await getChatGPTReply(text)
  await trySay(talker, response);
  return;
  }
  let realText = cleanMessage(text);
  // 如果不是指定艾特人那么就不进行发送消息
  if (text.indexOf(`${botName}`) === -1) {
  return;
  }
  realText = text.replace(`${botName}`, "");
  const topic = await room.topic();
  const response = await getChatGPTReply(realText)
  const result = `${realText}\n ----------------\n 个人网站;https://yby6.com \n ---------------------\n ${response}`;
  await trySay(room, result);
  }

const SINGLE_MESSAGE_MAX_SIZE = 500;

/**
* 发送
* @param talker 发送哪个  room为群聊类 text为单人
* @param msg
* @returns {Promise<void>}
  */
  async function trySay(talker, msg) {
  const messages = [];
  let message = msg;
  while (message.length > SINGLE_MESSAGE_MAX_SIZE) {
  messages.push(message.slice(0, SINGLE_MESSAGE_MAX_SIZE));
  message = message.slice(SINGLE_MESSAGE_MAX_SIZE);
  }
  messages.push(message);
  for (const msg of messages) {
  await talker.say(msg);
  }
  }

async function cleanMessage(text){
let realText = text;
const item = text.split("- - - - - - - - - - - - - - -");
if (item.length > 1) {
realText = item[item.length - 1];
}
return realText;
}
wangrongding commented 1 year ago

你好~ 是否愿意格式化代码后把一些宣传信息删除了再提一个 PR 呢?🌸

yangbuyiya commented 1 year ago

你好~ 是否愿意格式化代码后把一些宣传信息删除了再提一个 PR 呢?🌸

好的忘记删除部分信息,明天审查重新提交PR

wangrongding commented 1 year ago

好的忘记删除部分信息,明天审查重新提交PR

😅好的,谢谢~