如何在 Ruby 中创建 Telegram 机器人
发布: (2026年1月15日 GMT+8 21:47)
2 min read
原文: Dev.to
Source: Dev.to

你一定听说过或使用过 Telegram 机器人。
现在真正的问题是:它们是如何创建的?我们马上就会看到答案——准备好你的 IDE,因为我们将在 5 分钟内创建一个机器人。
要求
- 一个安装了 Ruby 的优秀 IDE
- 基础或高级的 Ruby 知识
- 来自 @BotFather 的机器人令牌
如果你不知道如何获取机器人令牌,请查看这篇文章 👉 如何获取你的 Telegram 令牌。
设置
1. 创建 Gemfile
source 'https://rubygems.org'
gem 'telegem', '~> 3.0.4'
gem 'dotenv', '~> 2.8'
# add any other gems you wish (httparty, nethttp, json, etc.)
2. 安装依赖
如果你使用 Bundler:
bundle install
或者手动安装 gem:
gem install telegem dotenv
3. 添加你的机器人令牌
在项目根目录创建 .env 文件:
BOT_TOKEN=11234:445849489449 # replace with your actual token
创建机器人
创建一个名为 bot.rb 的文件:
# bot.rb
require 'telegem'
require 'dotenv/load'
bot = Telegem.new(ENV['BOT_TOKEN'])
bot.command('start') do |ctx|
ctx.reply('welcome to test2bot')
end
bot.command('help') do |ctx|
ctx.reply('**u need help**', parse_mode: 'Markdown')
end
bot.start_polling
puts 'bot has started'
运行机器人
bundle exec ruby bot.rb
你的机器人现在会响应 /start 和 /help 命令。
更多资源
想要更深入的教程和更多示例,请查看官方仓库 👉 Telegem 示例。