用 Ruby 创建 Telegram 引用机器人
发布: (2026年1月17日 GMT+8 16:53)
1 min read
原文: Dev.to
Source: Dev.to
要求
- 必须有一个 IDE
- 项目结构:
project_folder/
├── bot.rb
├── quote.rb
├── help.rb
├── start.rb
└── Gemfile
注意:.env 文件未提交到 git。
start.rb
# start.rb
class Start
def initialize(bot)
@bot = bot
start_handler
end
def start_handler
@bot.command("start") do |ctx|
ctx.reply("welcome to quote_bot use /quote to get astonishing quotes")
end
end
end
telegem 提供 .command 方法来处理 / 命令(例如 /help、/start、/quote)。
ctx.reply 向当前聊天发送回复,并接受诸如 reply_markup 和 parse_mode 等选项。
help.rb
# help.rb
class Help
def initialize(bot)
@bot = bot
send_help_message
end
def send_help_message
@bot.command("help") do |ctx|
help_message = 3.0.4"
Gemfile
gem "httparty", "~> 0.21.0"
gem "dotenv", "~> 2.8"
.env 文件
创建一个 .env 文件(不要提交它),并填入你的令牌:
BOT_TOKEN=
安装与运行
# 如有需要,先安装 bundler
gem install bundler
# 安装依赖
bundle install
# 运行机器人
bundle exec ruby bot.rb
欲获取更详细的示例,请查看仓库。