I am new to messenger platform, I did search a lot on the internet how to make a "get started" button on messenger in python but there is no answer.
Below is my code:
def send_get_started(bot,recipient_id):
button = {
"get_started":{
"payload" : "first_coming"
}
}
bot.send_raw(button)
the send_raw function here I get from bot.py in pymessenger2 on python
which is here (also the code below)
def send_raw(self, payload):
request_endpoint = '{0}/me/messages'.format(self.graph_url)
response = requests.post(
request_endpoint,
params=self.auth_args,
data=json.dumps(payload, cls=AttrsEncoder),
headers={'Content-Type': 'application/json'})
result = response.json()
return result
Of course it did not work, I think I misunderstand somewhere, could somebody show me my problem?
Thanh you so much.
The endpoint should be:
https://graph.facebook.com/v2.6/me/messenger_profile
You could see this in the reference: Get Started Reference
The endpoint is wrong. Your request is using the '/messages' path when it should be using '/thread_settings'
When setting the 'Get Started' button or the Greeting you need to use the endpoint
https://graph.facebook.com/v3.0/me/thread_settings
Related
I am posting a GET request to this URL with a bearer token:
http://api.viagogo.net/catalog/events?page_size=1000&sort=resource_version&min_resource_version=75939827358
It returns results in Postman as expected.
When i call the same api with same token in code (C#), i get unauthorized 401 response.
This is my code:
var eventsUri = new Uri(eventsUrl);
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Add("User-Agent", "App Name");
var eventResponseFromHttp = await httpClient.GetAsync(eventsUri);
var responseContent = await eventResponseFromHttp.Content.ReadAsStringAsync();
var eventsFromHttps = JsonConvert.DeserializeObject<EventResponse>(responseContent);
But the weird thing is this:
If i call the same api without sort and min_resource_version query string parameters from code, it returns the results with 200:
http://api.viagogo.net/catalog/events?page_size=1000
I have no idea whats going on here. This is happening in a .Net Framework 4.7 application.
Any help is appreciated. Thanks.
UPDATE:
The same url with same token returns 200 and results using Python.
I've been trying to get this to work for the past 4 hours with no luck, so here's the problem:
I have this class:
class Bitly:
def __init__(self, api_token):
self.apiToken = api_token
self.header = {'Content-Type':'application/json',
'Authorization' : 'Bearer {}'.format(self.apiToken)
}
def shorten(self, longURL):
payload = {"long_url": longURL}
url = "https://api-ssl.bitly.com/v4/shorten"
return requests.post(url, headers=self.header, data=payload)
that, after being initialized with a valid token, is supposed to return the response JSON with the shortened link inside when calling the shorten method.
Instead i keep getting this response:
{"message":"UNPROCESSABLE_ENTITY","resource":"bitlinks","description":"The JSON value provided is invalid."}
And i can't figure out what i'm doing wrong with the payload for it to give me this message.
I'm sure it's a stupid error but i'm pretty new to this, so have mercy.
Nevermind, i solved it, here's the solution for future reference:
instead of using
data=payload
use
json=payload
Yes, it was that simple.
UPDATE
For me the Problem got fixed as soon as I was putting "encoding: URLEncoding(destination: .queryString)" in my request. Maybe this helps somebody else. link
I struggled the whole day to find the problem in my Alamofire PUT Request or the Flask Restful API. Request like GET, DELETE and POST are working fine with Alamofire, except the PUT Request.
When I'm using PUT Requests in combination with Postman and Flask-Restful everything is also working fine. But as soon as I'm trying to achieve the same Result with Alamofire, I'm not getting any parameters in Flask. I tried to illustrate this in the code examples.
So in short my example illustrates the following:
DELETE Request(Same with GET and POST)
Postman: success
Alamofire: success
PUT Request
Postman: success
Alamofire: failure (parameter dictionary empty in Flask-Restful)
Here is my Python Code [API Server]:
from flask import Flask, request, jsonify
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app)
class Stackoverflow(Resource):
def delete(self):
print(request.args)
if request.args.get('test-key') is None:
return jsonify({"message": "failure"})
else:
return jsonify({"message": "success"})
def put(self):
print(request.args)
if request.args.get('test-key') is None:
return jsonify({"message": "failure"})
else:
return jsonify({"message": "success"})
api.add_resource(Stackoverflow, '/stackoverflow')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
If I'm using Postman, I get this result (like expected):
Result in Postman
But now I'm trying to do the same with Alamofire in Swift. Same Server, nothing changed.
SWIFT demo Code [IOS APP]:
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view
simplePUTRequest()
simpleDELETERequest()
}
func simplePUTRequest(){
AF.request("http://localhost:5000/stackoverflow", method: .put, parameters: ["test-key":"testvalue"])
.validate(statusCode: 200..<300)
.responseJSON { response in
if let data = response.data {
print("Result PUT Request:")
print(String(data: data, encoding: .utf8)!)
//print(utf8Text)
}else{
}
}
}
func simpleDELETERequest(){
AF.request("http://localhost:5000/stackoverflow", method: .delete, parameters: ["test-key":"testvalue"])
.validate(statusCode: 200..<300)
.responseJSON { response in
if let data = response.data {
print("Result DELETE Request:")
print(String(data: data, encoding: .utf8)!)
//print(utf8Text)
}else{
}
}
}
Xcode Console:
Result PUT Request:
{
"message": "failure"
}
Result DELETE Request:
{
"message": "success"
}
python Console (both Alamofire Requests):
ImmutableMultiDict([])
127.0.0.1 - - [15/Jun/2019 21:17:31] "PUT /stackoverflow HTTP/1.1" 200 -
ImmutableMultiDict([('test-key', 'testvalue')])
127.0.0.1 - - [15/Jun/2019 21:17:31] "DELETE /stackoverflow?test-key=testvalue HTTP/1.1" 200 -
As you can see, I'm getting the success message only while using the DELETE method.
Till now I tried using different encodings like URLEncoding.httpbody and URLEncoding.default, but nothing really helped.
For me it seems like it's a Alamofire/Swift Problem, because in Postman the same request method is working fine.
I would really appreciate your help, because I'm stuck and don't know anything further to do. I hope I didn't misunderstood something essential.
Thank you in advance!
I am currently using the same version AlamoFire, and when I use the PUT method, I use it as follows:
let request = AF.request(url, method: .put, parameters: ["uid": uid],
encoding: JSONEncoding.default, headers: headers)
request.responseJSON(completionHandler: { response in
guard response.error == nil else {
//Handle error
}
if let json = response.value as? [String: Any]
// Handle result.
}
The only difference to your post is that I used the encoding option. You can try to put the option and see what happens.
It looks like your server is expecting your PUT parameters to be URL form encoded into the URL. You may be hitting the version of the request method that uses JSON encoding by default, so adding encoder: URLEncodedFormParameterEncoder.default at the end of your request call should fix that. A future release will make that the default, as it's safe across all request types.
If that's not the issue, I suggest you investigate more closely to see what the differences between the requests may be. Since you control the server you should have easy access to the traffic.
I'm trying to get the payload from the quick replies that I'm using to create a chatbot on Messenger, but I keep getting this error: KeyError: 'quick_reply'. I am using python to create bot. I've tried everything imaginable such as:
#app.route('/', methods=['POST'])
def webhook():
data = request.get_json()
log(data)
if data["object"] == "page":
for entry in data["entry"]:
for messaging_event in entry["messaging"]:
if messaging_event.get("message"):
recieved(messaging_event)
message_text = messaging_event["message"]["quick_reply"]["payload"]
if messaging_event.get("delivery"):
pass
if messaging_event.get("optin"):
pass
if messaging_event.get("postback"):
pass
return "ok", 200
But each one keeps giving me the same problem. I've looked online and at docs but there seems to be no answer. Any insights?
When a Quick Reply is tapped, a text message will be sent to your webhook Message Received Callback. The text of the message will correspond to the title of the Quick Reply. The message object will also contain a field named quick_reply containing the payload data on the Quick Reply.
so quick reply payload will be like message.quick_reply.payload
I am struggling getting a Rest API Post to work with a vendor api and hope someone can give me a pointer.
The intent is to feed a cli command to the post body and pass to a device which returns the output.
The call looks like this : ( this works for all other calls but this is different because of posting to body)
def __init__(self,host,username,password,sid,method,http_meth):
self.host=host
self.username= username
self.password= password
self.sid=sid
self.method=method
self.http_meth=http_meth
def __str__(self):
self.url = 'http://' + self.host + '/rest/'
self.authparams = urllib.urlencode({ "session_id":self.sid,"method": self.method,"username": self.username,
"password": self.password,
})
call = urllib2.urlopen(self.url.__str__(), self.authparams).read()
return (call)
No matter how I have tried this I cant get it to work properly. Here is an excerpt from the API docs that explains how to use this method:
To process these APIs, place your CLI commands in the HTTP post buffer, and then place the
method name, session ID, and other parameters in the URL.
Can anyone give me an idea of how to properly do this. I am not a developer and am trying to learn this correctly. For example if I wanted to send the command "help" in the post body?
Thanks for any guidance
Ok this was ridiculously simple and I was over-thinking this. I find that I can sometimes look at a much higher level than a problem really is and waist time. Anyway this is how it should work:
def cli(self,method):
self.url = ("http://" + str(self.host) + "/rest//?method=" +str(method)+ "&username=" +str(self.username)+ "&password=" +str(self.password)+ "&enable_password=test&session_id="+str(self.session_id))
data="show ver"
try:
req = urllib2.Request(self.url)
response = urllib2.urlopen(req,data)
result = response.read()
print result
except urllib2.URLError, e:
print e.reason
The cli commands are just placed in the buffer and not encoded....