Update status Facebook using Python - python

I'm trying the solve problem update status using facebook API with pyfacebook. So I look at here Update Facebook Page's status using pyfacebook and I think doesn't work anymore.
Well, finally I solve the problem:
#!/usr/bin/python
import facebook
# Replace these with your app's credentials
api_key = 'YOUR_API_KEY'
secret_key = 'YOUR_SECRET_KEY'
client = facebook.Facebook(api_key, secret_key)
client.auth.createToken()
client.login()
print '[*] Please login / give permission application to access you . Then press enter key to continue...',
raw_input()
try:
client.auth.getSession()
client.request_extended_permission("publish_stream", popup=False)
raw_input()
cek = client.status.set("Testing update status using facebook API with pyfacebook")
except facebook.FacebookError, e:
print "ERROR", e

Related

atlassian-python-api exception by using confluence.delete_attachment()

i try to delete all attachments from a site with confluence.delete_attachment(page_id, filename, version), butt it throws always the same exception:
requests.exceptions.HTTPError: 401 Client Error: Authorization Required for url:
I am currently deleting the attachments as follows:
from atlassian import Confluence
confluence_url = 'https://xxx/confluence/'
confluence_usr = os.environ.get('CONFLUENCE_CREDS_USR')
confluence_psw = os.environ.get('CONFLUENCE_CREDS_PSW')
confluence = Confluence(url=confluence_url, username=confluence_usr, password=confluence_psw)
# Check site response, if site not reachable, check 5 times every 5 sec
response = resilient_confluence_http_get_request(f'{confluence_url}rest/api/content/{page_ids[csv_file]}')
# Check site response, if site not reachable, check 5 times every 5 sec
attachment = confluence.get_attachments_from_content(page_ids[csv_file])
print(f"attachment type: {type(attachment)}")
print(f"attachment content:\n {attachment}\n\n")
att_to_del = []
indices = 0
for i in attachment['results']:
print(f"id type: {type(attachment['results'][indices]['id'])}")
att_to_del.append(attachment['results'][indices]['id'])
indices += 1
print(f"delete attachments with id's {att_to_del}")
for id_to_delete in att_to_del:
response = requests.delete(f'https://xxx/confluence/rest/api/content/{id_to_delete}',
auth=(confluence_usr, confluence_psw))
The delete function is the only one that doesn't work. What am I doing wrong?
Here i try to delete with confluence.delete_attachment(...):
def response_wait_repeat():
attachments = confluence.get_attachments_from_content('my_site_id')
print(attachments)
confluence.delete_attachment('my_site_id', 'my_filename', version=None)
I assume you are using atlassian-python-api
as the examples on the pypi documentation, you first need to create a connection to the confluence:
from atlassian import Confluence
confluence = Confluence(
url='http://localhost:8090',
username='admin',
password='admin')
status = confluence.create_page(
space='DEMO',
title='This is the title',
body='This is the body. You can use <strong>HTML tags</strong>!')
print(status)
If you are still getting this error (401 Authorization Required) I would check manually in confluence, whether you have the permission to do these such actions.
It's probably the case, because you are saying the only action you cannot preform is delete.
otherwise I would contact the confluence admin.

How to successfully receive Google Drive v3 Push Notifications using python?

I have completed the steps provided by Google to implement push notifications using the Drive API. Everything goes as described except I do not receive any notifications from Google whenever a change occurs (listed as Step 4 below).
Below is a summary of the steps I followed and the results at each stage:
Step 1 (Success): Verify that you own the domain
I went to Search Console as directed and successfully verified the site.
Step 2 (Success): Register your domain
I visited the Domain Verification page and added my domain in the API Console. Google API Console updated to show the list with my desired domain.
I have a valid SSL certificate from GoDaddy for my domain and have verified that as well.
Step 3 (Success): Created my notification channel
Using the python SDK, I created the channel and got back a response from Google. The python code below shows how I did this. Note: The address included in my request directs Google to send notifications to my Flask website that I am hosting in Google's App Engine. I am showing the domain as my_domain.com here for privacy as I am in the process of bringing up the site.
channel_id = str(uuid.uuid4())
body = {
'kind': 'api#channel',
'id': channel_id,
'type': 'web_hook',
'address': "https://my_domain.com/notifications"
}
try:
start_page_token = service.changes().getStartPageToken().execute().get('startPageToken');
print(service.changes().watch(pageToken=start_page_token, body=body).execute())
except Exception as e:
print('Exception: {}'.format(e))
And here is the response from Google:
{u'resourceId': u'vTMwJWl7a23Af1LK1TpJZ38eO_0', u'kind': u'api#channel', u'expiration': u'1538433975000', u'id': u'dce14225-95c8-42a7-9945-4fed1604c848', u'resourceUri': u'https://www.googleapis.com/drive/v3/changes?alt=json&includeCorpusRemovals=false&includeRemoved=true&includeTeamDriveItems=false&pageSize=100&pageToken=4919&restrictToMyDrive=false&spaces=drive&supportsTeamDrives=false&alt=json'}
Step 4 (Failed): Process a notification from Google
I am running a Flask website on App Engine and created an app.route to receive notifications from Google. I've included the code below. I never receive anything at this URL.
#app.route('/notifications')
def notifications():
print('in notifications()')
try:
chan_id = request.args.get('X-Goog-Channel-ID', 'empty')
msg_num = request.args.get('X-Goog-Message-Number', 'empty')
rid = request.args.get('X-Goog-Resource-ID', 'empty')
state = request.args.get('X-Goog-Resource-State', 'empty')
resource_uri = request.args.get('X-Goog-Resource-URI', 'empty')
goog_changed = request.args.get('X-Goog-Changed', 'empty')
goog_chan_exp = request.args.get('X-Goog-Channel-Expiration', 'empty')
goog_chan_token = request.args.get('X-Goog-Channel-Token', 'empty')
print('chan_id: {}'.format(chan_id))
print('msg_num: {}'.format(msg_num))
print('rid: {}'.format(rid))
print('state: {}'.format(state))
print('resource_uri: {}'.format(resource_uri))
print('goog_changed: {}'.format(goog_changed))
print('goog_chan_exp: {}'.format(goog_chan_exp))
print('goog_chan_token: {}'.format(goog_chan_token))
except Exception as e:
print('notifications() exception: {}'.format(e))
print('leaving notifications()')
return jsonify(result='done')
I'm not sure if this is the problem but, when I tried Google Drive push notifications, I didn't use the SDK. I only made a POST request as it shows in the documentation.
Could you try to make a POST request to "https://www.googleapis.com/drive/v3/changes/watch" instead of using service.changes().watch()?
You will need an access_token for the request, but I believe you wont need to send a startPageToken as they don't use it in their example:
I hope it helps!

Python spotipy Oauth : Bad request

This is my code
UserScope = 'user-library-read'
util.prompt_for_user_token(username='vulrev1',scope=UserScope,client_id="533adb3f925b488za9d3772640ec6403",client_secret='66054b185c7541fcabce67afe522449b',redirect_uri="http://127.0.0.1/callback")
lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp'
spotify = spotipy.Spotify()
results = spotify.artist_top_tracks(lz_uri)
for track in results['tracks'][:10]:
print ('track : ' + track['name'])
I'm getting this
spotipy.oauth2.SpotifyOauthError: Bad Request
I'm not quite sure what's going on here, is there something I need to do with the host files ? because http://127.0.0.1 refuses to connect
token = util.prompt_for_user_token(username='vulrev1',scope=UserScope,client_id="533adb3f925b488za9d3772640ec6403",client_secret='66054b185c7541fcabce67afe522449b',redirect_uri="http://127.0.0.1/callback")
spotify = spotipy.Spotify(auth=token)
You have to send your token as a auth. And also i think you must change your user ID to the specific numbers where u can find at the link of your profile.

How can we check if our app is installed for some organizations but not all of them?

We created an application for Google Apps Marketplace. Our app works only if it's installed for everyone. But the problem is, some customers install our app for some organizations, not everyone. We want to display a specific message to those customers, but the problem is that we don't know if our app is installed for some organizations, or not installed at all. Therefore, customers who installed our app for some organizations get a message which is intended for customers who didn't install our app at all. We show them the install button but nothing happens when they install our app again, because it's already installed. We want to give them instructions how to change our app's status to "on for everyone".
How can we check if our app is installed for some organizations? We get the following error message from Google:
Failed to retrieve access token: {
"error" : "unauthorized_client",
"error_description" : "Unauthorized client or scope in request."
}
Which is the same error message we receive for cutomers who didn't install our app at all.
This is the Python function who throws the exception:
def _do_refresh_request(self, http_request):
"""Refresh the access_token using the refresh_token.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
body = self._generate_refresh_request_body()
headers = self._generate_refresh_request_headers()
logger.info('Refreshing access_token')
resp, content = http_request(
self.token_uri, method='POST', body=body, headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if loads fails?
d = simplejson.loads(content)
self.token_response = d
self.access_token = d['access_token']
self.refresh_token = d.get('refresh_token', self.refresh_token)
if 'expires_in' in d:
self.token_expiry = datetime.timedelta(
seconds=int(d['expires_in'])) + datetime.datetime.utcnow()
else:
self.token_expiry = None
if self.store:
self.store.locked_put(self)
else:
# An {'error':...} response body means the token is expired or revoked,
# so we flag the credentials as such.
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
self.invalid = True
if self.store:
self.store.locked_put(self)
except StandardError:
pass
raise AccessTokenRefreshError(error_msg)
Update 1: in Apps > Marketplace apps, an app can be on for everyone, on for selected orgs or off. We need to know the status of our app.
Update 2: I tried calling check_general_access but also when our application is uninstalled we receive True (Application has general access). This is after we confirmed that check_access returned False.
#staticmethod
def check_access(admin_email):
http = httplib2.Http()
credentials = SignedJwtAssertionCredentials(
SERVICE_EMAIL,
PRIVATE_KEY,
scope='https://apps-apis.google.com/a/feeds/emailsettings/2.0/ https://www.googleapis.com/auth/admin.directory.user.readonly',
sub=str(admin_email),
)
http = credentials.authorize(http)
try:
service = build(serviceName='admin', version='directory_v1', http=http)
logging.info("Application has access to admin's %s domain" % (admin_email))
return True
except Exception as e:
logging.info("Application does not have access to admin's %s domain (exception: %s)" % (admin_email, e.message))
return False
#staticmethod
def check_general_access():
http = httplib2.Http()
credentials = SignedJwtAssertionCredentials(
SERVICE_EMAIL,
PRIVATE_KEY,
scope='https://apps-apis.google.com/a/feeds/emailsettings/2.0/ https://www.googleapis.com/auth/admin.directory.user.readonly',
)
http = credentials.authorize(http)
try:
service = build(serviceName='admin', version='directory_v1', http=http)
logging.info("Application has general access")
return True
except Exception as e:
logging.info("Application does not have general access (exception: %s)" % e.message)
return False
Not sure, but may have found a way. From the documentation I asserted that domain wide access is needed to impersonate a user within the target domain. Service apps do not need this for other tasks. While convoluted, you can test if you get credentials without the sub parameter to SignedJwtAssertionCredentials. If this succeeds, but adding the sub parameter fails, you're installed but not domain wide.
Let us know if this works and obviously Google has some work to do there still.
You can add ping back, every hour or so call some end point. If the ping was too long ago they probably remove the app

Python - Facebook API - Need a working example

Ok, so i've googled around, i've found threads here on stackoverflow and i've checked the official Facebook wiki and.. and what not..
I now hope that one of you guys sits on a Facebook API sample code for Python.
This is what i've got so far and all i get is "Invalid Signature" via PyFacebook which appears to be a dead project:
from facebook import Facebook
api_key = '123456789______'
secret = '<proper secret key>'
OTK = 'XXXXX' # <-- You get this from: https://www.facebook.com/code_gen.php?v=1.0&api_key=123456789______
long_term_key = None
fb = Facebook(api_key, secret)
def generate_session_from_onetime_code(fb, code):
fb.auth_token = code
return fb.auth.getSession()
if not long_term_key:
long_term_key = generate_session_from_onetime_code(fb, OTK)['session_key']
print 'Replace None with this in the .py file for long_term_key:'
print long_term_key
fb.session_key = long_term_key
fb.uid = 000000001 # <-- Your user-id
fb.signature = api_key # <-- This doesn't work at all, MD5 of what?
#fb.validate_signature(fb) # <-- doesn't work either, prob need to pass MD5 handle?
print fb.friends.get() # <-- Generates "Invalid Signature"
"all" i want, is to retrieve my friends list for now,
if there's a better API point me in the right direction but Facebook has officially declared their own Python SDK dead and pyfacebook is almost working for me but not quite..
So, please help.
The unofficial fork of the python sdk is still working fine for me.
To retrieve your friends, generate an access token here:
https://developers.facebook.com/tools/access_token/
Limitations:
A user access token with user_friends permission is required to view
the current person's friends.
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
Code
import facebook
token = 'your token'
graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
friend_list = [friend['name'] for friend in friends['data']]
print friend_list

Categories