NodeRed搭建Telegram Bot ChatGPT
type
Post
status
Published
date
Feb 16, 2023
slug
node-red-chatgpt
summary
使用nodered可视化来搭建一个基于ChatGPT的机器人
tags
开发
折腾
技巧
category
技术分享
icon
password
2023-03-04更新,使用了改为gpt-3.5-turbo模型,支持对话模式
图片没有做更新,只更新了代码
/new 新开一个对话
notion image

什么是Node-Red

 
Node-RED是IBM推出的一款基于流程编程的视觉化程式设计语言开发工具,通过这一工具,开发者可以将硬件设备与应用程序接口和在线服务相连,并组成一个小型物联网。2016年,IBM让Node-RED成为开源JS 基金会的子项目
通俗来说,Node-Red是一个可视化编程服务,我们可以不需要写代码就能完成一个简单的功能
 

Telegram Bot

按照官网网站的介绍,bot可以干很多事情:

What Can You Do with Bots?

 

这篇教程就是我们来创建一个bot,让它作为我们的chatgpt的机器人

准备工作:

  1. 需要有一个openai账号的api key
  1. 需要自己有一个telegram的账号
  1. 需要自己有node-red的服务平台

开始

  • 首先是node-red的搭建,官方支持很多种方式的搭建,网上教程也很多,这里是搭建到了我自己的vps上
    • notion image
      使用的docker
      docker run -it -p 1880:1880 -v node_red_data:/data --name mynodered nodered/node-red
       
  • 然后我们来创建Telegram Bot
    • telegram打开与https://t.me/BotFather对话,然后创建一个bot
      notion image
      接下来输入用户名,bot id 就创建好了机器人。把API Key记下来,我们要在后面用到
      notion image
  • 打开我们之前搭建好的node-red页面左边是工具栏,中间是Flow画布右边是信息输出,帮助之类
    • notion image
      安装telegram 插件,打开用户设置,控制板里面:
      notion image
      安装完成之后,左侧的节点栏就会多出来telegram 接受,命令,发送等
      notion image
  • 开始编写Flow,首先我们梳理一下整体流程:
    • 接受telegram消息
    • 解析消息的内容,并且制作openai api需要的参数
    • 发送http请求到openai
    • 接收接口返回的数据,并且解析
    • 执行send,发送数据到telegram
    • 整体的流程图:
      notion image
      在第一个telegram里面需要添加bot,如图:
      notion image
      第2个节点 make post body
      notion image
      flow.set("chatid", msg.payload.chatId) let histroy = flow.get('histroy'); node.log(histroy); let messages = [{ "role": "user", "content": msg.payload.content }]; const isNew = msg.payload.content == '/new' ? true:false if(isNew) { flow.set('histroy','') return } if (histroy != null && histroy != undefined && histroy.length > 0) { let hisobj = JSON.parse(histroy) messages.unshift(hisobj) } msg.payload = { "model": "gpt-3.5-turbo", "messages": messages} return msg
      http请求节点配置:token填写open apikey
      notion image
      解析请求回来的数据节点:
      notion image
      msg.payload.content = '请稍后再试'; if (msg.payload.choices[0] != undefined) { msg.payload.content = msg.payload.choices[0].message.content; } flow.set('histroy', JSON.stringify(msg.payload.choices[0].message)); msg.payload.chatId = flow.get("chatid"); msg.payload.type = 'message'; return msg;
      最后send节点,直接选择之前创建好的bot就可以
      notion image
      ok整个流程创建完毕,然后调集右上角的部署,成功之后我们来测试一下
      notion image

一切正常,就是速度会稍微慢一点,本文只是简单的玩一下,多人使用会有chatid混乱的问题

 
 

© Fat uncle 2024