使用Google People API和Python向联系人添加特定字段
我使用了People API来创建联系人、更新联系人、获取联系人和删除联系人。现在我想在创建联系人时添加一些额外的字段,但似乎这些字段没有被添加上。我想添加国家代码、一个备用电话号码、城市和职位名称。我按照文档中的说明进行了尝试。职位名称应该放在职业字段中,国家代码放在电话号码字段的canonicalForm字段下,城市则放在地址字段中。尽管我做了必要的更改,但每次创建新联系人时,这些字段都没有被填充。我知道这一点是因为我搜索这个联系人时,发现缺少这些字段。我在创建联系人的时候可能漏掉了什么,或者我搜索的方式不对(虽然搜索确实能找到结果,但我不太明白这是怎么回事)
这是我的createcontact.py文件
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/contacts"]
CREDENTIALS_FILE_PATH = r'/credentials.json'
def create_new_contact(first_name, phone_number, job_title, company, email, city, primaryNumberCC):
creds = None
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
CREDENTIALS_FILE_PATH, SCOPES
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.json", "w") as token:
token.write(creds.to_json())
try:
service = build("people", "v1", credentials=creds)
service.people().createContact(body={
"names": [{"givenName": first_name}],
"phoneNumbers": [{'value': phone_number,'canonicalForm': primaryNumberCC}],
"occupations":[{'value':job_title}],
"organizations":[{'title':company}],
"emailAddresses":[{'value':email}],
"addresses": [{"city": city}],
}).execute()
except HttpError as err:
print(err)
这是我搜索联系人的方式。
import os
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# Define the scopes required for accessing the People API
SCOPES = ['https://www.googleapis.com/auth/contacts']
def get_credentials():
creds = None
# The file token.json stores the user's access and refresh tokens, and is created automatically when the authorization flow completes for the first time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json')
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
def get_contact_resource_by_name(name):
creds = get_credentials()
service = build('people', 'v1', credentials=creds)
# Perform a search query using the contact's name
results = service.people().searchContacts(query=name, readMask="names").execute()
if 'results' in results:
if len(results['results']) > 0:
# Extract the resource name of the first matching contact
print(results)
return results['results'][0]['person']['resourceName']
return None
1 个回答
2
我觉得你的函数 create_new_contact
是可以工作的。但是,你提到 尽管进行了必要的更改,当我创建一个新联系人时,这些字段没有被填充。我知道这一点是因为我搜索了那个联系人,却发现缺少这些字段。
。我看到你的 get_contact_resource_by_name
函数只返回了 names
字段。我担心这可能是问题的原因。如果我理解得没错,那我们可以试试下面的修改。
修改后的脚本:
在这个修改中,get_contact_resource_by_name
函数进行了调整。
def get_contact_resource_by_name(name):
creds = get_credentials()
service = build('people', 'v1', credentials=creds)
# Perform a search query using the contact's name
results = service.people().searchContacts(query=name, readMask="names,phoneNumbers,occupations,organizations,emailAddresses,addresses").execute()
if 'results' in results:
if len(results['results']) > 0:
# Extract the resource name of the first matching contact
print(results)
return results['results'][0]['person']['resourceName']
return None
- 在这个修改中,当你在调用
create_new_contact(first_name, phone_number, job_title, company, email, city, primaryNumberCC)
时,把first_name
作为参数传给get_contact_resource_by_name(name)
,它会返回正确的值,包括names, phoneNumbers, occupations, organizations, emailAddresses, addresses
这些字段。