Facepy unable to upload image to Facebook - python

I'm trying to use Facepy, a sort of API for Facebook and Python, to simply post an image from my desktop to a Facebook page for which I have the authorization code and publish_stream and upload_photo permissions. (UPDATE: how do I verify that that is true?)
It's not working for me, though it is working for the author of Facepy. I'm at a loss for what is causing the issue. When I run this code, taken from the Facepy site (and using a .jpg on my computer):
UPDATE: This is the entirety of the code I am running:
from facepy import GraphAPI
print 'Trying Facebook page...'
my_token = 'xxxxxxxxxxxxxxxxx'
graph = GraphAPI(my_token)
# Get my latest posts
my_posts = graph.get("me/posts")
#Post a photo of a parrot
graph.post(path = "me/photos",source = open("python.png"))
print 'Done.'
Facepy returns this error:
Error: (#1) An unknown error occurred
I have tried it, unsuccessfully, with Python 2.5 and Python 2.7 on WinXP. Facepy can, however, get my latest posts, with graph.get('me/posts')
Any advice to get this to work would be appreciated.

I had the same problem. And apparently found the answer.
According to GitHub page, a source parameter needs a rb mode:
graph.post(
path = 'me/photos',
source = open('parrot.jpg', 'rb')
Works for me (with Python 3 & Graph API 2.8).
To publish from URL, you can use url:
par = {
"caption": "Some text",
"url": "https://example.com/1.jpg"}
send_post = graph.post(path='me/photos', **par)

Related

GitHub "Requires Authentication" error when using PyGithub

I was trying to figure out how to use the PyGithub module, but I keep getting the same error:
github.GithubException.GithubException: 401 {"message": "Requires authentication", "documentation_url": "https://docs.github.com/rest/reference/users#get-the-authenticated-user"}
My code is pretty simple, considering I just started out:
from github import Github
g = Github("Charonum","xxxxxxxx")
user = g.get_user()
print(user.name)
print(user.login)
The error is when it gets to print(user.name).
Looking at their documentation, it doesn't look like you're initializing the Github class correctly. I would read through that to find more about how to properly setup. The error is pretty clear that you don't have your authentication credentials input properly.
Example from the documentation:
from github import Github
# using an access token
g = Github("access_token")
# Github Enterprise with custom hostname
g = Github(base_url="https://{hostname}/api/v3", login_or_token="access_token")

Google Drive API v3 files.export method throws a 403 error: "Export only supports Docs Editors files."

Summary
Trying to download a JPEG file using files.export, but get a Error 403 message: "Export only supports Docs Editors files."
Description
I am trying to make use of Google Drive API for a project of mine, which is really all about collecting some pictures, storing them on the Drive, and later loading them back for some processing. Pretty straighforward.
To that extent, I am simply following the API Documentation and the example code snippets provided therein. Now, I was able to upload a picture to the storage. Trying to download it, I ran into this error message:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/1D1XpQwrCvOSEy_vlaRQMEGLQJK-AeeZ7/export?mimeType=image%2Fjpeg&alt=media returned "Export only supports Docs Editors files.". Details: "Export only supports Docs Editors files.">
The code use to upload the picture looks something like that:
import io
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
# GoogleDrive is a service created with googleapiclient.discovery.build
# upload a picture
file_metadata = {'name': 'example_on_drive.jpg'}
media = MediaFileUpload('example_upload.jpg', mimetype='image/jpeg')
file = GoogleDrive.files().create(
body=file_metadata,
media_body=media,
fields='id').execute()
The upload is successful, I get back the file's ID:
print(file)
{'id': '1aBoMvaHauCRyZOerNFfwM8yQ78RkJkDQ'}
and I can see it on my Google Drive.
Then I try to access that very same file:
request = GoogleDrive.files().export_media(fileId=file.get('id'), mimeType="image/jpeg")
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download %d%%" % int(status.progress() * 100))
At which point the error occurs. I see the API Explorer on the website return the same error, which is why I am tempted to conclude that my code is not to blame. This file.export only has two inputs and I don't see how exactly I am failing to use it correctly. I looked through similar questions, but most of them deal with downloading text documents and my error message tells me it's got something to do with the doctype. Am I using a wrong mimeType?
Error handling suggestions on the official page do not feature this particular error message.
Have you got any suggestions?
From the error message of Export only supports Docs Editors files., in order to download the files except for Google Workspace documents (Document, Spreadsheet, Slides and so on), unfortunately, the method of "Files: export" cannot be used. In your case, when you want to download the image file, please use the method of "Files: get". When your script is modified, it becomes as follows.
From:
request = GoogleDrive.files().export_media(fileId=file.get('id'), mimeType="image/jpeg")
To:
request = GoogleDrive.files().get_media(fileId=file.get('id'))
Reference:
Download files
About the download a file using "export" and "get", you can see it at above official document.

Fetching URL from a redirected target using Python

I'm building a Twitch chat-bot, integrating some Spotify features using Spotipy library.
The goal behind the implementation is to achieve full-automated Spotipfy API Authentication for the bot.
How the Spotify API and Spotipy library work is, an authorization token is needed first in order to do anything over Spotify-end. So that's why, whenever the bot is initially run over my VPS, it prompts me to copy a URL from the console, locate it on a browser to wait for its redirect and paste on the console the redirected URL including the desired token. That's how the authentication object retrieves the token data.
To automate this process, I've seen several solutions via Flask or Django.
Django implementation would be useful for me, since I also have Django environment active on the same VPS, except that Django environment runs on Python 2.7 while my Twitch chat-bot runs on a separate Python 3.6 environment. Hence, I would like to keep them separate unless there is no way to implement such automation without listening redirects over Django, Flask or any other web-framework. Unfortunately, my bot can only run on Python 3.6 or higher.
I'm specifically curious if there is any built-in function or a lightweight library to handle such operation.
The function which I'm using to fetch Spotify Auth token is:
def fetchSpotiToken():
global spotiToken, spoti
spotiToken = spotifyAuth.get_cached_token()
if not spotiToken:
spAuthURL = spotifyAuth.get_authorize_url()
print(spAuthURL)
# Prints the URL that Spotify API will redirect to
authResp = input("Enter URL")
# Console user is expected to visit the URL and submit the new redirected URL on console
respCode = spotifyAuth.parse_response_code(authResp)
spotiToken = spotifyAuth.get_access_token(respCode)
elif spotifyAuth.is_token_expired(spotifyAuth.get_cached_token()):
spotiToken = spotifyAuth.refresh_access_token(spotiToken["refresh_token"])
spoti = spotipy.Spotify(auth=spotiToken["access_token"])
return [spotiToken, spoti]
PS: I've been developing Python only for couple of weeks, even after doing some research, I wasn't able to find a solution to this problem in a way that I need. I'm not sure if it's even possible to achieve it that way. So, if that's impossible, please excuse me for my lack of knowledge.
I've found the solution myself.
It seems that requests is a good match for this example.
Following snippet works perfectly for now.
def tryFetchSpotiToken():
global spotiToken, spoti
try:
spotiToken = spotifyAuth.get_cached_token()
except:
if not spotiToken:
spAuthURL = spotifyAuth.get_authorize_url()
htReq = requests.get(spAuthURL)
htRed = htReq.url
respCode = spotifyAuth.parse_response_code(htRed)
spotiToken = spotifyAuth.get_access_token(respCode)
elif spotifyAuth.is_token_expired(spotifyAuth.get_cached_token()):
spotiToken = spotifyAuth.refresh_access_token(spotiToken["refresh_token"])
spoti = spotipy.Spotify(auth=spotiToken["access_token"])

Is there another reason for Illegal redirect_URI error when using Spotify API?

I am trying to use the Spotify API (using Spotipy), however I am having issues with the authentication step. I am following along a youtube playlist to learn it. To do that, I am just following along with the code that is shown below. However, when it opens into my web browser for authentication, I get an "Illegal redirect_uri" error.
I tried searching the web and came across this answer that says that it is probably a typo in the redirect_URI on the spotify website or that has been set in my environment variable, however, I have quadruple checked to make sure there was no typo. An image is attached that shows what my environment variable is and what the redirect_URI is set as in spotify.
Is there another reason that I could be getting this error?
Thank you for the help. Spotify Redirect_URI
import os
import sys
import json
import spotipy
import webbrowser
import spotipy.util as util
from json.decoder import JSONDecodeError
#Get the username from terminal
username = sys.argv[1]
# Erase cache and prompt for user permission
try:
token = util.prompt_for_user_token(username)
except:
os.remove(f".cache-{username}")
token = util.prompt_for_user_token(username)
#Create our spotifyObject
spotifyObject = spotipy.Spotify(auth=token)
It is probably a security issue, since google.com will not understand the parameters of the request sent by the Spotify API. It looks like you are not trying to intercept the request (since you are using google.com), so you could try to use https://localhost:8080/ as the redirect url. Since there is (probably) no server running locally, no page will open (and you will get an error), but you only need to copy the url in the address bar ;-)

Authentication OneDrive API Python

Using code sample from GitHub that is specifically for setting up authentication for Python access to OneDrive API (I'm beginning to think this source is outdated), I've failed to make it past the part where you paste code provided by Microsoft after executing program..
Python code:
import onedrivesdk
redirect_uri = 'https://login.microsoftonline.com/common/oauth2/nativeclient'
client_secret = '*this code omitted*'
client_id='*this code omitted*'
api_base_url='https://api.onedrive.com/v1.0/'
scopes=['onedrive.readwrite']
http_provider = onedrivesdk.HttpProvider()
auth_provider = onedrivesdk.AuthProvider(
http_provider=http_provider,
client_id=client_id,
scopes=scopes)
client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
# Ask for the code
print('Paste this URL into your browser, approve the app\'s access.')
print('Copy everything in the address bar after "code=", and paste it below.')
print(auth_url)
code = raw_input('Paste code here: ')
client.auth_provider.authenticate(code, redirect_uri, client_secret)
After executing code and pasting url in browser, a popup shows up, where I verify that I want to give my app access to API.. I hit "Ok."
I am then presented with code in URL taskbar. I copy and paste code into program..
Then the error I get is:
raise Exception(str(message["error"]))
Exception: invalid_request
Link to GitHub source used: https://github.com/OneDrive/onedrive-sdk-python
Note: I had to omit scopes such as the first two in this list:
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
because they apparently don't exist (according to error code provided by Microsoft after pasting URL into taskbar)
Is there a better source for setting up authentication for a Python program to communicate with OneDrive API?
I am a relatively new Python user, your patience is appreciated.
I ran into the same issue and the solution was to include the redirect_uri in the app registration.
This can be done at https://portal.azure.com/ und Azure Active Directory > App registrations > "Your App" > Authentication. In my case, I needed to add http://localhost:8080/ to the redirect URIs.
I found the suggestion here:
https://github.com/OneDrive/onedrive-sdk-python/issues/98
Hope it helps someone save some time.

Categories

Resources