Creating New Contact Google People API - python

I was following the guide:
https://developers.google.com/people/v1/write-people
My Code:
def main():
"""Shows basic usage of the Google People API
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('people', 'v1', http=http,
discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
contact2 = service.people().createContact(
body={"names": [{"givenName": "John", "familyName": "Doe"}]}).execute()
contact2()
if __name__ == '__main__':
main()
When i run, My Error:
~/quickstart.py
Traceback (most recent call last):
File "~/quickstart.py", line 77, in <module>
main()
File "~/quickstart.py", line 66, in main
contact2()
TypeError: 'dict' object is not callable
Process finished with exit code 1
I am getting this error. How do I effectively create a new contact?

Your problem is this line:
contact2()
service.people().createContact returns dictionary as response and you are trying to call it.
dictionary object is not a function.

Problem solved, although I do not understand why. I was able to save contact using:
contact2 = service.people().createContact(
body={"names": [{"givenName": "John", "familyName": "Doe"}]})
contact2.execute()

Related

Sending Facebook message

Just trying to send a Facebook message with python.
Code:
import fbchat
from fbchat import Client
from fbchat.models import *
client = Client("my_username", "my_password")
#help(fb.Client.send)
#client.send(text="This is a test", thread_id="christopher.batey", thread_type=ThreadType.USER)
name = "christopher.batey"
friends = client.searchForUsers(name)
friend = friends[0]
uid = friend.uid
msg = "This is a test"
print(help(client.send))
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
Error:
Traceback (most recent call last):
File "main.py", line 13, in
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
TypeError: init() got an unexpected keyword argument 'thread_id'
I'm not familiar with the API but from the documentation, it looks like the proper call would be:
client.send(Message(text=msg), thread_id="christopher.batey", thread_type=ThreadType.USER)
where the message object is the first argument passed into send, followed by thread_id and thread_type.
I spent some time exploring this module a few years ago.
Quickly looking back at the github examples the the thread_id should be a number.
As such change
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
to
client.send(Message(text=msg), thread_id=uid, thread_type=ThreadType.USER)
in your code. As your uid is that of the friend you want to send too.

Why am I receiving a TweepError('Authentication required!')?

I'm trying to create a Twitter bot with Tweepy that will search through the tweets on my timeline, and find tweets matching a particular keyword ("brexit"), and retweet those tweets. My developer account is the same account that I would like to do the retweeting.
I have followed everything, I believe, to the book. This is my code:
import tweepy
from tweepy import OAuthHandler
import time
auth = tweepy.OAuthHandler("XXX", "XXX")
auth.set_access_token("XXX", "XXX")
api = tweepy.API(auth)
class listener(tweepy.StreamListener):
def on_status(self, status):
print("Tweet arrived!")
print("Authors name: %s" % status.author.screen_name)
status.retweet()
time.sleep(10)
def on_error(selfself, status_code):
if status_code == 420:
return False
keywords = ["brexit"]
def search_tweets():
api = tweepy.API(auth)
tweetlistener = listener()
stream = tweepy.Stream(tweepy.api.home_timeline(), listener = tweetlistener)
stream.filter(track=keywords)
search_tweets()
However, I am getting the following error message:
Traceback (most recent call last):
File "C:/Users/borde/Documents/PythonProjects/brexitbot/botcode.py", line 29, in <module>
search_tweets()
File "C:/Users/borde/Documents/PythonProjects/brexitbot/botcode.py", line 26, in search_tweets
stream = tweepy.Stream(tweepy.api.home_timeline(), listener = tweetlistener)
File "C:\Users\borde\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\binder.py", line 245, in _call
method = APIMethod(args, kwargs)
File "C:\Users\borde\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\binder.py", line 44, in __init__
raise TweepError('Authentication required!')
tweepy.error.TweepError: Authentication required!
I've tried resetting the keys, to make sure that they hadn't been timed out, but it still isn't working. I also tried changing the listener class so that it just prints out the found tweets, as opposed to retweeting them.
I'm completely new to this, and any help would be appreciated.
Thank you.
If you look at the documentation, you'll see that the first argument to that Stream call should be your instantiated api object's auth attribute:
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)
You just instantiated your api TWICE and not using it at all. Delete that duplicate line from search_tweets and instantiate stream like this:
stream = tweepy.Stream(auth=api.auth, listener = tweetlistener)
P.S. you're passing an instance instead of class, c/p the following instead of your function:
def search_tweets():
stream = tweepy.Stream(auth=api.auth, listener=listener)
stream.filter(track=keywords)
Btw, you should name your classes starting with uppercase letter, change class listener(tweepy.StreamListener): to class Listener(tweepy.StreamListener): and in that code I just provided: listener=Listener.

use google translate premium API by json

I am new to google translate api premium edition and json. I have the service account and the key credentials save in a json file. I want to use the 'nmt' model. The following are my python code. I can get the access token but still cannot make it run correctly. Please let me know which part I did wrong. I appreciate your help.
from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build
base_url = ['https://www.googleapis.com/language/translate/v2']
# load json credential keys
my_credentials = GoogleCredentials.from_stream('./data/TranslateAPI-cbe083d405fe.json')
# get access token
access_token = my_credentials.get_access_token(base_url)
# build service
service = build('translate', 'v2', credentials=access_token, model='nmt')
text = u'So let us begin anew--remembering on both sides that civility is not a sign of weakness, and sincerity is always subject to proof. Let us nevernegotiate out of fear. But let us never fear to negotiate.'
test = service.translations().list(q=text, target='es')
results = test.execute()
I got the following errors:
Traceback (most recent call last):
File "C:\Users\ying\workspace\GoogleTranslateAPI_v3\test1.py", line 32, in <module>
test = service.translations().list(q=text, target='es')
File "C:\Anaconda\lib\site-packages\googleapiclient\discovery.py", line 778, in method
headers, params, query, body = model.request(headers,
AttributeError: 'str' object has no attribute 'request'
You should use Google Cloud Translate Client
The client you are using doesn't support "NMT". The error you got in this case is about you entered wrong type of value to "model" parameter. The correct value should be a googleapiclient.Model

Python: how to login on Youtube

So, I'm a bit confused on how I get past authentication on Youtube using Python and successfully login. I always get error 403 when I try to PragmaticLogin():
yt_service = gdata.youtube.service.YouTubeService()
service.developer_key = 'MY Key'
service.client_id='My ID'
service.email = 'myemail#yahoo.gr'
service.password = 'mypassword'
service.source = 'my_program'
service.ProgrammaticLogin()
What do I have to do?
Update:
I think that it has to do with authentication. Do I need both developer_key and client_id? Where do I get each? I want to have rights to add comments to my videos etc.
Full error:
Traceback (most recent call last):
File "/home/bodhi32/Documents/bot.py", line 9, in <module>
client.ClientLogin(USERNAME, PASSWORD)
File "/usr/lib/pymodules/python2.7/gdata/service.py", line 833, in ClientLogin
self.ProgrammaticLogin(captcha_token, captcha_response)
File "/usr/lib/pymodules/python2.7/gdata/service.py", line 796, in ProgrammaticLogin
raise Error, 'Server responded with a 403 code'
gdata.service.Error: Server responded with a 403 code
ClientLogin is deprecated and has all sorts of errors. Don't use it.
Use OAuth2.
This sample should get you started:
https://github.com/youtube/api-samples/blob/master/python/my_uploads.py
Use your code but make sure you fill the developer_key and client_id fields ( check below how to get them).
yt_service = gdata.youtube.service.YouTubeService()
service.developer_key = 'MY Key'
service.client_id='My ID'
service.email = 'myemail#yahoo.gr'
service.password = 'mypassword'
service.source = 'my_program'
service.ProgrammaticLogin()
To obtain a youtube api go to
https://cloud.google.com/console/project and create a new project, then enable youtube.
Check this video for more info Obtaining a simple API key for use with the YouTube API

How to use refresh_access_token in the Yahoo Social Python SDK

I'm trying to use the Yahoo Social Python SDK to get a users contacts through oAuth. This is for a webapp running on App Engine. SO, I have everything set up to run through the oAuth dance, exchanging consumer keys and verifiers and all that jazz. I store the token and can reuse it to retrieve a users contacts until the token the expires an hour later. So, is there anyone out there who has used the Python SDK and can tell me what is wrong with this simple code:
import yahoo.application
CONSUMER_KEY = '####'
CONSUMER_SECRET = '##'
APPLICATION_ID = '##'
CALLBACK_URL = '##'
oauthapp = yahoo.application.OAuthApplication(CONSUMER_KEY, CONSUMER_SECRET, APPLICATION_ID, CALLBACK_URL)
oauthapp.token = yahoo.oauth.AccessToken.from_string(access_token) #access_token is legit string pulled from datastore
oauthapp.token = oauthapp.refresh_access_token(oauthapp.token)
contacts = oauthapp.getContacts()
Running this throws the following error:
'oauth_token'<br>
Traceback (most recent call last):<br>
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 513, in __call__<br>
handler.post(*groups)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/scripteditor.py", line 1249, in post<br>
oauthapp.token = oauthapp.refresh_access_token(oauthapp.token)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/application.py", line 90, in refresh_access_token<br>
self.token = self.client.fetch_access_token(request)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/oauth.py", line 165, in fetch_access_token<br>
return AccessToken.from_string(self.connection.getresponse().read().strip())<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/oauth.py", line 130, in from_string<br>
key = params['oauth_token'][0]<br>
KeyError: 'oauth_token'<br>
Basically, if I comment out the line with refresh_access_token, and the token has not expired, this code works and I get the users contacts. But with refresh_acces_token, it fails at that line. Can anyone give a hand?
Looks like something wrong with passing params. Try to debug oauth_token variable.
Solved. For reasons I can't understand, the above code now just works. It might have been a problem on yahoo's end, but I really can't be sure. It's been running fine for two weeks.

Categories