Telegram Bot/Discord机器人部署到香港VPS全流程教程

Telegram Bot/Discord机器人部署到香港VPS全流程教程

为什么要把 Bot 部署到 VPS?

本地运行 Bot 的问题很明显:电脑一关机 Bot 就停了,家庭宽带 IP 不固定,带宽也有限制。将 Bot 部署到香港 VPS,可以实现 7×24 小时不间断运行,固定 IP,访问 Telegram/Discord API 延迟低。


一、环境准备

# 更新系统
sudo apt update && sudo apt upgrade -y

# 安装 Python 3 和 pip(Python Bot)
sudo apt install python3 python3-pip python3-venv -y

# 安装 Node.js(Node.js Bot)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install nodejs -y

# 验证安装
python3 --version
node --version

二、部署 Telegram Bot(Python aiogram 示例)

# 创建项目目录
mkdir ~/tgbot && cd ~/tgbot

# 创建虚拟环境
python3 -m venv venv
source venv/bin/activate

# 安装依赖
pip install aiogram python-dotenv

# 创建环境变量文件
nano .env

写入 Bot Token:

BOT_TOKEN=你的BotToken

创建 Bot 主文件:

nano bot.py
import asyncio
from aiogram import Bot, Dispatcher, types
from aiogram.filters import CommandStart
import os
from dotenv import load_dotenv

load_dotenv()
bot = Bot(token=os.getenv("BOT_TOKEN"))
dp = Dispatcher()

@dp.message(CommandStart())
async def start(message: types.Message):
    await message.answer("Bot 运行中!")

async def main():
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

三、使用 systemd 实现进程守护(开机自启)

sudo nano /etc/systemd/system/tgbot.service
[Unit]
Description=Telegram Bot
After=network.target

[Service]
Type=simple
User=youruser
WorkingDirectory=/home/youruser/tgbot
ExecStart=/home/youruser/tgbot/venv/bin/python bot.py
Restart=always
RestartSec=10
EnvironmentFile=/home/youruser/tgbot/.env

[Install]
WantedBy=multi-user.target
# 启用并启动服务
sudo systemctl daemon-reload
sudo systemctl enable tgbot
sudo systemctl start tgbot

# 查看运行状态
sudo systemctl status tgbot

# 查看实时日志
sudo journalctl -u tgbot -f

四、部署 Discord Bot(Node.js discord.js 示例)

mkdir ~/discordbot && cd ~/discordbot
npm init -y
npm install discord.js dotenv

nano .env
DISCORD_TOKEN=你的DiscordBotToken
nano index.js
const { Client, GatewayIntentBits } = require('discord.js');
require('dotenv').config();

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });

client.on('ready', () => {
    console.log(`Bot 已登录:${client.user.tag}`);
});

client.on('messageCreate', msg => {
    if (msg.content === '!ping') msg.reply('Pong!');
});

client.login(process.env.DISCORD_TOKEN);

同样创建 systemd 服务文件,将 ExecStart 改为 node index.js,确保 Bot 7×24 小时运行。


五、常见问题

  • Bot 无法连接 Telegram API:检查服务器是否能访问 api.telegram.org,香港 VPS 通常可直接访问
  • 进程意外退出:查看 journalctl 日志确认报错原因,systemd 的 Restart=always 会自动重启
  • 环境变量读取失败:确认 .env 文件路径和 EnvironmentFile 配置的路径一致

总结

香港 VPS 部署 Bot 的完整流程:安装运行环境 → 上传 Bot 代码 → 配置环境变量 → 创建 systemd 服务实现开机自启和进程守护。香港节点访问 Telegram 和 Discord API 延迟低,是 Bot 托管的理想选择。

IDC.Net 香港云服务器首月 10 元起,1 核 2G 内存足够运行多个 Bot,CN2 GIA 线路,支持支付宝付款,3 天无理由退款。

Telegram