I’m working on a Ruby Telegram bot and need help with controlling response probability. Right now my bot always sends a message when triggered, but I want to add some randomness to make it more interesting.
What I’m trying to achieve is different probability rates for each response. Specifically, I want the bot to send the first response 50% of the time, the second response 30% of the time, and stay completely silent (no message at all) for the remaining 20% of cases.
Is there a way to implement this weighted probability system in Ruby? I’m still learning programming so any clear examples would be really helpful.
you could also use weighted arrays - just duplicate entries based on weight. like options = ['first'] * 5 + ['second'] * 3 + [nil] * 2 then result = options.sample. if result isn’t nil, send the message. uses more memory but it’s really readable for beginners.
Another clean approach is using Ruby’s case statement with ranges. I used this in my chatbot last year and it’s super maintainable:
when /TRIGGER_PATTERN/
chance = rand(1..100)
case chance
when 1..50
bot.api.send_message(chat_id: message.chat.id, text: "first response")
when 51..80
bot.api.send_message(chat_id: message.chat.id, text: "second response")
when 81..100
# silence - do nothing
end
end
The range syntax makes the percentages really obvious. Need to adjust weights later? Just modify the ranges. You can also throw in some logging to track which responses fire during testing.
Use a cumulative probability approach with rand(). Set up weighted options where each entry has the response and its probability threshold.
when /TRIGGER_PATTERN/
random_value = rand(100)
if random_value < 50
bot.api.send_message(chat_id: message.chat.id, text: "first response")
elsif random_value < 80 # 50 + 30
bot.api.send_message(chat_id: message.chat.id, text: "second response")
end
# remaining 20% cases fall through without sending anything
end
Generate a random number 0-99, then check which range it hits. Easy to tweak probabilities by changing thresholds, and adding responses is simple. I’ve used this in several bots - works great.