Facebook Messenger bot Generic Template Not Working - python

I have created a Facebook Messenger bot which works fine. I have used the Button Template and Image template, and both work perfectly. But when I try the Generic Template, I get no response. I have simply copy pasted the code from here, by performing the appropriate modifications.
I don't know how to debug. Facebook Messenger gives no output on the messaging box. I am currently running the app via Heroku.
Here is my code:
def send_message(token, recipient):
r = requests.post("https://graph.facebook.com/v2.6/me/messages",
params={"access_token": token},
data=json.dumps({
"recipient":{
"id":recipient
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Welcome to Peter\'s Hats",
"image_url":"http://www.godominion.com/content/images/feature-img-small-appliance-electronics.png",
"subtitle":"We\'ve got the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://peterssendreceiveapp.ngrok.io/view?item=103",
"messenger_extensions": true,
"webview_height_ratio": "tall",
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"
},
"buttons":[
{
"type":"web_url",
"url":"https://petersfancybrownhats.com",
"title":"View Website"
}
]
}
]
}
}
}
}),
headers={'Content-type': 'application/json'})
if r.status_code != requests.codes.ok:
print r.text
I would appreciate any help.
Thank you.
EDIT 1: SOLUTION
I got rid of the issue by commenting out:
"messenger_extensions": true,
and
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"},
I'm sure this is not the correct method. But as I am creating a bot, without actual links, this works.

On the second button, "url":"https://petersfancybrownhats.com" is broken.

Try like this
firstly make a function
def function():
extra_data = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"title": "Any Title",
"image_url": "https://mbtskoudsalg.com/images/road-clipart-journey-3.png",
"subtitle": "Subtitle.",
"buttons": [
{
"type": "web_url",
"title": "View",
"url": "**MAKE SURE TO WHITELIST THIS URL**", # URL
"messenger_extensions": "true",
"webview_height_ratio": "full"
}
]
}
]
}
}
}
# w_message = "Hi there! How may I help you?"
fb_message_template(extra_data["attachment"], "****RECIEVER ID****")
Make another function
import requests
# // Importing User Defined Modules // #
from get_environ_var import get_environ_var
# // Global vars // #
ACCESS_TOKEN = "FB_ACCESS_TOKEN"
def fb_message_template(extra_data, sender_id):
"""This function sends template message to facebook"""
data = {
'recipient': {'id': sender_id},
'message': {
"attachment": extra_data
}
}
qs = 'access_token=' + ACCESS_TOKEN
resp = requests.post('https://graph.facebook.com/v2.6/me/messages?' + qs, json=data)
print(resp.content)

Related

How would I get my response to the Google Assistant via Dialogflow, Actions SDK, Python, etc

I am trying to get my reply to the Google assistant as a string to search it through a Google spreadsheet and return additional information about it. Specifically, I have a Google spreadsheet with two columns, one being for the name of a thing, and another for my rating of it. I'm using ngrok and Flask to get my script's response online. The two parts I'm struggling with are...
(1) Getting my requested thing into the program.
(2) Switching the url of the webhook and/or changing the webhook so that the system can output the final result.
I am a beginner so I'm probably misusing a few terms here but anyways my code is below. I put a bunch of underscores in the places where I thought sensitive information was.
action.json >>
"actions": [
{
"description": "Welcome Intent",
"name": "MAIN",
"fulfillment": {
"conversationName": "jdii ratings"
},
"intent": {
"name": "actions.intent.MAIN",
"trigger": {
"queryPatterns": [
"What did I rate $Test:text",
"Look up $Test:text on my ratings spreadsheet"
]
},
"parameters": [
{
"name": "text",
"type": "Test"
}
]
}
}
],
"conversations": {
"jdii ratings": {
"name": "jdii ratings",
"url": "<_________>",
"fulfillmentApiVersion": 2
}
}
}
program.py >>
import random
import types
import gspread
from flask import Flask
from google.cloud import dialogflow_v2
from oauth2client.service_account import ServiceAccountCredentials
app = Flask(__name__)
wanted_thingy = "Squirt"
def get_requested_thingy_rating(requested_thingy_name):
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name("_______.json", scopes)
file = gspread.authorize(credentials)
sheet = file.open("JDII Ratings API")
requested_thingy_rating_final = 0.0
if not isinstance(requested_thingy_name, types.NoneType):
sheet = sheet.sheet1
thingy_list = sheet.col_values(1)
ratings_list = sheet.col_values(2)
requested_thingy_rating = 0.0
if requested_thingy_name in thingy_list:
thingy_pos = thingy_list.index(requested_thingy_name)
requested_thingy_rating = ratings_list[thingy_pos]
requested_thingy_rating_final = str(requested_thingy_rating)
# split_string = ready_string.split('\'')
# requested_thingy_rating_final = split_string[1]
print(requested_thingy_rating_final)
return requested_thingy_rating_final
#app.route("/start", methods=['POST', 'GET', 'PUT'])
def main():
response = {
"expectUserResponse": True,
"expectedInputs": [
{
"inputPrompt": {
"richInitialPrompt": {
"items": [
{
"simpleResponse": {
"textToSpeech": "What would you like to look up?",
"displayText": "What would you like to look up?"
}
}
]
}
},
"possibleIntents": [
{
"intent": "actions.intent.TEXT"
}
]
}
]
}
response_text = json.dumps(response)
return response_text
#app.route("/webhook", methods=['POST', 'GET', 'PUT'])
def main2():
global wanted_thingy
wanted_thingy_final = str(wanted_thingy)
wanted_thingy_rating = get_requested_thingy_rating(wanted_thingy_final)
print(wanted_thingy)
string = f"You rated {wanted_thingy} a {wanted_thingy_rating} out of ten."
response2 = {
"expectUserResponse": False,
"finalResponse": {
"richResponse": {
"items": [
{
"simpleResponse": {
'ssml': f'<speak>{string}</speak>'
}
}
]
}
}
}
response_text = json.dumps(response2)
return response_text
app.run()

Discord clicking button using api and requests in python not working

I have made this code to make a user interact with a button of my bot’s message, but i am unable to make it work. Please help.I get the following error:
{"code": 50035, "errors": {"session_id": {"_errors": [{"code": "BASE_TYPE_REQUIRED", "message": "This field is required"}]}}, "message": "Invalid Form Body”}
header = {
'authorization': auth
}
r = requests.get("https://discord.com/api/v9/channels/<channel_id>/messages", headers = header)
message = json.loads(r.text)[0]
data = {
"type": 3,
"guild_id": '<guild_id>',
"channel_id": '<channel_id>',
"message_id": message['id'],
"application_id": '<bot_id>', #the id of the bot to which i want to interact
"data": {
"component_type": 2,
"custom_id": message['components'][0]['components'][2]['custom_id'] #gets the custom_id of the button to interact
}
}
r = requests.post('https://discord.com/api/v9/interactions', json = data, headers = header)
Turns out, I need to add a session_id under the data dict, the problem got solved! Thanks furas for your help!
The code now:
data = {
"type": 3,
"guild_id": '<guild_id>',
"channel_id": '<channel_id>',
"message_id": message['id'],
"session_id": '<session_id>', #if you don't know the string, a random string worked for me
"application_id": '<bot_id>', #the id of the bot to which i want to interact
"data": {
"component_type": 2,
"custom_id": message['components'][0]['components'][2]['custom_id'] #gets the custom_id of the button to interact
}
}

TF400898: An Internal Error Occurred. Activity Id: 1fc05eca-fed8-4065-ae1a-fc8f2741c0ea

i’m trying to push files into git repo via azure API but getting activity_id error. I followed their documentation and trying to add simple file in my repo.
Here is my code:
import requests, base64
pat_token = "xxxx-xxxxx-xxxx"
b64Val = base64.b64encode(pat_token.encode()).decode()
payload = {
"refUpdates": [
{
"name": "refs/heads/main",
"oldObjectId": "505aae1f15ae153b7fc53e8bdb79ac997caa99e6"
}
],
"commits": [
{
"comment": "Added task markdown file.",
"changes": [
{
"changeType": "add",
"item": {
"path": "TimeStamps.txt"
},
"newContent": {
"content": "# Tasks\n\n* Item 1\n* Item 2",
"contentType": "rawtext"
}
}
]
}
]
}
headers = {
'Authorization': 'Basic %s' % b64Val,
'Content-Type': 'application/json',
}
params = (
('api-version', '6.0'),
)
response = requests.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repo}/pushes', headers=headers, data=payload, params=params)
Anyone knows how to solve this issue? I have also added this issue on their developer community
I’ve fixed that error, actually the payload was not in json format so i have to make it as json and after that it worked fine.
Like this
response = requests.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repoId}/pushes', headers=headers, params=params, data=json.dumps(payload))

AWS Pinpoint Request on Lambda Function using Python 3.6

I tried to using Pinpoint services in my Lambda Function using Python Language. But I am facing time out error once Executed my function. Here is my Lambda Function source code.
import json
import boto3
client = boto3.client('pinpoint')
def trigger(event, context):
print("---------1----------------")
payload = {
'TraceId': 'sadfasdf',
'Context': {
'string': 'string'
},
'MessageConfiguration': {
'GCMMessage': {
'RawContent': ""
}
},
'TemplateConfiguration': {
'PushTemplate': {
'Name': 'coll-1-en'
}
},
'Users': {
"id": {
"Substitutions":{
"subject": ["string"],
"id": ["120913"]
}
}
}
}
try:
print("---------2----------------")
response = client.send_users_messages(
ApplicationId='my_aws_pinpoint_services_project.id',
SendUsersMessageRequest=payload
)
print("---------3----------------")
data = response.read()
print(data.decode("utf-8"))
return response
except Exception:
return False
I am not sure what is the issue from my code. So I have inserted print("-------") to find out the error lines.
The codes didn't executed since response = client.send_users_messages( line. So I was sure the client.send_users_messages had an issue. But I am not sure what is wrong in this line. Pls help me to fix this issue. I attached the screenshot of the Test result.

AWS Pinpoint Request on Lambda Function using Python

I tried to using pinpoint services in my Lambda Function using Python Language.
But I am facing time out error once Executed my function.
Here is my lambda function source code.
import json
import boto3
client = boto3.client('pinpoint')
def trigger(event, context):
print("---------1----------------")
payload = {
'TraceId': 'sadfasdf',
'Context': {
'string': 'string'
},
'MessageConfiguration': {
'GCMMessage': {
'RawContent': ""
}
},
'TemplateConfiguration': {
'PushTemplate': {
'Name': 'coll-1-en'
}
},
'Users': {
"id": {
"Substitutions":{
"subject": ["string"],
"id": ["120913"]
}
}
}
}
try:
print("---------2----------------")
response = client.send_users_messages(
ApplicationId='my_aws_pinpoint_services_project.id',
SendUsersMessageRequest=payload
)
print("---------3----------------")
data = response.read()
print(data.decode("utf-8"))
return response
except Exception:
return False
I am not sure what is the issue from my code.
So I have inserted print("string") to find out the error lines.
The codes didn't executed since response = client.send_users_messages( line.
So I was sure the client.send_users_messages had an issue.
But I am not sure what is wrong in this line.
Pls help me to fix this issue.
I attached the screenshot of the Test result.

Categories