如何在单台Linux服务器上持续运行Twitch与Discord Node.js聊天机器人?
实现Node.js多机器人在Linux服务器持续运行的方案
前期准备
- 把两个机器人的代码上传到Linux服务器,用
scp或者git克隆都可以 - 确认服务器已安装Node.js和npm,执行
node -v和npm -v检查版本,没装的话用包管理器安装:- Ubuntu/Debian:
sudo apt install nodejs npm - CentOS/RHEL:
sudo yum install nodejs npm
- Ubuntu/Debian:
- 分别进入两个机器人的目录,执行
npm install安装依赖包
方法一:用nohup快速后台运行(临时测试用)
这是最简单的后台运行方式,适合快速验证机器人能否正常运行
- 进入Twitch机器人目录,执行:
日志会输出到nohup node bot.js > twitch-bot.log 2>&1 &twitch-bot.log,机器人在后台持续运行 - 进入Discord机器人目录,执行:
nohup node bot.js > discord-bot.log 2>&1 & - 查看运行状态:
ps aux | grep node - 停止机器人:找到对应进程ID,执行
kill <进程ID>
方法二:用screen会话管理(需偶尔交互调试用)
适合需要随时进入机器人控制台查看输出或调试的场景
- 安装screen:
- Ubuntu/Debian:
sudo apt install screen - CentOS/RHEL:
sudo yum install screen
- Ubuntu/Debian:
- 创建Twitch机器人会话:
screen -S twitch-bot,进入会话后运行node bot.js,按Ctrl+A+D退出会话(机器人仍在后台运行) - 创建Discord机器人会话:
screen -S discord-bot,同样运行node bot.js后按Ctrl+A+D退出 - 重新进入会话:
screen -r twitch-bot或screen -r discord-bot - 停止机器人:在会话内按
Ctrl+C,或者执行screen -S <会话名> -X quit
方法三:用systemd服务(推荐长期稳定运行)
这是最可靠的方案,支持开机自动启动,机器人崩溃后自动重启
配置Twitch机器人服务
- 创建服务文件:
sudo nano /etc/systemd/system/twitch-bot.service - 写入以下内容(替换
your-username为服务器用户名,/path/to/twitch-bot为机器人实际目录):[Unit] Description=Twitch Chat Bot After=network.target [Service] User=your-username WorkingDirectory=/path/to/twitch-bot ExecStart=/usr/bin/node bot.js Restart=always RestartSec=5 StandardOutput=append:/var/log/twitch-bot.log StandardError=append:/var/log/twitch-bot.log [Install] WantedBy=multi-user.target - 保存退出后,刷新systemd配置:
sudo systemctl daemon-reload - 启动服务并设置开机自启:
sudo systemctl start twitch-bot sudo systemctl enable twitch-bot
配置Discord机器人服务
- 创建服务文件:
sudo nano /etc/systemd/system/discord-bot.service - 写入类似内容,替换路径和描述:
[Unit] Description=Discord Chat Bot After=network.target [Service] User=your-username WorkingDirectory=/path/to/discord-bot ExecStart=/usr/bin/node bot.js Restart=always RestartSec=5 StandardOutput=append:/var/log/discord-bot.log StandardError=append:/var/log/discord-bot.log [Install] WantedBy=multi-user.target - 同样执行:
sudo systemctl daemon-reload sudo systemctl start discord-bot sudo systemctl enable discord-bot
常用systemd管理命令
- 查看服务状态:
sudo systemctl status twitch-bot或sudo systemctl status discord-bot - 停止服务:
sudo systemctl stop twitch-bot或sudo systemctl stop discord-bot - 实时查看日志:
tail -f /var/log/twitch-bot.log或tail -f /var/log/discord-bot.log
内容的提问来源于stack exchange,提问作者Abbacus
相关产品推荐
相关产品推荐

