jgorset / facebook-messenger Goto Github PK
View Code? Open in Web Editor NEWDefinitely the best way to make Bots on Facebook Messenger with Ruby
License: MIT License
Definitely the best way to make Bots on Facebook Messenger with Ruby
License: MIT License
How do you send and receive quick replies?
2016-11-12T04:54:11.504134+00:00 app[web.1]: [3c29e03d-8b90-4f57-b716-95ba002aac1c] Facebook::Messenger::Bot::RecipientNotFound ((#100) No matching user found):
2016-11-12T04:54:11.504209+00:00 app[web.1]: [3c29e03d-8b90-4f57-b716-95ba002aac1c]
2016-11-12T04:54:11.504260+00:00 app[web.1]: [3c29e03d-8b90-4f57-b716-95ba002aac1c] app/bots/product_bot.rb:78:in `ask'
2016-11-12T04:54:11.504263+00:00 app[web.1]: [3c29e03d-8b90-4f57-b716-95ba002aac1c] app/bots/product_bot.rb:168:in `block in <top (required)>'
2016-11-12T04:54:11.504459+00:00 app[web.1]: [3c29e03d-8b90-4f57-b716-95ba002aac1c] Error occurred while parsing request parameters.
2016-11-12T04:54:11.504461+00:00 app[web.1]: Contents:
2016-11-12T04:54:11.504461+00:00 app[web.1]:
2016-11-12T04:54:11.504462+00:00 app[web.1]:
2016-11-12T04:54:11.504645+00:00 app[web.1]: Error during failsafe response: no implicit conversion of nil into String
2016-11-12T04:54:11.504646+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/http/parameters.rb:71:in `rescue in parse_formatted_parameters'```
I just tried this on rails console, and don't see the page events subscribed to my app.
Facebook::Messenger.config.access_token = @access_token
Facebook::Messenger.config.app_secret = @app_secret
Facebook::Messenger.config.verify_token = @verify_token
Facebook::Messenger::Subscriptions.subscribe
=> true
Is it working? I want to be able to programmatically do this..
The Facebook API support the :sender_action to be passed to the .deliver method, but I get an error when I add that.
Hi thanks for making this gem. this is absolutely wonderful.
anyway i just try to play with the gem when i tried to run apps i got an error
Facebook::Messenger::Error: An active access token must be used to query information about the current user.
i wonder if my folder structure file is correct
https://github.com/ferryphang/SleepingForest
./bot.rb
./facebook/messenger.rb
./config.ru
This is my code when i try to reply a message
include Facebook::Messenger
Bot.on :message do |msg|
msg.reply({text: 'lala'})
end
But when i message my bot it raise error
NoMethodError (undefined method `reply' for #<Facebook::Messenger::Incoming::Message:0x007fb5f4b9aa30>):
Hi,
I am trying to get message from the user with message buttons. I read that block on Readme
# Messages with buttons
# The human may require simple options to communicate:
Bot.deliver(
recipient: {
id: '45123'
},
message: {
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' }
]
}
}
}
)
and I think id
means in here Facebook Page Id. Am I right? I checked the Facebook Messenger Documentation. However, I set the my page id, I see some errors on my Rails server logs. My sending message code is
Bot.on :postback do |postback|
if postback.payload == 'CLICK_GET_STARTED'
Bot.deliver(
recipient: {
id: postback.recipient
},
message: {
attachment: {
type: "template",
payload: {
template_type: "button",
text: "Are you okey?",
buttons: [
{ type: 'postback', title: "Yes", payload: "YES" },
{ type: 'postback', title: "No", payload: "NO" }
]
}
}
}
)
end
end
And the error is Facebook::Messenger::Bot::RecipientNotFound - (#100) Parameter recipient[id]: Invalid id: {"id":"my_page_id"}:
After that error I checked my page with that URL https://www.facebook.com/profile.php?id=my_page_id
I saw my page.
Where is the wrong in that code? Any idea?
Cheers.
This looks like the best facebook messenger bot api for ruby. To make it even better I suggest you include examples of how to use it within Rails. Perhaps how to mount the rack application within your rails app and where to place your ruby files that handle bot events (even though they can place it anywhere, they want to know what the standard most elegant place is). A simple controller as used in this gem seems nice: https://github.com/jun85664396/messenger-bot-rails
Am trying to trigger a message within a rails controller and not having any luck. Is this possible?
class OrdersController < ApplicationController
include Facebook::Messenger
def checkout
@order = Order.find(params[:id])
result = Braintree::Transaction.sale()
if result.success?
Bot.deliver(
recipient: {
id: '12345'
},
message: {
text: 'Human?'
}
)
end
end
end
If I add the following line to my controller logger.info Facebook::Messenger::Configuration.access_token
I can see that it is loading the config and returning the access token I have set up.
So seems to be something odd with Bot.deliver
. I've also tried Facebook::Messenger::Bot.deliver
and no success either.
When I test in the console it also returns nil
2.2.1 :050 > Facebook::Messenger::Bot.deliver(recipient: { id: '12345' }, message: { text: "Hello" })
=> nil
getting following errors:
undefined method `app_secret=' for Facebook::Messenger::Configuration:Module (NoMethodError)
the following after commenting out app_secret
uninitialized constant Welcome (NameError)
Things that need improvement:
Without these improvements only really simple apps can be implemented with this gem.
Configuration: because the configuration is managed globally (e.g Facebook::Messenger.config.access_token=
), instead of per instance, it's not possible to use this gem in the scenario where the application might connect at the same time to multiple pages. For instance, think about using something like Sidekiq.
Ideally, the subscription code should be something like
subscription = Facebook::Messenger::Subscriptions.new(
access_token: '...',
app_secret: '...',
verify_token: '...'
)
subscription.create
Message delivery: again, because we can't guarantee one access token in a particular delivery, the global access token could leak into a delivery for another page. We should be able to explicitly pass access_token
in the deliver
method.
Is it something the admins are in accordance?
I'm not sure I'll have the time myself to open a PR soon, but I'll leave this issue registered here and try to get to it.
Hi,
I am trying to send text message to bot via iPad mini. After bot sends a text message, user reads the message and the program should visit "read" block. It works on web and mobile messenger but not working on iPad messenger. Have you faced same problem?
Cheers.
This bug:
https://developers.facebook.com/bugs/1751749508372552/
Has broken Facebook::Messenger::Welcome.set as the API call now only supports one call_to_action with a payload string:
https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button
Fixed locally by changing welcome_setting_for
to call_to_actions: payload ? [payload] : []
allowing us to call Facebook::Messenger::Welcome.set payload: "HELLO"
without error.
Hi,
since v. 0.11.0 Facebook variables are defined in global variables with predefined names, as explained in documentation:
export ACCESS_TOKEN=EAAAG6WgW...
export APP_SECRET=a885a...
export VERIFY_TOKEN=95vr15g...
and an older way of defining them seems to be deprecated:
Facebook::Messenger.configure do |config|
config.access_token = ENV["ACCESS_TOKEN"]
config.app_secret = ENV["APP_SECRET"]
config.verify_token = ENV["VERIFY_TOKEN"]
end
However, I use another names for facebook vars - how can I still manually define them?
thanks!
UPD: with defining FB variables as expected, the following error fired up:
/facebook-messenger-0.11.0/lib/facebook/messenger/thread.rb:17:in `set': missing keyword: access_token (ArgumentError)
(adding it here as seems to be somehow related)
Hi,
My bot has a 'Get Started Button'. After the user clicks it, I check the payload in a postback and the conversation starts with a postback message. Generally bot and the user talk on message texts. In sometime user can cancel the conversation and return the beginning of the chat. How should I do it?
My point is that the user types "Cancel" and I can reply with my first postback the user text message.
As the API is growing at Facebook, it appears some new error codes are being returned.
We've been working with the API for the last weeks, and I'm almost sure that when someone deleted a conversation with a bot, Facebook would return 100 error in response to the Bot.deliver
action, a Facebook::Messenger::Bot::RecipientNotFound
.
Now, apparently it is returning a new error code, 200, per the API:
"This person isn't receiving messages from you right now."
I'm relying on these errors to keep track of the real bot users (I destroy those who don't receive messages), so it would be cool either to upgrade the gem with the recently added error responses (https://developers.facebook.com/docs/messenger-platform/send-api-reference#response) or wrap the errors in the exceptions in a way that the code was still available for us to check, e.g., see: https://github.com/ryanb/cancan/blob/master/lib/cancan/exceptions.rb#L35.
Any thoughts on this?
Thanks in advance.
When facebook push /webhook in logs show Can't verify CSRF token authenticity
I have a rails application. The webhook callback sometimes is a bit slow to return a 200 OK HTTP response, as it has to interact with other APIs before. This makes facebook send the app duplicated requests.
How can I send back as fast as possible 200 OK HTTP message once i've received a message in Bot.on :message do |message|
?
Thanks
Hi all,
thank you for your hard work on this messenger bot gem.
I'm just starting using it. Can't wait to spend time coding the bot.
But, I must say that it was a bit hard, at the beginning to configure the bot.
I didn't really know where to put my code (like the Access Token bot challenge... etc).
I think, it would be nice to just give a classic pattern configuration, for easy set up.
Something like :
Here is an easy configuration pattern on your rails app:
Only 3 files to create/edit:
app/bot/bot.rb
=> that's where the token check challenge and all the bot code goes.config/initializers/bot.rb
=> where the loading code in dev/test environments goes.config/routes.rb
=> that's where you add the route/mount code for 'bot'.Just to make it simple for beginners.
Hi, I am trying to set up the post backs in my app and have been unsuccessful. Also, nothing is showing in the logs, any ideas?
How can I detect FB ref? https://developers.facebook.com/docs/messenger-platform/referral-params
Hi. I want to get message sender name instead of id? For example message.sender.name
Is it possible?
I'm getting error saying 'An active access token must be used to query information about the current user' my code is here.
Facebook::Messenger.config do |config|
config.ACCESS_TOKEN = 'EAAX9oMZBEIAMBAFBgGPw2C7SymERdXSa7qyQjx4hwbZA6Mn03qVMIeOENGsotu659MOZCtKSujSVvPoZANkV5Cy5IscFOCEqH7EAak8SY9sJ2FhldWNcZBvLiUpsMYmbTYoIkyYDwWLA1HPoXdLrTz1HmJFqhg7bno2NXEmA4bAZDZD'
config.VERIFY_TOKEN = 'my_voice_is_my_password_verify_me'
config.APP_SECRET = "8bf7d61b66b1a6ad16f7c630e8febb92"
end
Facebook::Messenger::Subscriptions.subscribe
Please help
Hi,
the following error raises every time I am sending a message:
NoMethodError (undefined method `dig' for #Hash:0x007fa04e5762a0):
facebook-messenger (0.11.0) lib/facebook/messenger/server.rb:98:in `generate_hmac'
Gem version 0.11.0
Rails 5.0.0.1
Ruby 2.2.4
Hi,
I have setup a simple bot and noticed that on your tests you are checking for attachments, but when I try to use it in code I get an error
NoMethodError: undefined method `attachments' for #<Facebook::Messenger::Incoming::Message:0x007fa4393f5dd8>
Also, it seems that this always returns false message.respond_to? :attachments
. Any suggestions?
Thanks
/home/kushal/.rvm/gems/ruby-2.3.1/gems/facebook-messenger-0.10.0/lib/facebook/messenger/thread.rb:36:in `raise_errors': An active access token must be used to query information about the current user. (Facebook::Messenger::Thread::Error)
from /home/kushal/.rvm/gems/ruby-2.3.1/gems/facebook-messenger-0.10.0/lib/facebook/messenger/thread.rb:21:in `set'
from /home/kushal/AcquireTech/shopick/app/bot/shopick.rb:119:in `<top (required)>'
from /home/kushal/.rvm/gems/ruby-2.3.1@global/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:457:in `load'
from /home/kushal/.rvm/gems/ruby-2.3.1@global/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:457:in `block in load_file'
from /home/kushal/.rvm/gems/ruby-2.3.1@global/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:647:in `new_constants_in'
from /home/kushal/.rvm/gems/ruby-2.3.1@global/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:456:in `load_file'
from /home/kushal/.rvm/gems/ruby-2.3.1@global/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:354:in `require_or_load'
Hi while setting the thread configuration, i am getting above error and rails exits. I have tried to regenerate the token and update token but that isn't helping.
P.S Earlier it was working but suddenly stopped working
Sorry. This is probably more of a rails question than one for this repository, but I'm not sure where to go about finding an answer.
I'm able to follow the installation guide and mount the Facebook Messenger engine without any problems. What should I do instead if I want to be able to host multiple instances of the same bot? This will be separate bots (using the same code) but with different access tokens, app secret, etc..
The only way that makes sense to me is to mount separate bots doing something like this..
mount Facebook::Messenger::Server, at: 'bot/:unique_id'
Is this the way to do it? Basically having a separate webhook per bot as a way to identify each bot?
This is not an issue with gem but issue with myself. I didn't know how this errors has been received. I have use just given code below and setup bot. Facebook posts to my server but i get message in console as "Ignoring message, no hook registered". Can you please tell me the reason and close issue. Thank in Advance
#app/bot.rb
require 'facebook/messenger'
include Facebook::Messenger
Bot.on :message do |message|
Bot.deliver(
recipient: message.sender,
message: {
text: 'Hello, human!'
}
)
end
Bot.on :optin do |optin|
Bot.deliver(
recipient: optin.sender,
message: {
text: 'Ah, human!'
}
)
end
Bot.on :delivery do |delivery|
puts "Human was online at #{delivery.at}"
end
Facebook::Messenger::Thread.set(
setting_type: 'greeting',
greeting: {
text: 'Welcome to your new bot overlord!'
}
)
Hi, is there any support to just send reply indicator without replying to a message?
Hi.
I migrated my project from RAILS 4.2.6 to RAILS 5.0.0.
I see an error when I try start server on RAILS 5.0.0, work well on RAILS 4.2.6.
Error:
<top (required)>: undefined method 'on' for Bot:Module (NoMethodError)
from /home/vitalii/.rvm/gems/ruby-2.3.1@cai_bot/gems/activesupport-5.0.0/lib/active_support/dependencies.rb:293:in 'require'
Code:
include Facebook::Messenger
Bot.on :optin do |optin|
recipient(optin)
Bot.deliver(
recipient: optin.sender,
message: {
text: 'Welcome message'
}
)
end
I've been coming across this error while trying to change the application to play nicely with autoloading in rails (it was hacked together with requires which started causing some problems).
ArgumentError (A copy of Bot::IncomingRequest::FacebookMessenger has been removed from the module tree but is still active!):
Have you got any advice on what I should do?
We should facilitate for setting welcome messages. Maybe something like Facebook::Messenger::Welcome.set [...]
?
Have you ever seen anything like this, when using this in a Rails project?
NoMethodError (undefined method `bytesize' for nil:NilClass):
rack (1.6.4) lib/rack/utils.rb:369:in `bytesize'
rack (1.6.4) lib/rack/utils.rb:439:in `secure_compare'
facebook-messenger (0.5.0) lib/facebook/messenger/server.rb:57:in `integrity?'
facebook-messenger (0.5.0) lib/facebook/messenger/server.rb:41:in `receive'
facebook-messenger (0.5.0) lib/facebook/messenger/server.rb:19:in `call'
facebook-messenger (0.5.0) lib/facebook/messenger/server.rb:11:in `call'
Great gem! Thanks for sharing.
I am trying to implement this gem inside an existing Sinatra app. How should I change my config.ru
to run my app and also the Facebook::Messenger::Server
?
# config.ru - of my existing app
require 'rubygems'
require 'sinatra'
require './my_app'
run Sinatra::Application
# config.ru - for your gem
require 'facebook/messenger'
require_relative 'bot'
run Facebook::Messenger::Server
Hi, I would like to proxy calls to "https://graph.facebook.com/v2.6/me" which is the value for base_uri.
Looks like it is set as a read only attr since I cannot change it using Bot.base_uri.
Suggestions?
This could also help to instrument the client calling Facebook.
Hi.
I can't understand how to use 'Thread'.
I'm tried add greeting message to 'Bot.on :optin', but when I interacts to chat (after delete chat on my phone) I don't see greeting message.
Please explain, how to use thread.
Hi,
I tried to include facebook-messenger according to the documentation but I get error uninitialized constant Bot (NameError)
when I start the Rails server. How should I fix it?
How can I return the senders first name, last name, and gender from the facebook graph api when a message is received?
My bot stops responding after some body sends it like. For example it works great with text but when you click the like button on the messenger it stops and after the clicking the like button, bot still not responds any text. So let me be more clear; 1- Human 2- Bot
1- SOME TEXT
2- RESPOND(done)
1-SENDING LIKE ON MESSENGER
2-NO RESPOND
1-SOME TEXT
2-NO RESPOND
.....
2- NO RESPOND
Hi,
I'm trying to send an image attachment as part of a bot response. The image is definitely published and visible when I go to the URL, but when I use Bot.deliver(...) i get this error.
Facebook::Messenger::Bot::RecipientNotFound ((#100) Failed to fetch the file from the url)
Any ideas what's wrong?
I instrumented the webhook URL. I see two entries for every one input from a user.
The payload appears to be exactly the same in terms of time stamp and so forth. So I am assuming it's not the user or the client submitting something twice.
It appears to be somewhat intermittent as well. Sometimes only one input will be processed. But mostly it is a duplicate or triplicate.
I was able to get through about 90% of the installation process. Facebook accepted the webhook, but when I go to message my bot, I don't get a response, so I looked at the logs on my server and I'm getting this.
NoMethodError (undefined method `fetch' for nil:NilClass):
Any clue what's wrong?
Hi,
It's should be a silly question but I cannot handle the problem. Should I separate the text messages? How can I teach the bot which message it must answer.
For example, B: Bot, U: User
B: Where are you from?
U: I am from Turkey.
B: Which city did you born in Turkey?
U: I was born in Istanbul.
B: When did you born in Istanbul?
U: in 1986.
In that example the bot should understand the sequence of the messages. It should answer the questions in order.
It's just an example. I can use regex in here but my scenario is more complex than the example. I tried to use metadata
but I see that I cannot get from user message. I made a class which have some attributes message_id, message_text
and previous_message_id
. I initialized the class when user writes an answers but in that time bot answered the all questions :/ It have should quited the :message
block.
My point is that bot should know the next right question after user text message.
Cheers.
I set up a test app per the instructions and have a puts message in the bot.rb
file, but I don't see messages.
I noticed that I don't need to provide the web-hook as part of it -- assuming that providing the app ID is allowing your facebook server to listen for a message?
How can I identify the problem?
Is it possible to get the name of the user who is interacting with the bot?
When I started rails server, I got this error :
facebook/messenger/thread.rb:36:in `raise_errors': An active access token must be used to query information about the current user. (Facebook::Messenger::Thread::Error)
This's my thread code :
include Facebook::Messenger
Facebook::Messenger::Thread.set(
setting_type: 'greeting',
greeting: {
text: 'Hi, {{user_full_name}}. Welcome to your new bot!'
}
)
So, I followed Facebook example, used curl
:
curl -X POST -H "Content-Type: application/json" -d '{
quote> "setting_type":"greeting",
quote> "greeting":{
quote> "text":"Timeless apparel for the masses."
quote> }
quote> }' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=EAANG4r..."
{"result":"Successfully updated greeting"}%
This is my configure file :
Facebook::Messenger.configure do |config|
config.access_token = 'EAANG4r...'
...
end
Bug ?
What would be a good way to handle 10+ elements?
Say for example,
elems = Element.all
elements = carts.map do |element|
{
title: element.name,
subtitle: element.description,
buttons: [
{
type: 'postback',
title: 'View element',
payload: {
id: 'view_element',
element_id: element.id
sender: sender['id']
}.to_json
}
]
}
end
Is it possible to send a message using the phone number of the user?
Hi,
I am trying to develop a bot in my existing Rails project. I created a bot on Facebook developer page and a webhook with ngrok. When I try to post from the Facebook to bot I see Ignoring message (no hook registered)
error with Cannot render console from 173.252.90.106! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255"
Do you have any idea about that?
Cheers.
Hi, I am using your lib for my "quality of life" bot framework - currently switching from
https://github.com/netguru/messenger-ruby
to your lib - looks way better and the other one does not accept pull requests & issues.
Currently I have a strange problem with the recipent id's - I use your example code but it seems that it somhow has the wrong id :)
any ideas?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.