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
新开一个对话
什么是Node-Red
Node-RED
是IBM推出的一款基于流程编程的视觉化程式设计语言开发工具,通过这一工具,开发者可以将硬件设备与应用程序接口和在线服务相连,并组成一个小型物联网。2016年,IBM让Node-RED成为开源JS 基金会的子项目通俗来说,Node-Red是一个可视化编程服务,我们可以不需要写代码就能完成一个简单的功能
Telegram Bot
按照官网网站的介绍,bot可以干很多事情:
What Can You Do with Bots?
这篇教程就是我们来创建一个bot,让它作为我们的chatgpt的机器人
准备工作:
- 需要有一个
openai
账号的api key
- 需要自己有一个
telegram
的账号
- 需要自己有
node-red
的服务平台
开始
- 首先是node-red的搭建,官方支持很多种方式的搭建,网上教程也很多,这里是搭建到了我自己的vps上

使用的
docker
:docker run -it -p 1880:1880 -v node_red_data:/data --name mynodered nodered/node-red
- 然后我们来创建
Telegram Bot

接下来输入用户名,
bot id
就创建好了机器人。把API Key记下来,我们要在后面用到
- 打开我们之前搭建好的
node-red
,页面左边是工具栏,中间是Flow画布右边是信息输出,帮助之类

安装
telegram
插件,打开用户设置,控制板里面:
安装完成之后,左侧的节点栏就会多出来
telegram
接受,命令,发送等
- 开始编写Flow,首先我们梳理一下整体流程:
- 接受
telegram
消息 - 解析消息的内容,并且制作
openai api
需要的参数 - 发送
http
请求到openai
- 接收接口返回的数据,并且解析
- 执行
send
,发送数据到telegram
整体的流程图:

在第一个
telegram
里面需要添加bot
,如图:
第2个节点
make post body

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 api
的key

解析请求回来的数据节点:

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
就可以
ok整个流程创建完毕,然后调集右上角的部署,成功之后我们来测试一下
