AWS Pinpoint Request on Lambda Function using Python - 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.

Related

how to use only strings to pull json data

So I keep running into a issue where json is asking to use a int to find pieces of data in a json response. Below is the code that works though the issue is i want to print every 'name' in the json though id have to change the [0] to 1 and then 2 ect. I tried to increment it though that ran into issue too. This could be just me overlooking something but let me know, thanks.
def BaseTesting(TarLink):
PayloadToSend = {
}
HeadersToSend = { # make sure to change your token at least once every 30 mins
'authorization': '',
'user-agent': ''
}
ReqForFriends = requests.post(TarLink, headers=HeadersToSend, data=PayloadToSend).text
LoadedJSONData = json.loads(ReqForFriends)
print(LoadedJSONData['friends'][0]['name'])
BaseTesting(TarLink="")
JSON
{
"friends":[
{
"name":"test1",
"user_id":"1132",
"type":2,
"display":"true",
},
{
"name":"test2",
"user_id":"2341",
"type":1,
"display":"true",
},
{
"name":"test3",
"user_id":"1234",
"type":2,
"display":"true",
},
}
it seems to work properly
LoadedJSONData = {
"friends":[
{
"name":"test1",
"user_id":"1132",
"type":2,
"display":"true",
},
{
"name":"test2",
"user_id":"2341",
"type":1,
"display":"true",
},
{
"name":"test3",
"user_id":"1234",
"type":2,
"display":"true",
},
]
}
for i in range(0,3):
print(LoadedJSONData['friends'][i]['name']) #test1 test2 test3

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.

$eq invalid syntax Mongo DB

I have a nested json and i want to find a record whose value is equal to a given number. I'm using pymongo in python wih equal operator but getting some errors:
from pymongo import MongoClient
import datetime
import json
import pprint
def connectDatabase(service):
try:
if service=="mongodb":
host = 'mongodb://connecion_string.mlab.com:31989'
database = 'xxx'
user = 'xxx'
password = 'xxx'
client = MongoClient(host)
client.xxx.authenticate(user, password, mechanism='SCRAM-SHA-1')
db = client.xxx
new_posts = [{"author": "Mike", "text": "Another post!",
"tags": [
{
"CSPAccountNo": "414693"
},
{
"CSPAccountNo": "349903"
}]
}]
result=db.posts1.insert_many(new_posts)
print (xxx.posts1.find( {"CSPAccountNo": { $eq: "414693" } } )
except Exception as e:
print(e)
pass
print (connectDatabase("mongodb"))
Error:
File "mongo.py", line 35
print (cstore.posts1.find( {"CSPAccountNo": { $eq: "414693" } } )
^
SyntaxError: invalid syntax
I'm very new to Mongodb. Any help would be appreciated
In Python you have to use Python syntax, not JS syntax like in the Mongo shell. That means that dictionary keys need quotes:
print(cstore.posts1.find( {"CSPAccountNo": { "$eq": "414693" } } )
(Note, in your code you never actually insert the new_posts into the collection, so your find call might not actually find anything.)
It should be
print (xxx.posts1.find( {"tags.CSPAccountNo": { $eq: "414693" } } )

Facebook Messenger bot Generic Template Not Working

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)

How do I properly construct a query using the elasticsearch python API?

I've got some code that looks like this
from elasticsearch import Elasticsearch
client = Elasticsearch(hosts = [myhost])
try:
results = es_client.search(
body = {
'query' : {
'bool' : {
'must' : {
'term' : {
'foo' : 'bar',
'hello' : 'world'
}
}
}
}
},
index = 'index_A,index_B',
size = 10,
from_ = 0
)
except Exception as e:
## my code stops here, as there is an exception
import pdb
pdb.set_trace()
Examining the exception
SearchPhaseExecutionException[Failed to execute phase [query], all shards failed;
And further down
Parse Failure [Failed to parse source [{"query": {"bool": {"must": {"term": {"foo": "bar", "hello": "world"}}}}}]]]; nested: QueryParsingException[[index_A] [bool] query does not support [must]];
The stack trace was huge so I just grabbed snippets of it, but the main error appears to be that "must" is not supported, at least the way I have constructed my query.
I was using this and this for guidance on constructing the query.
I can post a more complete stack trace, but I was hoping someone is able to see a very obvious error that I have made inside the "body" parameter inside the "search" method.
Can anyone see anything that I have clearly done wrong as far as constructing the query body for the python API?
The syntax of the query doesn't look correct to me. Try this:
results = es_client.search(
body = {
"query": {
"bool": {
"must": [
{
"term": {
"foo": {
"value": "bar"
}
}
},
{
"term": {
"hello": {
"value": "world"
}
}
}
]
}
}
},
index = 'index_A,index_B',
size = 10,
from_ = 0
)

Categories