Posts tagged with python

I'm having trouble connecting to the Google Ads API with Python, first I have all the proper credentials for the connection which are DEVELOPER_TOKEN, CLIENT_SECRET, REFRESH_TOKEN, CUSTOMER_ID. It should be noted that I am trying to connect with the method that I have a yaml file where I have all my credentials and well I have tried to get a code where I can connect and I have tried all the methods and it does not let me, someone who can guide me for the API connection, please.

I have tried with the script of the repository of the same that Google Ads sends you, but it is very extensive to understand and in the same way I feel that I managed to understand it a little but nevertheless it does not work for me, I also tried with others and I don't need you to help me, please

I am working on a project using FastAPI to handle incoming WhatsApp messages and respond to them. I've set up the webhook, and I can successfully receive messages. However, I'm encountering issues when trying to send a response back to the user using the WhatsApp Business API.

Here is the relevant part of my code:

from fastapi import FastAPI, Request, HTTPException, Query from fastapi.responses import JSONResponse from pydantic import BaseModel import requests app = FastAPI() VERIFY_TOKEN = "tourism"   class WhatsAppEvent(BaseModel):     message: dict WHATSAPP_API_ENDPOINT = "https://graph.facebook.com/v18.0/***(Entered my phone number ID)/messages" WHATSAPP_API_TOKEN = "***(Entered my API access token)" @app.post("/") async def handle_post_request(request: Request):     # Process the incoming POST request here     data = await request.json()     print("Received POST request data:", data)     # Send a response     return {"status": "success", "message": "POST request received"} @app.get("/") def verify(request: Request):     mode = request.query_params.get('hub.mode')     challenge = request.query_params.get('hub.challenge')     token = request.query_params.get('hub.verify_token')     if mode and token:         if mode == 'subscribe' and token == VERIFY_TOKEN:             print("WEBHOOK_VERIFIED")             return JSONResponse(content=int(challenge), status_code=200)         else:             raise HTTPException(status_code=403, detail="Verification failed")     return {"code": 200, 'message': 'test'} @app.post("/incoming-message") def receive_message(event: WhatsAppEvent):     try:         user_message = event.message['text']         sender_id = event.message['sender']['id']         bot_response = f'You said: {user_message}' #sending an echo message                  # Prepare response for WhatsApp         response_data = {             'recipient': {'id': sender_id},             'message': {'text': bot_response}         }         send_whatsapp_message(sender_id, bot_response)         return JSONResponse(content=response_data, status_code=200)     except Exception as e:         raise HTTPException(status_code=500, detail=f"Error processing message: {str(e)}")      def send_whatsapp_message(recipient_id, message_body):     headers = {         'Authorization': f'Bearer {WHATSAPP_API_TOKEN}',         'Content-Type': 'application/json'     }     data = {         'phone': recipient_id,         'message': {             'text': message_body         }     }     try:         response = requests.post(WHATSAPP_API_ENDPOINT, headers=headers, json=data)         response.raise_for_status()  # Raises HTTPError for bad responses         print("WhatsApp API response:", response.text)  # Add this line for debugging         return response.json()  # If you want to return the API response data     except requests.exceptions.HTTPError as errh:         print("HTTP Error:", errh)         raise HTTPException(status_code=response.status_code, detail=f"HTTP Error: {errh}")     except requests.exceptions.RequestException as err:         print("Request Error:", err)         raise HTTPException(status_code=response.status_code, detail=f"Request Error: {err}") if __name__ == "__main__":     import uvicorn     uvicorn.run(app, reload=False, host="0.0.0.0", port=8000) 

I have verified that the webhook is working (WEBHOOK_VERIFIED is printed in the console), and I can see the incoming messages in the logs. However, the send_whatsapp_message function does not seem to be sending messages successfully.

The response from the WhatsApp API is as follows:

WEBHOOK_VERIFIED INFO:     2a03:2880:23ff:5::face:b00c:0 - "GET /?hub.mode=subscribe&hub.challenge=1310749767&hub.verify_token=tourism HTTP/1.1" 200 OK Received POST request data: {'object': 'whatsapp_business_account', 'entry': [{'id': '**(My ID)', 'changes': [{'value': {'messaging_product': 'whatsapp', 'metadata': {'display_phone_number': '**(My number)', 'phone_number_id': '**(My Phone number ID)'}, 'contacts': [{'profile': {'name': 'Rishikesh Dasari'}, 'wa_id': '**(recipient Number)'}], 'messages': [{'from': '**(recipient Number)', 'id': 'wamid.HBgMOTE5MzkwMzYwMjYyFQIAEhgWM0VCMEMyRUU3MzQ4Q0VCNjFGQUIzRgA=', 'timestamp': '1705643757', 'text': {'body': 'hello'}, 'type': 'text'}]}, 'field': 'messages'}]}]} INFO:     2a03:2880:20ff:b::face:b00c:0 - "POST / HTTP/1.1" 200 OK 

I have double-checked the WhatsApp API endpoint, token, and the structure of the request, but I'm still unable to send messages. I suspect there might be an issue with my send_whatsapp_message function.

Can someone please review the code and provide insights on what might be causing the problem? Additionally, if there's a better way to handle sending WhatsApp messages in FastAPI, I'm open to suggestions.

I am using this script based on the documentation: https://developers.google.com/google-ads/api/samples/add-image-extension

def create_image_extensions(df):     for index,row in df.iterrows():         extension_feed_item_service =              client.get_service("ExtensionFeedItemService")         extension_feed_item_operation =              client.get_type("ExtensionFeedItemOperation")         extension_feed_item = extension_feed_item_operation.create         extension_feed_item.image_feed_item.image_asset =               client.get_service("AssetService").asset_path(account_id,                  row.asset_id)         response = extension_feed_item_service.mutate_extension_feed_items(customer_id=account_id, operations=\[extension_feed_item_operation\])         image_resource_name = response.results\[0\].resource_name         print("Created an image extension with resource name: "f"'{image_resource_name}'")             campaign_extension_setting_service = client.get_service("CampaignExtensionSettingService")         campaign_extension_setting_operation = client.get_type("CampaignExtensionSettingOperation")         ces = campaign_extension_setting_operation.create         ces.campaign = client.get_service("CampaignService").campaign_path(account_id, row.campaign_id)         ces.extension_type = client.enums.ExtensionTypeEnum.IMAGE         ces.extension_feed_items.append(image_resource_name)              response = (             campaign_extension_setting_service.mutate_campaign_extension_settings(                 customer_id=account_id,                 operations=[campaign_extension_setting_operation],             )         )         print("Created a campaign extension setting with resource name: "f"'{response.results[0].resource_name}'")` 

But running into an error now:

Method: /google.ads.googleads.v15.services.ExtensionFeedItemService/MutateExtensionFeedItems, RequestId: B5OFT8TdalKrrmx0lEdMkA, IsFault: True, FaultMessage: Feed-based extension is read-only for this extension type. error_code {     feed_error: LEGACY_EXTENSION_TYPE_READ_ONLY   }   message: "Feed-based extension is read-only for this extension type." 

I am working on a project to extract data from Google Ads campaigns using Python. However, I'm facing an issue when trying to use the 'from google.ads.google_ads.client import GoogleAdsClient'

library, and it's giving me the error

'ModuleNotFoundError: No module named 'google.ads.google_ads''.

I have already installed the 'google-ads' library using pip. I'm currently stuck on this problem, and I would appreciate any guidance or solutions from anyone who has experience with this. Your help is highly valued.

Libraries already installed google 3.0.0 google-ads 22.1.0 google-api-core 2.14.0 google-auth 2.23.4 google-auth-httplib2 0.1.1 google-auth-oauthlib 1.1.0 googleads 40.0.0 googleapis-common-protos 1.61.0 grpcio 1.59.3 grpcio-status 1.59.2 proto-plus 1.22.3 protobuf 3.17.3

I'm currently using the Google Ads API to fetch historical metrics for specific keywords. By default, the API provides data for the last 12 months. However, I'm interested in retrieving data for a longer period, say 24 months or more. Is there a way to specify a date range or retrieve data for more than 12 months using the Google Ads API? If not, are there any workarounds to achieve this? The sample code is here:https://developers.google.com/google-ads/api/docs/keyword-planning/generate-historical-metrics

def main(client, customer_id):     """The main method that creates all necessary entities for the example.     Args:         client: an initialized GoogleAdsClient instance.         customer_id: a client customer ID.     """     generate_historical_metrics(client, customer_id) def generate_historical_metrics(client, customer_id):     """Generates historical metrics and prints the results.     Args:         client: an initialized GoogleAdsClient instance.         customer_id: a client customer ID.     """     googleads_service = client.get_service("GoogleAdsService")     keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService")     request = client.get_type("GenerateKeywordHistoricalMetricsRequest")     request.customer_id = customer_id     request.keywords = ["mars cruise", "cheap cruise", "jupiter cruise"]     # Geo target constant 2840 is for USA.     request.geo_target_constants.append(         googleads_service.geo_target_constant_path("2840")     )     request.keyword_plan_network = (         client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH     )     # Language criteria 1000 is for English. For the list of language criteria     # IDs, see:     # https://developers.google.com/google-ads/api/reference/data/codes-formats#languages     request.language = googleads_service.language_constant_path("1000")     response = keyword_plan_idea_service.generate_keyword_historical_metrics(         request=request     )     for result in response.results:         metrics = result.keyword_metrics         # These metrics include those for both the search query and any variants         # included in the response.         print(             f"The search query '{result.text}' (and the following variants: "             f"'{result.close_variants if result.close_variants else 'None'}'), "             "generated the following historical metrics:\n"         )         # Approximate number of monthly searches on this query averaged for the         # past 12 months.         print(f"\tApproximate monthly searches: {metrics.avg_monthly_searches}")         # The competition level for this search query.         print(f"\tCompetition level: {metrics.competition}")         # The competition index for the query in the range [0, 100]. This shows         # how competitive ad placement is for a keyword. The level of         # competition from 0-100 is determined by the number of ad slots filled         # divided by the total number of ad slots available. If not enough data         # is available, undef will be returned.         print(f"\tCompetition index: {metrics.competition_index}")         # Top of page bid low range (20th percentile) in micros for the keyword.         print(             f"\tTop of page bid low range: {metrics.low_top_of_page_bid_micros}"         )         # Top of page bid high range (80th percentile) in micros for the         # keyword.         print(             "\tTop of page bid high range: "             f"{metrics.high_top_of_page_bid_micros}"         )         # Approximate number of searches on this query for the past twelve         # months.         for month in metrics.monthly_search_volumes:             print(                 f"\tApproximately {month.monthly_searches} searches in "                 f"{month.month.name}, {month.year}"             )