用 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_markupparse_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

欲获取更详细的示例,请查看仓库。

Back to Blog

相关文章

阅读更多 »

Ruby 异常处理与正则表达式

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

C# 条件语句 (if, else, switch)

最初发表于 if 语句 if 语句在条件为真时执行代码块。 ```csharp int number = 10; if (number > 5) { Console.WriteLine('Num...'); } ```