如何在 Ruby 中创建 Telegram 机器人

发布: (2026年1月15日 GMT+8 21:47)
2 min read
原文: Dev.to

Source: Dev.to

如何在 Ruby 中创建 Telegram 机器人封面图片

你一定听说过或使用过 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 示例

Back to Blog

相关文章

阅读更多 »

用 Ruby 创建 Telegram 引用机器人

要求 - 必须使用 IDE - 项目结构: ``` project_folder/ ├── bot.rb ├── quote.rb ├── help.rb ├── start.rb └── Gemfile ``` 注意: 不提交 .env 文件。

Ruby 异常处理与正则表达式

异常处理 在 Ruby 中查看抛出和处理异常的基本方法。 ruby def raise_exception puts 'I am before the raise.' raise 'An error has occured' puts 'I am after the raise' 执行…