Create a google contact with python3 - python-3.x

I would like to create a contact with the google api and python3
but gdata seemsnot to be compatible with python3.
Like :
AttributeError: 'function' object has no attribute 'func_name'
Does anyone have any sample that works on how to create contact with google api in python3 ?
thanks

First, have you installed the gdata python client with pip, or with pip3? According to Google's repository, which says,
Python 3.3+ is also now supported! However, this library has not yet been > used as thoroughly with Python 3, so we'd recommend testing before
deploying with Python 3 in production,
you can use pip3, like pip3 install google-api-python-client, to reinstall it. Once that's cleared up, see the below modified sample code-block for how to create a contact by just their Name, E-mail and Phone number with Python 3:
import atom.data
import gdata.data
import gdata.contacts.client
import gdata.contacts.data
gd_client = gdata.contacts.client.ContactsClient(source='YOUR_APPLICATION_NAME')
def create_contact(gd_client):
new_contact = gdata.contacts.data.ContactEntry()
# Set the contact's name.
new_contact.name = gdata.data.Name(
given_name=gdata.data.GivenName(text='First'),
family_name=gdata.data.FamilyName(text='Last'),
full_name=gdata.data.FullName(text='Full'))
new_contact.content = atom.data.Content(text='Notes')
# Set the contact's email addresses.
new_contact.email.append(gdata.data.Email(address='handle#gmail.com',\
primary='true', rel=gdata.data.WORK_REL, display_name='E. Bennet'))
new_contact.email.append(gdata.data.Email(address='liz#example.com',\
rel=gdata.data.HOME_REL))
# Set the contact's phone numbers.
new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1212',
rel=gdata.data.WORK_REL, primary='true'))
new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1213',
rel=gdata.data.HOME_REL))
# Send the contact data to the server.
contact_entry = gd_client.CreateContact(new_contact)
print ("Contact's ID: {}".format(contact_entry.id.text))
return contact_entry

For read-only access to Contacts, Google has built the new People API, which works just fine with Python3 in the google-api-python-client. However, for write access you'll need to use the older GData format.
The short answer to your question is that you won't be able to get GData to work with Python3 because the gdata-python-client is no longer maintained and never had Python3 support built in (see https://github.com/google/gdata-python-client/issues/29)
However, not all hope is lost! You can still query directly to Google's REST API. Specifically, to create a contact you need to work with the https://www.google.com/m8/feeds/contacts/{userEmail}/full route (see the Contacts API documentation for more information)
The appropriate way to work with the API directly is to submit a web request using something like Python's Requests module.
CREATE_ROUTE = 'https://www.google.com/m8/feeds/contacts/default/full'
FULL_PATH = CREATE_ROUTE + '?access_token=' + ACCESS_TOKEN
import requests
r = requests.get(FULL_PATH)
print(r.text)
Where ACCESS_TOKEN is the access token you got back from Google when you authorized your access (this can still be done using google-api-python-client)

Related

GCP SDK API for Policy Analyzer for Python

I can see the Service Account usage out of gcloud CLI by doing as such:
gcloud policy-intelligence query-activity --activity-type=serviceAccountKeyLastAuthentication --project=<project_name>
I would like to replicate this in a python script..
I am attempting to this do this but I am not sure how to authenticate, and I am getting a 401 error, despite having enabled the API. I am following this documentation. https://cloud.google.com/policy-intelligence/docs/activity-analyzer-service-account-authentication#iam-get-service-account-key-id-rest
import requests
r = requests.get(f"https://policyanalyzer.googleapis.com/v1/projects/{self.project_id}/locations/global/activityTypes/serviceAccountKeyLastAuthentication/activities:query?filter=activities.full_resource_name%3D%22%2F%2Fiam.googleapis.com%2Fprojects%2F{self.project_id}%2FserviceAccounts%2F{self.sa_email}%2Fkeys%2F{self.key_id}%22"
Is there some way I need to authenticate my request call? The rest of the script I am using the python client libraries using discovery.build and authenticating as such:
credentials, project = google.auth.default()
self.crm = discovery.build("cloudresourcemanager", "v3", credentials=credentials)
There does not seem to be a "policy analyzer" python library, so I am not sure on next steps.
The end goal is to see the last key authentication time of every service account key in the organization.
Thanks!
You may check this link for the sample Python code
Do note that the feature is still in preview and does not have a Python client for the same yet. The gcloud cli and REST is the way of accessing this feature programmatically.
Take a look at the python example shown towards the bottom of the page here:
https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts.keys/list
It shows how to get application default credentials used to pass in the client. You could accomplish the same with http requests, but that example above should help.
Also, looking at the original curl request, if you decode the filter to unicode it should be:
activities.full_resource_name="//iam.googleapis.com/projects/PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT_EMAIL/keys/KEY_ID"
Assuming you got it from the sample [curl][1] request.
[1]: https://cloud.google.com/policy-intelligence/docs/activity-analyzer-service-account-authentication#view-recent-specific-key

Creating a Stripe Refund via Code by Zapier

I've been trying to create a refund in Stripe via code by Zapier, using the python code from this answer: Is is possible to create a Stripe refund action in Zapier?
I'm receiving a "ModuleNotFoundError: no module named 'stripe'" when I attempt to test the step in Zapier.
My code looks something like this:
import stripe
stripe.api_key = "myAPIkey"
stripe.Refund.create(
charge = input_data["charge"],
)
What am I missing?
https://zapier.com/help/create/code-webhooks/use-python-code-in-zaps
You cannot require external libraries or install libraries commonly referred to as "pip modules". Only the standard Python library and requests are available in the Code app and requests is already included in the namespace.
(disclaimer, I've never used Zapier, but)As far as I know, that means you can't use a library like Stripe's official Python library(your error message is that it's now installed).
Instead you'd need to make this call by translating https://stripe.com/docs/api/curl#create_refund directly into calls to Stripe's REST API using the requests library. Remember that you need to supply an API key with it(Making an API call in Python with an API that requires a bearer token)

API.put_photo is deprecated. Is there a new method for publishing photos or Figures on Facebook using Python API?

I am using facebook API (version 3.1.) to publish automatically on my Facebook feed using a python script (shown below), which was working fine until recently. I found that facebook deprecated the put_photo function from the new api version (8.0), but can't find how to call the new function or new method to publish photos automatically from the python script. So, Is there a new way to do this? What am I missing?
Thanks a lot for the help!
import facebook
import sys,os
import json
import numpy as np
def facebook_post_sentido(figure_name):
def get_cfg():
cfg = {
"page_id" : "my_id"
"access_token" : "my_token"
}
return cfg
def gen_api(cfg):
API = facebook.GraphAPI(cfg['access_token'])
print("generating api connection")
return API
cfg = get_cfg()
API = gen_api(cfg)
photo_id = API.put_photo(image=open(figure_name, 'rb'), )
# API.put_object(parent_object=cfg["page_id"], connection_name="feed",
# message="SISMO SENTIDO RELOCALIZADO",
# attached_media=json.dumps([{'media_fbid': str(photo_id.get('id', ''))}]))
facebook_post_sentido(figure_name="myfigure")
When I run the code I get the following error:
facebook.GraphAPIError: (#200) This endpoint is deprecated since the required permission publish_actions is deprecated
There is no way to post a photo onto user profiles via API any more.
This has been completely removed, same as making normal posts via API. With the exception of live videos, you can not publish anything any more onto user profiles via API.
Apps wanting to provide sharing functionality to end users, can use one of the dialogs provided. (But even those don’t allow a photo upload, you can only share links.)

Can't call any methods made available by FBO.gov's web API

I'm trying to get data from fbo.gov, which is a government website where they post contracts that vendors can bid in. They have a document containing ways of accessing information on the site through SOAP requests, which is what I'm trying to do. Although all of the examples in that document are in PHP, I am trying to make my requests in Python, because I've never done anything with PHP before.
To make the SOAP requests in Python, I'm using zeep.
Right now, I can successfully authenticate myself through HTTP, but no matter what method I try to call, I always get the same error: This user has an inactive agency.
Here is the code I'm using to send the request
from requests import Session
from requests.auth import HTTPBasicAuth
import zeep
from zeep.transports import Transport
test = "https://fbo-test.symplicity.com"
prod = "https://fbo.gov"
session = Session()
session.auth = HTTPBasicAuth("sample_username", "sample_password")
client = zeep.Client(f"{test}/ws/fbo_api.php?wsdl", transport=Transport(session=session))
dictionary = {"notice_type": "PRESOL"}
print(client.service.getList(data=dictionary))
I realize this is a long shot, but what could be causing this error? I can't find anything even remotely related to the error anywhere on the internet.
Per the Federal Service Desk:
The FBO API is only available for government user accounts.
Some of the FBO data is available at: ftp://ftp.fbo.gov
Currently, FBO is in the process of moving to SAM, and will have a public API once the move is complete. The new API is under development, with the latest specification at: https://open.gsa.gov/api/get-opportunities-public-api/
FBO.GOV has been retired as of 11/12/2019 along with the ftp.fbo.gov bulk download, use the following instead,
https://open.gsa.gov/api/sam-entity-extracts-api/

How to access a shared folder using python imaplib?

How do you access a shared folder ? This is a shared folder which is visible to other users too. I am currently using outlook where the shared folder is visible along with my personal emails
Following back on my question. After reading enough this seems to work.
While using imaplib and connecting to exchange in python 3
use this,
result, data=mail.login('personal#domain.com\shared#domain.com','personalPassword')
If you have access to this shared mailbox in outlook then you will be able to connect using this. Print the result if it says 'OK' then the code did work.
I believe this is an answer.
Posting a link here for those who are working on similar problem with a python solution.
https://medium.com/#theamazingexposure/accessing-shared-mailbox-using-exchangelib-python-f020e71a96ab
Here is the snippet:
from exchangelib import Credentials, Account
credentials = Credentials('Firstname.Lastname#someenterprise.com', 'Your_Password_Here')
account = Account('**shared_mail_box_name#someenterprise.com**', credentials=credentials, autodiscover=True)
for item in account.inbox.all().order_by('-datetime_received')[:100]:
print(item.subject, item.sender, item.datetime_received)

Resources