Posts tagged with python

Edit: I see that I can only use and send to numbers associated with Twilio. My question was to see if I didn't have to use numbers associated with Twilio, for example, if I were to make a website that can send numbers on WhatsApp, like my own WhatsApp web, how do I do that, as in how do I make a website that can send messages through WhatsApp just like WhatsApp web?

I want to make a python program, that asks for your number when you start it. It then asks for the number you want to send the message to. This code will ultimately be running on android if that helps.

from twilio.rest import Client  contact = '' contact = input('Which number do you want to send the message to: ') message = '' message = input('What do you Want to send: ') account_sid = '_'  auth_token = '_'  client = Client(account_sid, auth_token)  #some code to get my number #some code to get my number my_number = #i got my number   message = client.messages.create(                                from_='whatsapp:'+ my_number,                                 body=message,                                     to='whatsapp:' + contact ,                           )    print(message.sid) 

So it's the code to get the user's number that I need help with. Another option I've been considering is manually inputting the number and using that (I will add an OTP if I go this route but not rn). Which sounds like the better option?

I'm new to Twilio's APIs so any help would be appreciated.

I'm trying to get reports for my google ads and display them on a dashboard for easier viewing and monitoring.

I've gone through the whole process to authenticate my account. I got all the keys needed. Everything works up until the query is run. See code below copied from Google ads API examples

#!/usr/bin/env python # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #     https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example illustrates how to get all campaigns. To add campaigns, run add_campaigns.py. """ import argparse import sys from google.ads.google_ads.client import GoogleAdsClient from google.ads.google_ads.errors import GoogleAdsException def main(client, customer_id):     ga_service = client.get_service("GoogleAdsService", version="v6")     query = """         SELECT campaign.id, campaign.name         FROM campaign         ORDER BY campaign.id"""     # Issues a search request using streaming.     response = ga_service.search_stream(customer_id, query=query)     try:         for batch in response:             for row in batch.results:                 print(                     f"Campaign with ID {row.campaign.id} and name "                     f'"{row.campaign.name}" was found.'                 )     except GoogleAdsException as ex:         print(             f'Request with ID "{ex.request_id}" failed with status '             f'"{ex.error.code().name}" and includes the following errors:'         )         for error in ex.failure.errors:             print(f'\tError with message "{error.message}".')             if error.location:                 for field_path_element in error.location.field_path_elements:                     print(f"\t\tOn field: {field_path_element.field_name}")         sys.exit(1) if __name__ == "__main__":     # GoogleAdsClient will read the google-ads.yaml configuration file in the     # home directory if none is specified.     google_ads_client = GoogleAdsClient.load_from_storage()     parser = argparse.ArgumentParser(         description="Lists all campaigns for specified customer."     )     # The following argument(s) should be provided to run the example.     parser.add_argument(         "-c",         "--customer_id",         type=str,         required=True,         help="The Google Ads customer ID.",     )     args = parser.parse_args()     main(google_ads_client, args.customer_id) 

Nothing gets printed to my console. When I print out print(response) i get <google.api_core.grpc_helpers._StreamingResponseIterator object at 0x7fb7dcaaf3d0>

I get no errors, tracebacks nothing. This is what my console looks like (hiding customer_id):

I am trying to fetch campaigns' reports from Google Ads API. But, getting an error when trying to fetch data with MCC:

Code:

  import sys,os   from google.ads.google_ads.client import GoogleAdsClient   from google.ads.google_ads.errors import GoogleAdsException   def get_data(client, customer_id):     ga_service = client.get_service("GoogleAdsService", version="v6")     query = """         SELECT           campaign.name,           campaign.status,           segments.device,           metrics.impressions,           metrics.clicks,           metrics.ctr,           metrics.average_cpc,           metrics.cost_micros         FROM campaign         WHERE segments.date DURING LAST_30_DAYS         """     # Issues a search request using streaming.     response = ga_service.search_stream(customer_id, query=query)     try:         for batch in response:             for row in batch.results:                 print(                     row                 )     except GoogleAdsException as ex:         print(             f'Request with ID "{ex.request_id}" failed with status '             f'"{ex.error.code().name}" and includes the following errors:'         )         for error in ex.failure.errors:             print(f'\tError with message "{error.message}".')             if error.location:                 for field_path_element in error.location.field_path_elements:                     print(f"\t\tOn field: {field_path_element.field_name}")         sys.exit(1)     if __name__ == "__main__":         # get client object with oauth2         credentials = {'developer_token': "xxxxxxxxxxxxxxx",             'refresh_token': "xxxxxxxxxxxxxxxx",             'client_id': "xxxxxxxxxxxxxxx",             'client_secret': "xxxxxxxxxxxxxxxx"                        }         google_ads_client = GoogleAdsClient.load_from_dict(credentials)              get_data(google_ads_client, 'xxxxxxxxx') 

Wehn Running the code with MCC client ID:

get_data(google_ads_client, 'MANAGER(MCC)_CLIENT_ID') 

I'm Getting Error_1:

Request made: ClientCustomerId: xxxxxxxxx, Host: googleads.googleapis.com:443, Method: /google.ads.googleads.v6.services.GoogleAdsService/SearchStream, RequestId: xxxxxxxxxx, IsFault: True, FaultMessage: Metrics cannot be requested for a manager account. To retrieve metrics, issue separate requests against each client account under the manager account.

I assumed, the solution would be to set a different ClientCustomerId of the account itself, not MCC. So I did, and run the code again with the client id of the direct account, and, got another error:

Wehn Running the code with Account client ID:

get_data(google_ads_client, 'ACCOUNT_CLIENT_ID') 

I'm Getting Error_2:

Request made: ClientCustomerId: xxxxxxx, Host: googleads.googleapis.com:443, Method: /google.ads.googleads.v6.services.GoogleAdsService/SearchStream, RequestId: xxxxxxxxxx, IsFault: True, FaultMessage: User doesn't have permission to access customer. Note: If you're accessing a client customer, the manager's customer id must be set in the 'login-customer-id' header. See https://developers.google.com/google-ads/api/docs/concepts/call-structure#cid

That error essentially says to insert the manager's client id, which I already did and got error_1 (!).

What am I missing here?

I have created a test account in https://console.cloud.google.com/

I followed the instructions in the following link: OAuth Web Application Flow

All went ok till Step 3 - Generating a refresh token. In Step 3: sub steps 1-4 went ok as describe in the link.

But on sub step 5 I am getting :

The authentication flow has completed. You may close this window.

and in my cmd I see:

Access token: XXXXXXXXXX Refresh token: None

Can someone please help me to understand what am I doing wrong?

Thanks,

Nir

I am trying to work with Google-ads-API. Running Ubuntu 20.04, Python 3.9(min requirement for the client library to work is 3.6), working with google-ads-api V6. Here's the story of my agony.

I have made a test manager account[A], generated a developer's token, and have "test-level" access to use the API, which is great. Test level allows you to make calls to the API regarding information\reports dealing with test accounts(not production).

Also, went through the whole Oauth2 credentials for account [A], allowed test emails, and after running "examples/authentication/authenticate_in_web_application.py", I am redirected to a webpage, allow my main test manager account to access the second test manager account[B](as instructed by the documentation, to create another test manager account[B], besides the main account[A] with the developer token), a refresh token is generated successfully from this OAuth2 prompt, to allow account [B] to be managed my account [A], added the refresh token to my google-ads.yaml file, and things are all good.

When I run this .py file from the examples

python3 google-ads-python/examples/account_management/list_accessible_customers.py 

The result is this:

Total results: 2 Customer resource name: "customers/1792845307" Customer resource name: "customers/5341438919" 

Lovely, took 2 days to get this far. And it's been two days now trying to get past the following. Please note that the above results are both from my account [B], the API request to get these results was made while the developer token for account [A] is set in the google-ads.yaml file.

So, the .yaml file for now contains Developer account token for account [A], OAuth creds for account[A] on cloud console(.json) file. The refresh token for account [B] that resulted from the Authentication in step1.

Moving on, by running "get_account_information.py", which is also in the examples folder, and passing to it one of the accounts from the above result[mandatory flag --c, which is the client id), I keep getting an access denied error:

python3 get_account_information.py --c 5341438919 I get this:

Request with ID "LhKeU9ZI4zZgnp05VSHbjg" failed with status "PERMISSION_DENIED" and includes the following errors: Error with message "User doesn't have permission to access customer. Note: If you're accessing a client customer, the manager's customer id must be set in the 'login-customer-id' header. See https://developers.google.com/google-ads/api/docs/concepts/call-structure#cid".``` 

I have tried setting "the manager's customer id must be set in the 'login-customer-id' ", this login-customer-id is located in the .yaml file. I have tried setting that to both the results from the call in step 2. I also tried adding the account manager ID from account[A]. I tried manually adding account [A] as an account manager for account [B] from withing google-ads's UI, then tried setting the "login-customer-id" again for all these accounts these linking processes, yet, failed miserably.

I am facing this access denied for all the .py files in the example directory. Tried to be as thorough and verbose as possible for this lengthy process, hoping it'll make sense. If you have tried to work with this API, you will understand what I mean, and I look forward to any insight\help\input regarding this, even if you haven't worked with this API.

In the documentation, the guide says that after creating a test developer manager account, all accounts below that will be also test accounts, and will be designated by a red label saying "TEST", otherwise it's a production account. Both accounts [A]+[B] above are test manager\developer accounts, yet don't have any red labels stating they are tests, neither any children I tried creating under them. So I wonder if the error\roadblock I am facing is due to them not being designated as test accounts? But why are they being listed as "Accessible accounts" in Step2.

Thanks a lot! If any other pieces of info should be required, I shall provide.