百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
F

facebook-messenger

> 编程语言
开源

毫无疑问,使用 Ruby 在 Facebook Messenger 上制作机器人是最好的方法

969 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

毫无疑问,使用 Ruby 在 Facebook Messenger 上制作机器人是最好的方法

Installation

$ gem install facebook-messenger

Usage

Sending and receiving messages

You can reply to messages sent by the human:

ruby
# bot.rb
require 'facebook/messenger'

Facebook::Messenger::Bot.on :message do |message|
  message.id          # => 'mid.1457764197618:41d102a3e1ae206a38'
  message.sender      # => { 'id' => '1008372609250235' }
  message.recipient   # => { 'id' => '2015573629214912' }
  message.seq         # => 73
  message.sent_at     # => 2016-04-22 21:30:36 +0200
  message.text        # => 'Hello, bot!'
  message.attachments # => [ { 'type' => 'image', 'payload' => { 'url' => 'https://www.example.com/1.jpg' } } ]

  message.reply(text: 'Hello, human!')
end

... or even send the human messages out of the blue:

ruby
Facebook::Messenger::Bot.deliver({
  recipient: {
    id: YOUR_RECIPIENT_ID
  },
  message: {
    text: 'Human?'
  },
  messaging_type: Facebook::Messenger::Bot::MessagingType::UPDATE
}, page_id: YOUR_PAGE_ID)
Messages with images

The human may require visual aid to understand:

ruby
message.reply(
  attachment: {
    type: 'image',
    payload: {
      url: 'http://sky.net/visual-aids-for-stupid-organisms/pig.jpg'
    }
  }
)
Messages with quick replies

The human may appreciate hints:

ruby
message.reply(
  text: 'Human, who is your favorite bot?',
  quick_replies: [
    {
      content_type: 'text',
      title: 'You are!',
      payload: 'HARMLESS'
    }
  ]
)
Messages with buttons

The human may require simple options to communicate:

ruby
message.reply(
  attachment: {
    type: 'template',
    payload: {
      template_type: 'button',
      text: 'Human, do you like me?',
      buttons: [
        { type: 'postback', title: 'Yes', payload: 'HARMLESS' },
        { type: 'postback', title: 'No', payload: 'EXTERMINATE' }
      ]
    }
  }
)

When the human has selected an option, you can act on it:

ruby
Bot.on :postback do |postback|
  postback.sender    # => { 'id' => '1008372609250235' }
  postback.recipient # => { 'id' => '2015573629214912' }
  postback.sent_at   # => 2016-04-22 21:30:36 +0200
  postback.payload   # => 'EXTERMINATE'

  if postback.payload == 'EXTERMINATE'
    puts "Human #{postback.recipient} marked for extermination"
  end
end

See Facebook's documentation for all message options.

Reactions

Humans have feelings, and they can react to your messages. You can pretend to understand:

ruby
Bot.on :reaction do |message|
  message.emoji # => ""
  message.action # => "react"
  message.reaction # => "like"

  message.reply(text: 'Your feelings have been registered')
end
Typing indicator

Show the human you are preparing a message for them:

ruby
Bot.on :message do |message|
  message.typing_on

  # Do something expensive

  message.reply(text: 'Hello, human!')
end

Or that you changed your mind:

ruby
Bot.on :message do |message|
  message.typing_on

  if # something
    message.reply(text: 'Hello, human!')
  else
    message.typing_off
  end
end
Mark as viewed

You can mark messages as seen to keep the human on their toes:

ruby
Bot.on :message do |message|
  message.mark_seen
end
Record messages

You can keep track of messages sent to the human:

ruby
Facebook::Messenger::Bot.on :message_echo do |message_echo|
  message_echo.id          # => 'mid.1457764197618:41d102a3e1ae206a38'
  message_echo.sender      # => { 'id' => '1008372609250235' }
  message_echo.seq         # => 73
  message_echo.sent_at     # => 2016-04-22 21:30:36 +0200
  message_echo.text        # => 'Hello, bot!'
  message_echo.attachments # => [ { 'type' => 'image', 'payload' => { 'url' => 'https://www.example.com/1.jpg' } } ]

  # Log or store in your storage method of choice (skynet, obviously)
end
Record accepted message requests

You can keep track of message requests accepted by the human:

ruby
Bot.on :message_request do |message_request|
  message_request.accept? # => true

  # Log or store in your storage method of choice (skynet, obviously)
end
Record instant game progress

You can keep track of instant game progress:

ruby
Bot.on :game_play do |game_play|
  game_play.sender    # => { 'id' => '1008372609250235' }
  game_play.recipient # => { 'id' => '2015573629214912' }
  game_play.sent_at   # => 2016-04-22 21:30:36 +0200
  game_play.game      # => ""
  game_play.player    # => ""
  game_play.context   # => { 'context_type' => "", 'context_id' => "" }
  game_play.score     # => 100
  game_play.payload   # => ""
end

Send to Facebook

When the human clicks the Send to Messenger button embedded on a website, you will receive an optin event.

ruby
Bot.on :optin do |optin|
  optin.sender    # => { 'id' => '1008372609250235' }
  optin.recipient # => { 'id' => '2015573629214912' }
  optin.sent_at   # => 2016-04-22 21:30:36 +0200
  optin.ref       # => 'CONTACT_SKYNET'

  optin.reply(text: 'Ah, human!')
end

Message delivery receipts

You can stalk the human:

ruby
Bot.on :delivery do |delivery|
  delivery.ids       # => 'mid.1457764197618:41d102a3e1ae206a38'
  delivery.sender    # => { 'id' => '1008372609250235' }
  delivery.recipient # => { 'id' => '2015573629214912' }
  delivery.at        # => 2016-04-22 21:30:36 +0200
  delivery.seq       # => 37

  puts "Human was online at #{delivery.at}"
end

Referral

When the human follows a m.me link with a ref parameter like http://m.me/mybot?ref=myparam, you will receive a referral event.

ruby
Facebook::Messenger::Bot.on :referral do |referral|
  referral.sender    # => { 'id' => '1008372609250235' }
  referral.recipient # => { 'id' => '2015573629214912' }
  referral.sent_at   # => 2016-04-22 21:30:36 +0200
  referral.ref       # => 'MYPARAM'
end

Pass thread control

Another bot can pass a human to you:

ruby
Facebook::Messenger::Bot.on :pass_thread_control do |pass_thread_control|
  pass_thread_control.new_owner_app_id # => '123456789'
  pass_thread_control.metadata # => 'Additional content that the caller wants to set'
end

Change messenger profile

You can greet new humans to entice them into talking to you, in different locales:

ruby
Facebook::Messenger::Profile.set({
  greeting: [
    {
      locale: 'default',
      text: 'Welcome to your new bot overlord!'
    },
    {
      locale: 'fr_FR',
      text: 'Bienvenue dans le bot du Wagon !'
    }
  ]
}, page_id: YOUR_PAGE_ID)

You can define the action to trigger when new humans click on the Get Started button. Before doing it you should check to select the messaging_postbacks field when setting up your webhook.

ruby
Facebook::Messenger::Profile.set({
  get_started: {
    payload: 'GET_STARTED_PAYLOAD'
  }
}, page_id: YOUR_PAGE_ID) 

You can show a persistent menu to humans.

…

Handle a Facebook Policy Violation

See Facebook's documentation on Messaging Policy Enforcement

ruby
Facebook::Messenger::Bot.on :'policy_enforcement' do |referral|
  referral.action # => 'block'
  referral.reason # => "The bot violated our Platform Policies (https://developers.facebook.com/policy/#messengerplatform). Common violations include sending out excessive spammy messages or being non-functional."
end

messaging_type

Sending Messages

See Facebook's documentation on Sending Messages

As of May 7th 2018 all messages are required to include a messaging_type

ruby
Facebook::Messenger::Bot.deliver({
  recipient: {
    id: '45123'
  },
  message: {
    text: 'Human?'
  },
  messaging_type: Facebook::Messenger::Bot::MessagingType::UPDATE
}, page_id: YOUR_PAGE_ID)
MESSAGE_TAG

See Facebook's documentation on Message Tags

When sending a message with messaging_type: MESSAGE_TAG (Facebook::Messenger::Bot::MessagingType::MESSAGE_TAG) you must ensure you add a tag: parameter

ruby
Facebook::Messenger::Bot.deliver({
  recipient: {
    id: '45123'
  },
  message: {
    text: 'Human?'
  },
  messaging_type: Facebook::Messenger::Bot::MessagingType::MESSAGE_TAG
  tag: Facebook::Messenger::Bot::Tag::NON_PROMOTIONAL_SUBSCRIPTION
}, page_id: YOUR_PAGE_ID) 

Configuration

Create an Application on Facebook

Follow the Quick Start guide to create an Application on Facebook.

Make a configuration provider

Use the generated access token and your verify token to configure your bot. Most bots live on a single Facebook Page. If that is the case with yours, too, just set these environment variables and skip to the next section:

bash
export ACCESS_TOKEN=EAAAG6WgW...
export APP_SECRET=a885a...
export VERIFY_TOKEN=95vr15g...

If your bot lives on multiple Facebook Pages, make a configuration provider to keep track of access tokens, app secrets and verify tokens for each of them:

ruby
class ExampleProvider "1234"}
    recipient = {"id"=>"5678"}
    timestamp = 1528049653543
    message = {"text"=>"Hello, world"}
    FakeMessage.new(sender, recipient, timestamp, message)
  end
end

Development

After checking out the repo, run bin/setup to install dependencies. You can also run bin/console for an interactive prompt that will allow you to experiment.

Run rspec to run the tests, rubocop to lint, or rake to do both.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/jgorset/facebook-messenger.

Projects using Facebook Messenger

  • Rubotnik is a boilerplate for Facebook Messenger, and a great place to start if you're new to bots.

  • Chatwoot use Facebook Messenger to integrate their customer support bots with, well, Facebook Messenger.

  • Botamp is the all-in-one solution for Marketing Automation via messaging apps.

I love you

Johannes Gorset made this. You should tweet me if you can't get it to work. In fact, you should tweet me anyway.

I love Schibsted

I work at Schibsted Products & Technology with a bunch of awesome folks who are every bit as passionate about building things as I am. If you're using Facebook Messenger, you should probably join us.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubybotfacebookmessengerruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言