Hey there, fellow developer! Ready to dive into the world of Line API integration using Ruby? You're in for a treat. Line's messaging platform is a powerhouse, and with the line-bot-api
package, we'll be up and running in no time. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's add the line-bot-api
gem to your project. Pop this into your Gemfile:
gem 'line-bot-api'
Then run:
bundle install
Easy peasy, right?
Now, let's get those Line channel credentials set up. You'll need your channel secret and channel token from the Line Developer Console. Here's how we initialize the Line client:
require 'line/bot' client = Line::Bot::Client.new do |config| config.channel_secret = 'YOUR_CHANNEL_SECRET' config.channel_token = 'YOUR_CHANNEL_TOKEN' end
Time to handle those incoming webhook events. Here's a basic Sinatra app to get you started:
post '/callback' do body = request.body.read signature = request.env['HTTP_X_LINE_SIGNATURE'] unless client.validate_signature(body, signature) error 400 do 'Bad Request' end end events = client.parse_events_from(body) events.each do |event| case event when Line::Bot::Event::Message handle_message(event) end end "OK" end
Let's add a handle_message
method to parse those incoming messages:
def handle_message(event) case event.type when Line::Bot::Event::MessageType::Text message = { type: 'text', text: event.message['text'] } client.reply_message(event['replyToken'], message) end end
Want to spice things up? Try sending a carousel template:
def send_carousel(event) message = { type: 'template', altText: 'Carousel template', template: { type: 'carousel', columns: [ { title: 'Title 1', text: 'Description 1', actions: [ { type: 'message', label: 'Action 1', text: 'Action 1' } ] }, { title: 'Title 2', text: 'Description 2', actions: [ { type: 'message', label: 'Action 2', text: 'Action 2' } ] } ] } } client.reply_message(event['replyToken'], message) end
Need user details? Here's how to fetch them:
user_id = event['source']['userId'] response = client.get_profile(user_id) profile = JSON.parse(response.body) puts "Display name: #{profile['displayName']}"
For local testing, ngrok is your best friend. Run your app locally, then use ngrok to expose it:
ngrok http 4567
Update your webhook URL in the Line Developer Console with the ngrok URL, and you're good to go!
When you're ready to go live, make sure your hosting solution supports SSL - Line requires HTTPS for webhooks. Heroku, AWS, or Google Cloud Platform are all solid choices.
And there you have it! You're now equipped to build some awesome Line integrations with Ruby. Remember, this is just scratching the surface - there's so much more you can do with the Line API. Keep experimenting, and don't forget to check out the official Line documentation for more advanced features.
Happy coding, and may your bots be ever responsive!