I'm trying to remove users from an audience in the Facebook Ads API, using the delete_users function.
This is my code so far:
'''
from collections import UserList
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.customaudience import CustomAudience
from facebook_business.api import FacebookAdsApi
from facebook_business.api import FacebookRequest
access_token = 'XXX'
id = 'XXX'
api = FacebookAdsApi.init(access_token=access_token)
fields = []
params = {
'name': 'Test Audience',
'subtype': 'CUSTOM',
'description': 'People who purchased on my website',
'customer_file_source': 'USER_PROVIDED_ONLY',
}
print ( AdAccount(id).create_custom_audience(
fields=fields,
params=params,
) )
fields = []
params = {
'name': 'Test Audience',
'payload': hashed_list_of_emails
}
CustomAudience.delete_users(
self
fields=fields,
params=params,
method='DELETE',
endpoint='/users',
)
'''
I am receiving an error which tells me to replace self with node_id=self['id'], but I am unclear on what this is. I am also unclear on which part of the delete_users function should contain the audience_id, and where to insert the payload of the list of hashed email to remove from the audience.
Related
The documentation of the API is here, and I try to implement this line in python
//retrieve entries created on a specific day (use the date_created field)
//this example returns entries created on September 10, 2019
https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/10/2019","operator":"is"}]}
But when I try to do with python in the following code, I got an error:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
url = 'https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}'
r = session.get(url)
print(r.content)
The error message is :
ValueError: Error trying to decode a non urlencoded string. Found invalid characters: {']', '['} in the string: 'search=%7B%22field_filters%22:%20[%7B%22key%22:%22date_created%22,%22value%22:%2209/01/2023%22,%22operator%22:%22is%22%7D]%7D'. Please ensure the request/response body is x-www-form-urlencoded.
One solution is to parameterize the url:
import requests
import json
url = 'https://localhost/wp-json/gf/v2/entries'
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
headers = {'Content-type': 'application/json'}
response = session.get(url, params=params, headers=headers)
print(response.json())
But in the retrieved entries, the data is not filtered with the specified date.
In the official documentation, they gave a date in this format "09/01/2023", but in my dataset, the format is: "2023-01-10 19:16:59"
Do I have to transform the format ? I tried a different format for the date
date_created = "09/01/2023"
date_created = datetime.strptime(date_created, "%d/%m/%Y").strftime("%Y-%m-%d %H:%M:%S")
What alternative solutions can I test ?
What if you use urllib.parse.urlencode function, so your code would looks like:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
import urllib.parse
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
encoded_params = urllib.parse.urlencode(params)
url = f'https://localhost/wp-json/gf/v2/entries?{encoded_params}'
r = session.get(url)
print(r.content)
hope that helps
I had the same problem and found a solution with this code:
params = {
'search': json.dumps({
'field_filters': [
{ 'key': 'date_created', 'value': '2023-01-01', 'operator': 'is' }
],
'mode': 'all'
})
}
encoded_params = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
url = 'http://localhost/depot_git/wp-json/gf/v2/forms/1/entries?' + encoded_params + '&paging[page_size]=999999999' # nombre de réponses par page forcé manuellement
I'm not really sure what permitted it to work as I'm an absolute beginner with Python, but I found that you need double quotes in the URL ( " ) instead of simple quotes ( ' ), so the solution by William Castrillon wasn't enough.
As for the date format, Gravity Forms seems to understand DD/MM/YYYY. It doesn't need a time either.
I am trying to pass multiple parameters to hotel offers using the Amadeus Python SDK but I am getting a 400 error code. How can I include checkInDate and checkOutDate in the request?
here's the code :
amadeus = Client(
client_id = clientID,
client_secret = ClientSecret
)
try:
hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode=citycode,checkInDate=checkindate,checkOutDate=checkoutdate,adults=adults,roomQuantity=rooms)
k = hotels_by_city.data
print(k)
Here an example of how to use the Python SDK to implement Hotel Search and Book:
# Install the Python library from https://pypi.org/project/amadeus
from amadeus import Client, ResponseError
amadeus = Client(
client_id='YOUR_AMADEUS_API_KEY',
client_secret='YOUR_AMADEUS_API_SECRET'
)
try:
# Get list of Hotels by city code
hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode='PAR', checkInDate='2021-01-10', checkOutDate='2021-01-12')
# Get list of offers for a specific hotel
hotel_offers = amadeus.shopping.hotel_offers_by_hotel.get(hotelId = 'HSMADAMI', checkInDate='2021-01-10', checkOutDate='2021-01-12')
# Confirm the availability of a specific offer
offer = hotel_offers.data['offers'][0]['id']
offer_availability = amadeus.shopping.hotel_offer(offer).get()
guests = [{'id': 1, 'name': { 'title': 'MR', 'firstName': 'BOB', 'lastName': 'SMITH' }, 'contact': { 'phone': '+33679278416', 'email': 'bob.smith#email.com'}}]
payments = { 'id': 1, 'method': 'creditCard', 'card': { 'vendorCode': 'VI', 'cardNumber': '4151289722471370', 'expiryDate': '2021-08' } }
hotel_booking = amadeus.booking.hotel_bookings.post(offer, guests, payments)
print(hotel_booking.data)
except ResponseError as error:
raise error
the documentation:
https://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC
from xmlrpc.client import ServerProxy
url = 'http://api.opensubtitles.org/xml-rpc'
server = ServerProxy(url)
token = server.LogIn('username', 'Password', 'eng', 'TemporaryUserAgent')['token']
data = server.SearchSubtitles(token, [{'sublanguageid': 'english', 'query': 'Movie Name'}])
I print data and it has IDSubtitleFile in it. but then I try
id_subtitle_file = data.get('IDSubtitleFile')
and it prints None
I have seen it done this way too
id1= data.get('data')
subtitle_id = id1.get('IDSubtitleFile'))
but this throws 'list' object has no attribute 'get'
what am I doing wrong?
Please check the API documentation: here
The search request response structure:
{
status: ...
data: [ # <-- array
...records...
]
}
Code sample below:
from xmlrpc.client import ServerProxy
server = ServerProxy("http://api.opensubtitles.org/xml-rpc")
token = server.LogIn('username', 'pass', 'eng', 'TemporaryUserAgent')['token']
response = server.SearchSubtitles(token,
[{'sublanguageid': 'english', 'query': 'Movie Name'}]
)
for record in response["data"]:
print(record["IDSubtitleFile"])
I have written a python script to get instance information over email with cron setup and populate metrics as well. With the following code i can see all the logs in cloudwatch logs console. However "dimension" never gets created under cloudwatch events section and not triggering any mail as well.
import boto3
import json
import logging
from datetime import datetime
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def post_metric(example_namespace, example_dimension_name, example_metric_name, example_dimension_value, example_metric_value):
cw_client = boto3.client("cloudwatch")
response = cw_client.put_metric_data(
Namespace=example_namespace,
MetricData=[
{
'MetricName': example_metric_name,
'Dimensions': [
{
'Name': example_dimension_name,
'Value': example_dimension_value
},
],
'Timestamp': datetime.datetime.now(),
'Value': int(example_metric_value)
},
]
)
def lambda_handler(event, context):
logger.info(event)
ec2_client = boto3.client("ec2")
sns_client = boto3.client("sns")
response = ec2_client.describe_instances(
Filters=[
{
'Name': 'tag:Name',
'Values': [
'jenkins-slave-*'
]
}
]
)['Reservations']
for reservation in response:
ec2_instances = reservation["Instances"]
for instance in ec2_instances:
myInstanceId = (instance['InstanceId'])
myInstanceState = (instance['State']['Name'])
myInstance = \
(
{
'InstanceId': (myInstanceId),
'InstanceState': (myInstanceState),
}
)
logger.info(json.dumps(myInstance)
post_metric("Jenkins", "ciname", "orphaned-slaves", myInstanceId, 1)
# Send message to SNS (Testing purpose)
SNS_TOPIC_ARN = 'arn:aws:sns:us-east-1:1234567890:example-instance-alarms'
sns_client.publish(
TopicArn = SNS_TOPIC_ARN,
Subject = 'Instance Info: ' + myInstanceId,
Message = 'Instance id: ' + myInstanceId
)
Can anyone please help if i am missing anything here. Thanks in advance.
You forgot to add required fields such as EvaluationPeriods, AlarmName and etc. to your put_metric_data according to documentation.
You can use this for an example.
I'm transitioning to the new admin-sdk api's and not finding it easy. I've figured out oath and a basic user lookup, but now I am stuck on creating a google apps account.
Here's the code I am using:
import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
SERVICE_ACCOUNT_EMAIL = 'xyz#developer.gserviceaccount.com'
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'privatekey.p12'
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL,
key,
scope='https://www.googleapis.com/auth/admin.directory.user',
sub='myadmin#mydomain.edu',
)
http = httplib2.Http()
http = credentials.authorize(http)
userinfo = { 'primaryEmail': 'jane#mydomain.edu',
'name': { 'givenName': 'Jane', 'familyName': 'Smith' },
'password': 'mypasswd',
}
service = build("admin", "directory_v1", http=http)
users = service.users()
users.insert(userinfo).execute()
And here is the result:
Traceback (most recent call last):
File "xy", line 39, in <module>
new_user = users.insert(userinfo ).execute()
TypeError: method() takes exactly 1 argument (2 given)
I have tried a lot of permutations on this theme to no avail, including:
users.insert(name='Jane Smith', password='mypasswd', name.familyName='Smith',
name.givenName='Jane', primaryEmail='jane#testg.berkeley.edu').execute()
SyntaxError: keyword can't be an expression
users.insert(name='Jane Smith', password='mypasswd', familyName='Smith',
givenName='Jane', primaryEmail='jane#testg.berkeley.edu').execute()
File "build/bdist.linux-x86_64/egg/apiclient/discovery.py", line 573, in method
TypeError: Got an unexpected keyword argument "givenName"
Any help would be greatly appreciated.
Try:
userinfo = {'primaryEmail': 'jane#mydomain.edu',
'name': { 'givenName': 'Jane', 'familyName': 'Smith' },
'password': 'mypasswd',
}
service = build("admin", "directory_v1", http=http)
service.users().insert(body=userinfo).execute()