Authenticating other Users from my App - Tweepy - python

I've created an app in python to like tweets by hitting the POST endpoint -very simple.
Next I'd like to have an account different than mine able to login and authenticate to use the feature.
I have no clue how to do that and would appreciate any advice
I'm a junior dev, just starting to mess around with an API
for background: I'm going to implement this in flask but for now, just have a python like.py file with basic logic in it for my dev account authentication
import tweepy
import config
import time
client = tweepy.Client(
bearer_token=config.bearer_token,
consumer_key=config.consumer_key,
consumer_secret=config.consumer_secret,
access_token=config.access_token,
access_token_secret=config.access_token_secret
)
print('Sup Loser, what you wanna like? \n')
search = input('query: ')
query= f'{search} -is:retweet -has:media -is:reply'
response = client.search_recent_tweets(query=query, max_results=42)
for tweets in response.data:
id = tweets.id
print(f"searching '{search}' liking tweet -- ID# {id} -- URL https://twitter.com/twitter/statuses/{id}")
time.sleep(1)
client.like(id)

Related

How to post a tweet with media (picture) using Twitter API V2 and Tweepy Python?

i'm trying to create my first Twitter bot using Twitter API V.2 and Tweepy. So i can post simple text Tweets but i haven't found how to post tweets with medias (pictures) so how can i do that ? (I saw that some people say "you can't post media tweets using twitter API v2... You need to use API V 1.1 " so if it's true how can i use Twitter API V1.1 instead of API V2 ? )
Thank you if you can help me ^^
Here is my actual code :
from io import BytesIO
from PIL import Image
import tweepy
from tweepy import API
consumer_key = "APP_KEY"
consumer_secret = "APP_SECRET_KEY"
access_token = "TOKEN"
access_token_secret = "SECRET_TOKEN"
client = tweepy.Client(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret
)
response = client.create_tweet(
text="Just a dummy tweet",
# in_reply_to_tweet_id= 1484105392598749186 <--- Reply to a tweet by ID
)
print(f"https://twitter.com/user/status/{response.data['id']}")
If you are managing an Essential project, you need to apply for Elevated (it's free) in your project located on your Twitter Developer Portal, this is because an Elevated project can use both v1.1 and v2 (Essential only v2).
Once your submission is accepted, you must verify to allow read and write functions on your project (Developer Platform -> Project & Apps -> YOUR_PROJECT -> Development -> user authentication settings) selecting "OAuth 1.0a" and selecting "Read and Write".
Now, you can tweet media with the following code:
auth = tweepy.OAuth1UserHandler(
consumerKey,
consumerSecret,
accessToken,
accessTokenSecret
)
api = tweepy.API(auth)
media = api.media_upload(filename="./assets/twitter-logo.png")
print("MEDIA: ", media)
tweet = api.update_status(status="Image upload", media_ids=
[media.media_id_string])
print("TWEET: ", tweet)
For uploading media, you need to use the function media_upload (update_status_with_media is deprecated). This functions returns an Media object that have the attribute media_id_string, which is the element you need to make a tweet with a pic.

How to apply Spotify API authentication on my current code which uses Spotify Search API?

Earlier I was using Spotify's Search API
without any kind of authentication. But just last week or so, they made their API usage with Authentication only.
So since the past 2-3 days I've not been able to figure how this authorization works for Search API where I as a developer can let users access responses from Search API without having them to login with their Spotify accounts.
Can someone help me with this authorization stuff(The docs from Spotify don't solve my problem :< )
So here's the python code that I was earlier using -
import requests
import json
def Spotify(keyword):
url = "https://api.spotify.com/v1/search?q="+keyword+"&type=track&limit=1"
headers = {
'accept': "application/json",
'access_token':''
}
r = requests.get(url=url,headers=headers).text
jsonwa = json.loads(r)
name = jsonwa["tracks"]["items"][0]["name"]
artists = jsonwa["tracks"]["items"][0]["artists"][0]["name"]
song_preview_url = jsonwa["tracks"]["items"][0]["preview_url"]
image = jsonwa["tracks"]["items"][0]["album"]["images"][1]["url"]
return_this = []
return_this.append(name)
return_this.append(artists)
return_this.append(song_preview_url)
return_this.append(image)
print return_this
return return_this
song = "hello"
Spotify(song)
Per the web authorization docs:
All requests to the Spotify Web API require authorization
You'll need your users to grant permission for your app in order to get an access token. The user must be logged in to gran permission.
Once your app is granted permission by the user, you can use the refresh_token from that point on, and the user shouldn't need to grant permission again unless they revoke permission for example. You'll need to manage the access_token expiration.

Django users post to twitter

I use Django-social-auth to authenticate the users of a Django project. So I guess I have all the necessary information about a Twitter user to make a post on their behalf on their Twitter account. So do I really need to install a new app? or with the info at hand how would I do that? Isn't it just a matter of posting to a Twitter API with the relevant info?
You could just extract the code into your own project and that will work. But the benefits of using an open source library is that there's a good chance when Twitter or Social Network X changes it's API, the library, if popular, would get updated as opposed to you needing to make the change.
So if you use Django Social Auth you can do:
import urllib
import settings
import oauth2 as oauth
try:
twitter_user = user.social_auth.get(provider='twitter')
except:
return
if not twitter_user.tokens:
return
access_token = twitter_user.tokens['oauth_token']
access_token_secret = twitter_user.tokens['oauth_token_secret']
token = oauth.Token(access_token,access_token_secret)
consumer_key = settings.TWITTER_CONSUMER_KEY
consumer_secret = settings.TWITTER_CONSUMER_SECRET
consumer = oauth.Consumer(consumer_key,consumer_secret)
client = oauth.Client(consumer,token)
data = {'status':'Your tweet goes here'}
request_uri = 'https://api.twitter.com/1/statuses/update.json'
resp, content = client.request(request_uri, 'POST', urllib.urlencode(data))
Yes, I believe if you have the User's twitter account details that are necessary, then you can write an (django) app which will do so. You can use something like python-twitter to post to twitter.
You should be able to find more information regarding Twitter's api here.

Getting started with Twitter\OAuth2\Python

I'm attempting to connect to twitter using python, and I'm finding it really frustrating.
Everything I read suggests that I need a consumer key, a consumer secret, an access key and an access secret - for example: Using python OAUTH2 to access OAUTH protected resources
I can get the consumer key and the consumer secret from the twitter settings page for the little test app I created, but what about the other two? After a bit of googling it seems everyone thinks it's so obvious where you get this info from that it's not worth putting up, so I might be having a really dumb moment but could someone please spell it out for idiots like me please?
Edit:
OK to get these details open your app settings in Twitter and click the "My Access Token" link.
I suppose when looking for an Access Token, if you were to click on a link titled "My Access Token" might help. I'd love to attribute my stupidity to the wine, but really I don't know...
Almost all oauth examples on blogs seem to be examples of the authorisation phase of oauth and none focus on how to actually make requests once you have these, as once you understand how it works this part is quite obvious. Getting that initial understanding is quite difficult unfortunately.
If you're just trying access your twitter account from a script or app for yourself you can get the access token (called key in the python oauth library) and secret from dev.twitter.com at the bottom of the settings page for your app under the heading Your access token.
import oauth2 as oauth
import json
CONSUMER_KEY = "your app's consumer key"
CONSUMER_SECRET = "your app's consumer secret"
ACCESS_KEY = "your access token"
ACCESS_SECRET = "your access token secret"
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
access_token = oauth.Token(key=ACCESS_KEY, secret=ACCESS_SECRET)
client = oauth.Client(consumer, access_token)
timeline_endpoint = "https://api.twitter.com/1.1/statuses/home_timeline.json"
response, data = client.request(timeline_endpoint)
tweets = json.loads(data)
for tweet in tweets:
print tweet['text']
This example is using the python lib python-oauth2, which is an unfortunately named OAuth library not an OAuth2 library.
If you want to actually let other people authorise their account to be used by your app then you need to implement the redirect dance where you ask twitter for a request token/secret pair and then redirect the user to the twitter authorize page with this request token, they sign in and authorize the token and get redirected back to your application, you then exchange the request token for an access token and secret pair which you can store and use to make requests like above.
The Twitter Three-legged OAuth Example in the Readme at http://github.com/simplegeo/python-oauth2 seems to cover what needs to be done
Personally I use tweepy, it provides a nice python wrapper to Twitter's API

401 and 403 Errors with google base API

I built a wiki using Google App engine and the Data APIs. The wiki pages are stored as Google Base 'Reference Articles.' I want users to be able to view, edit, and delete the items, so when a request is made to the server, client login uses my username and password, and retrieves or edits the data on the user's behalf. The login code:
client = gdata.base.service.GBaseService()
client.ssl = False
gdata.alt.appengine.run_on_appengine(client)
#EMAIL, API_KEY and PASSWORD are constants stored on the server
client.email = EMAIL
client.password = PASSWORD
client.api_key = API_KEY
client.ProgrammaticLogin()
q = gdata.base.service.BaseQuery()
q.feed = '/base/feeds/items/' + self.base_id
item = base_client.GetItem(q.ToUri())
This works fine for me, but if I log out of my google account, it returns the following error:
'status': 401L, 'body': '<HTML>\n<HEAD>\n<TITLE>Authorization required</TITLE>
All I want is for the users to be able to CRUD my data stored on Base. What am I doing wrong?
Thanks in advance
It sounds like logging out in your client is invalidating all sessions for your account. Your best bet is probably to create a role account specifically for your app to use.

Categories

Resources