首页 > 解决方案 > 使用 ruby​​ Telegram 机器人发送消息的示例方法的概率

问题描述

我有一个用 ruby​​ 编写的 Telegram 内联机器人。我想对它回答的内容有更多的控制权,并且有时将其关闭,即使它应该回复。

这就是我现在所拥有的:

when /WHATEVER/
  whatever = ['option 1', 'option 2']
  bot.api.send_message(chat_id: message.chat.id, text: "#{whatever.sample}")

我希望它有 50% 的时间用选项 1 回复,30% 的时间用选项 2 回复,20% 的时间不回复。

可能吗?

对不起,如果没有正确解释,我不是程序员,英语不是我的第一语言。

谢谢

标签: rubybotstelegramtelegram-bot

解决方案


您可以生成一个随机数并使用它来决定要采取的操作:

r = rand # 0.0 <= r < 1
if r <= 0.5 
  bot.api.send_message(chat_id: message.chat.id, text: "option 1")
else if r <= 0.8 
  bot.api.send_message(chat_id: message.chat.id, text: "option 2")
else
  # do nothing, you can actually ommit the `else` clause
end

一种不太优雅的方式:

options = ["1", "1", "1", "1", "1", "2", "2", "2", nil, nil]
option = options.sample
bot.api.send_message(chat_id: message.chat.id, text: option) if option

推荐阅读