Hey there, fellow Ruby enthusiast! Ready to dive into the world of Facebook Messenger bots? You're in for a treat. We'll be using the nifty facebook-messenger
gem to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get your Facebook App ready:
Easy peasy, right?
Time to get our hands dirty with some Ruby goodness:
# Add this to your Gemfile gem 'facebook-messenger' # Then run bundle install
Now, let's set up a basic configuration:
require 'facebook/messenger' Facebook::Messenger::Subscriptions.subscribe( access_token: ENV['ACCESS_TOKEN'], subscribed_fields: %w[messages feed] )
Whether you're using Sinatra or Rails, setting up a webhook is a breeze:
# For Sinatra get '/webhook' do if params['hub.verify_token'] == ENV['VERIFY_TOKEN'] params['hub.challenge'] else 'Error, wrong validation token' end end # Don't forget to set up your routes for POST requests!
Now for the fun part - let's make your bot respond:
Bot.on :message do |message| message.reply(text: "Hey there! I got your message: #{message.text}") end
Your bot can do more than just text. Let's spice things up:
# Sending an image Bot.deliver({ recipient: { id: recipient_id }, message: { attachment: { type: 'image', payload: { url: 'https://example.com/cool-image.jpg' } } } }, access_token: ENV['ACCESS_TOKEN'])
Want to take it up a notch? Try these:
# Quick replies message.reply( text: 'Pick a color:', quick_replies: [ { content_type: 'text', title: 'Red', payload: 'PICKED_RED' }, { content_type: 'text', title: 'Blue', payload: 'PICKED_BLUE' } ] ) # Persistent menu Facebook::Messenger::Profile.set({ persistent_menu: [ { locale: 'default', composer_input_disabled: false, call_to_actions: [ { title: 'My Account', type: 'postback', payload: 'ACCOUNT_PAYLOAD' } ] } ] }, access_token: ENV['ACCESS_TOKEN'])
Local testing? No problem! Use ngrok to expose your local server:
ngrok http 4567
Then update your webhook URL in the Facebook App settings.
When you're ready to go live:
And there you have it! You're now armed and ready to create awesome Facebook Messenger bots with Ruby. Remember, the key to a great bot is creativity and user experience. So go forth and bot-ify the world!
Need more info? Check out the facebook-messenger gem documentation and the Facebook Messenger Platform docs.
Happy coding, Rubyist!