Posts tagged with python

This code is being used on aws lambda for making Google ads client

try:     googleads_client = GoogleAdsClient.load_from_dict(credentials, version="v11",) except GoogleAdsException as e:     print(f"Google Ads Exception: {e.message}") 

Unfortunately this is running into time out issue even if the time is set to 3 minutes. As there is no error, It is not possible to debug the issue. Any experienced developer can share some tips? Thanks alot

We are building a chatbot for WhatsApp using the OpenAI API, which is intended to be able to answer any question asked to it. However, we are experiencing some issues when trying to integrate the OpenAI API with the WhatsApp Business API. Here is the code we are using for this integration:

import os import requests from flask import Flask, request import openai from Testbotgpt import generate_response app = Flask(__name__) def send_message(to, text):     data = {         "recipient_type": "individual",     "to": "whatsapp:{}".format(to),     "type": "text",     "text": {       "body": text     }     }     headers = {         'Content-Type': 'application/json',         'Authorization': 'Bearer <Access Token>'     }     api_url = 'https://api.whatsapp.com/v1/messages'     response = requests.post(api_url, json=data, headers=headers)     if response.status_code != 200:                raise ValueError('Error sending message: {}'.format(response.text)) @app.route('/bot', methods=['POST']) def bot():     incoming_msg = request.values.get('Body', '').lower()     from_number = request.values.get('From', '')     responded = False      # Check if the message contains a greeting     if 'hi' in incoming_msg:         send_message(from_number, "Hello! How can I help you today?")         responded = True     elif 'bye' in incoming_msg:         send_message(from_number, "Goodbye! Have a great day.")         responded = True        # Use the GPT model to generate a response based on the user's input     else:         response = generate_response(incoming_msg)         send_message(from_number, response)         responded = True           return 'OK' if __name__ == '__main__':   app.run() 

Could you please help us understand what we are doing wrong and suggest a solution to fix the issue?

I am building an application using the WhatsApp Business Cloud API. Essentially I want to know if it's possible to build an application that collects all the messages from the day and downloads it. Specifically the media attached to it using the API. As far as I know you can use webhooks to get incoming messages. But in order to do this the application has to be run forever, and my cousin has a problem with this as it could cause problems to run an application forever vs just run it once a day. I'm able to send messages using the API and a python wrapper but that's much more simple than what I'm trying to do. Aditionally, there is an option of using selenium but that's not really an automated solution to what we're trying to do because everytime selenium executes the browser we'd need to log in using the QR code. If anyone has any idea if this is possible (or not possible) I'd be very appreciative!

from heyoo import WhatsApp import logging import requests from dotenv import load_dotenv from flask import Flask, request, make_response app = Flask(__name__) token = 'EAAVk5rqOCsABAAcPPrZC6GnlZAJuykdFIQd4DhkuRVNeGntfFOU5jaK4jG2yCZBS6i7kFQGk3kRvDP0fExBXRsFyqWUqfVVJsSxeQdcA9XHWpRuUsnnuwqLcZAQpwTiuoZCXv4ixCcHYlPEe6NGHupCalHvWw9NQRoZAVnegU5ZCBvX6eO9E8vyum1lQ2SSt7OuUpdpIkmkyBK8tiEL8rpGwM8RrqZA3A10ZD' messenger = WhatsApp(token,  phone_number_id='100398242927044') messenger.send_message('Hey its JJ ', '1xxxxxxxx') logging.basicConfig(     level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) print("hello") @app.route("/", methods=["GET", "POST"]) def hook(): 

//some code that isn't working yet

I'm new to all of this stuff so I don't really know how to set up a webhook either but my cousin who's business I'm building this app for doesn't ideally want to use a webhook.

I have a list of IDs that are integers. If I do print(data_clients["id"]) I get something like:

4323324234 2342342344 5464564565 

Then I want to call an API (Google Ads) that uses those numbers as IDs (to know which data to retrieve). I have to do a loop (or something similar) to get the data from each ID.

I've tried this

for id in range(data_clients["id"]):                 query = (f''' WHATEVER ''')                 stream = ga_service.search_stream(customer_id = data_clients["id"], query=query)                 list_id = [] 

With this code I get the following error:

4323324234 has type int, but expected one of: bytes, unicode 

And if I try to convert the int to Unicode or bytes (with chr or to_bytes), I get

int too big to convert 

Maybe the solution is obvious, but I'm a Python/coding beginner, so I'm pretty confused.

Any ideas? Thanks!

I have multiple keywords for which I am looking for some related keyword ideas along with their metrics. For that, I am using google-ads-api's GenerateKeywordIdeasRequest. It takes a list of keywords, but right now I am passing a single keyword at a time. After that I convert the output into a dataframe and pick the top 3 keywords ideas based on their monthly search volume.

for example: if passed "bottle", it would return

and from there I would extract the top 3 keyword searches suggested for "bottle".

But with this approach, it takes a lot of time to generate ideas for all input keywords. So I tried passing all input keywords at once, which reduce the processing time dramatically but the issue is, I am not able to get the top 3 suggested keyword for each input keyword separately as all suggested keywords ideas for each input are now mixed. And It is hard to tell which is suggested for which passed input.

Here is the code I am using

import pandas as pd from google.ads.googleads.client import GoogleAdsClient class GoogleAD:     def __init__(self):       pass          def get_keywords_search_volume(client, customer_id, location_ids, language_id, keyword_texts, page_url= None):         """function to get keyword search volume from google ads API """         keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService")         keyword_competition_level_enum = (client.enums.KeywordPlanCompetitionLevelEnum)         keyword_plan_network = (client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH_AND_PARTNERS)         location_rns = GoogleAD.map_locations_ids_to_resource_names(client, location_ids)         language_rn = client.get_service("GoogleAdsService").language_constant_path(language_id)                  # Either keywords or a page_url are required to generate keyword ideas         # so this raises an error if neither are provided.         if not (keyword_texts or page_url):             raise ValueError(                 "At least one of keywords or page URL is required, "                 "but neither was specified."             )                  # Only one of the fields "url_seed", "keyword_seed", or         # "keyword_and_url_seed" can be set on the request, depending on whether         # keywords, a page_url or both were passed to this function.         request = client.get_type("GenerateKeywordIdeasRequest")         request.customer_id = customer_id         request.language = language_rn         request.geo_target_constants = location_rns         request.include_adult_keywords = False         request.keyword_plan_network = keyword_plan_network                  # To generate keyword ideas with only a page_url and no keywords we need         # to initialize a UrlSeed object with the page_url as the "url" field.         if not keyword_texts and page_url:             request.url_seed.url = page_url                  # To generate keyword ideas with only a list of keywords and no page_url         # we need to initialize a KeywordSeed object and set the "keywords" field         # to be a list of StringValue objects.         if keyword_texts and not page_url:             request.keyword_seed.keywords.extend(keyword_texts)                  # To generate keyword ideas using both a list of keywords and a page_url we         # need to initialize a KeywordAndUrlSeed object, setting both the "url" and         # "keywords" fields.         if keyword_texts and page_url:             request.keyword_and_url_seed.url = page_url             request.keyword_and_url_seed.keywords.extend(keyword_texts)                  keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(request=request)                  for idea in keyword_ideas:             competition_value = idea.keyword_idea_metrics.competition.name         return keyword_ideas          def map_locations_ids_to_resource_names(client, location_ids):             """Converts a list of location IDs to resource names.             Args:                 client: an initialized GoogleAdsClient instance.                 location_ids: a list of location ID strings.             Returns:                 a list of resource name strings using the given location IDs.             """             build_resource_name = client.get_service(                 "GeoTargetConstantService"             ).geo_target_constant_path             return [build_resource_name(location_id) for location_id in location_ids]          def get_keyword_df(key_word):          """function to generate dataframe with keyword search volume"""         try:             client = GoogleAdsClient.load_from_storage('desc.yaml')             list_keywords = GoogleAD.get_keywords_search_volume(client, "686xxxxx647", ["2840"], "1000", key_word, None)             keyword_df = pd.DataFrame()             for idea in list_keywords:                 keyword_dict = {}                 competition_value = idea.keyword_idea_metrics.competition.name                 idea_text = idea.text                 monthly_search_volume = idea.keyword_idea_metrics.avg_monthly_searches                 keyword_dict['idea_text'] = idea_text                 keyword_dict['monthly_search_volume'] = int(monthly_search_volume)                 keyword_dict['competition_value'] = competition_value                 keyword_dict['key_word'] = key_word                 keyword_dict['key_word_modified'] = key_word.replace('%',' percent')                 keyword_series = pd.Series(keyword_dict)                 keyword_df = keyword_df.append(keyword_series, ignore_index = True)         except Exception as e:             print(e)             # print(e.args[2])             keyword_df = pd.DataFrame()         return keyword_df suggestion_df = GoogleAD.get_keyword_df(['bottle']) 

Let me know if there's any more information I can provide.