Not able to upload image in created album: Imgur python - python

I am trying to create an album and upload images into it using imgurpython. However, I am not able to attach images to the album. It is giving me following error: (403) The album you're requesting does not belong to your account. Following is my code:
client = ImgurClient(client_id, client_secret)
def CreateAlbumAndUploadImages(albumName,albumDescription,images):
fields = {}
fields['title'] = albumName
fields['description'] = albumDescription
fields['privacy'] = 'public'
x = client.create_album(fields)
print(x)
y = client.album_add_images(x['id'],images) #error here
print(y)
return x
def UploadPhoto(images):
config = {
'name': 'some image name here',
'title': 'some title here',
'description': 'some description here'}
image = client.upload_from_path(image_path, config=config, anon=False)
print("Done")
print(image)
return image
def main():
#x = CreateAlbum('Album 101','Album 101 desciption')
id = []
id.append( UploadPhoto(['image1.jpg'])['id'])
id.append( UploadPhoto(['image2.jpg'])['id'])
x = CreateAlbumAndUploadImages('albumNameHere','some description here',id)
pass
if __name__ == '__main__':
main()
NOTE: I am trying to build a bot, hence calling authorize on web is not an option

I had a similar problem and figured it out by realizing that I hadn't fully authenticated the client. To do so you must do this:
client = ImgurClient(client_id,client_secret, refresh_token)
client.set_user_auth(access_token, refresh_token)
Then it should work. If you need to get access and refresh token then do:
client = ImgurClient(client_id, client_secret)
print client.get_auth_url('pin') #go to page and copy down pin
creds = client.authorize(raw_input('Pin: '), 'pin')
client.set_user_auth(creds['access_token'], creds['refresh_token'])
#You will only need to do this once per user, store tokens
After that, just save your access token and refresh token and just include it in the first example.

Related

Obtain Intents, Entities and the training data from Dialogflow in the python environment

I want to know if there is some way through which I can obtain all the Intents(its corresponding questions), Entities and the training data(I defined in Google Dialogflow) programmatically using python.
Following is the code(works fine) through which i get a response from dialogflow.
GOOGLE_APPLICATION_CREDENTIALS = '###'
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] =
GOOGLE_APPLICATION_CREDENTIALS
def dialogflow_api_response(text):
session_client = dialogflow.SessionsClient()
session = session_client.session_path('###', '##')
text_input = dialogflow.types.TextInput(text=text, language_code='en')
query_input = dialogflow.types.QueryInput(text=text_input)
response = session_client.detect_intent(session=session, query_input=query_input)
jsonObj = MessageToJson(response)
x = json.loads(jsonObj)
If there is, please point me in the right direction.
Thank you
Yes it is possible to get all the intents, entities, unserEntities and contexts from Dialogflow agent using Dilogflow API as JSON object. Here's the code to get the list of intents:
def list_intents(project_id):
import dialogflow_v2 as dialogflow
intents_client = dialogflow.IntentsClient()
parent = intents_client.project_agent_path(project_id)
intents = intents_client.list_intents(parent)
for intent in intents:
print('=' * 20)
print('Intent name: {}'.format(intent.name))
print('Intent display_name: {}'.format(intent.display_name))
print('Action: {}\n'.format(intent.action))
print('Root followup intent: {}'.format(
intent.root_followup_intent_name))
print('Parent followup intent: {}\n'.format(
intent.parent_followup_intent_name))
print('Input contexts:')
for input_context_name in intent.input_context_names:
print('\tName: {}'.format(input_context_name))
print('Output contexts:')
for output_context in intent.output_contexts:
print('\tName: {}'.format(output_context.name))
for training_phrase in intent.training_phrases:
train_phrase = training_phrase.parts[0].text
print(train_phrase)
For further information you can refer to DF official gitHub here

Adding Image to google slide from google drive or local stored one

getting "Invalid requests[0].createImage: Access to the provided image was forbidden."
on adding image from google drive to google slides
Here below the code snippet I've tried
although making the image public through advanced sharing option.
the service account has edit access to the slide I want to add image to it.
import section: add here the required dependencies
# python build-in modules
import json
import time
import io
# external modules
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from apiclient.http import MediaFileUpload
# user modules
from via_types import BasePlugin
class GoogleSlidesPlugin(BasePlugin):
"""
this plugin allows to communicate with Google API and Google Spreadsheets
by using the already created credentials
"""
def __init__(self):
BasePlugin.__init__(self)
self.Scopes = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.readonly','https://www.googleapis.com/auth/presentations','https://www.googleapis.com/auth/presentations.readonly']
self.Creds = ServiceAccountCredentials.from_json_keyfile_name(
r'Libraries/credentials/lucky-dahlia-268410-c4c0c57c1908.json', self.Scopes)
self.service = build('slides', 'v1', credentials=self.Creds)
self.drive = build('drive', 'v3', credentials=self.Creds)
def add_images_to_gslides(self, args):
"""
Adds a new worksheet to a spreadsheet.
:param args: [0]: Presentation
[1]: images array Paths
[2]: slide number to insert images
:param uid: this value is automatically generated for groped steps
:return: the detail and status execution of plugin
"""
# start results to report to output
self.response.status = 'pass'
self.response.details = 'image/s was/were added to slides'
try:
# try to store the passed arguments0
presentation_id = args[0]
except Exception as e:
# if there is a missed argument the command is going to end its exec
# store the results to report in output
self.response.status = 'fail'
self.response.details = 'some argument was missed'
return self.response
try:
# open connection with an specific GSlide
presentation = self.service.presentations().get(presentationId=presentation_id).execute()
slides = presentation.get('slides')
print('The presentation contains {} slides:'.format(len(slides)))
for i, slide in enumerate(slides):
print('- Slide #{} contains {} elements.'.format(
i + 1, len(slide.get('pageElements'))))
IMG_FILE = args[1]
try :
print('** Searching for icon file')
rsp = self.drive.files().list(q="name='%s'" % IMG_FILE).execute().get('files')[0]
print(' - Found image %r' % rsp['name'])
IMAGE_URL = 'https://drive.google.com/uc?export=download&id=' + rsp['id']
#IMAGE_URL = 'https://drive.google.com/file/d/'+rsp['id']+ '/edit'
except Exception as e:
file_metadata = {'name': IMG_FILE}
media = MediaFileUpload(IMG_FILE, mimetype='image/png')
upload = self.drive.files().create(body=file_metadata, media_body=media, fields='webContentLink, id, webViewLink').execute()
fileId = upload.get('id')
IMAGE_URL = upload.get('webContentLink')
self.drive.permissions().create(fileId=fileId, body={'type': 'anyone','role': 'writer'}).execute()
print(IMAGE_URL)
requests = []
image_id = 'MyImage_02'
page_id = slide['objectId']
emu4M = {
'magnitude': 4000000,
'unit': 'EMU'
}
requests.append({
'createImage': {
'objectId': image_id,
'url': IMAGE_URL,
'elementProperties': {
'pageObjectId': page_id,
'size': {
'height': emu4M,
'width': emu4M
},
'transform': {
'scaleX': 1,
'scaleY': 1,
'translateX': 100000,
'translateY': 100000,
'unit': 'EMU'
}
}
}
})
body = {
'requests': requests
}
response = self.service.presentations() \
.batchUpdate(presentationId=presentation_id, body=body ).execute()
create_image_response = response.get('replies')[0].get('createImage')
print('Created image with ID: {0}'.format(
create_image_response.get('objectId')))
except Exception as e:
self.response.status = 'fail'
self.response.details = e
return self.response
if __name__ == '__main__':
# use_the_main_function_to_test_your_plugin_without_using_a_sequence
plugin_template = GoogleSlidesPlugin()
plugin_template.add_images_to_gslides([presentationID,'image.png'])
print(plugin_template.response.status,
plugin_template.response.details)
I also wanted to find a way to upload images to Google Slides using Python. I created a program that uploads images to Google Cloud Storage (instead of Google Drive); creates a signed URL for them; then uses that URL to import images into Google Slides. It's available here under the MIT License and may be a helpful tool/resource.

Way2SMS python code not sending SMS whereas POSTS returns Success

I get Successful status code for my POST requests , Login is working fine , but the SMS is not sent
I have gone through all codes on internet, most of them are out-dated, as the site has changed its code.
import requests as req
def login_way2sms():
with req.Session() as mySession:
url = 'http://www.way2sms.com/re-login'
home_url = 'http://www.way2sms.com/'
mobile = [your registered mobile number]
password = [your password]
headers = dict(Referrer="http://www.way2sms.com/")
before = mySession.get(home_url)
login_data = dict(mobileNo=mobile, password=password, CatType='', redirectPage='', pid='')
mySession.post(url, data=login_data, headers=headers)
after = mySession.get(home_url)
return mySession
def send_msg(mysession): #saw sendsms-toss in Inspect under Network tab
url = 'http://www.way2sms.com/smstoss'
home_url = 'http://www.way2sms.com/'
sms_url = 'http://www.way2sms.com/send-sms'
group_contact_url = 'http://www.way2sms.com/GroupContacts'
web_msg_count_url = 'http://www.way2sms.com/CheckWebMsgCount'
headers = dict(Referrer="http://www.way2sms.com/send-sms")
before = mysession.get(home_url)
token = '2B7CF7C9D2F14935795B08DAD1729ACF'
message = 'How to make this work?'
mobile = '[a valid phone number]'
ssaction = 'undefined'
senderid = 'WAYSMS'
msg_data = dict(Token=token, message=message, toMobile=mobile, ssaction=ssaction, senderId=senderid)
mysession.post(url, data=msg_data, headers=headers)
after = mysession.get(home_url)
mysession.post(group_contact_url, headers=headers)
group_contacts = mysession.get(sms_url)
mysession.post(web_msg_count_url, headers=headers)
web_msg_count = mysession.get(sms_url)
# last 2 POST requests send after clicking the Send Msg button
def main():
login_way2sms() #login using username and password
send_msg(currsession) #send sms
main()
I finally got it right , Thanks for replying. We can do it without using the apikey and secret keys as well, Here take a look at this. And init is just another script where constant urls and login is defined, nothing much there.
import requests as req
import init
def login_way2sms(credential):
with req.Session() as mySession:
mobile = credential.username
password = credential.password
headers = dict(Referrer="http://www.way2sms.com/")
login_data = dict(mobileNo=mobile, password=password, CatType='', redirectPage='', pid='')
mySession.post(init.login_url, data=login_data, headers=headers)
return mySession
def get_token(mysession):
cookies = mysession.cookies['JSESSIONID']
token = cookies[4:]
return token
def send_msg(mysession, token):
"""
:rtype: req.Session()
"""
headers = dict(Referrer="http://www.way2sms.com/send-sms")
message = 'Hi, I am Upgraded a little!!!'
mobile = '[valid phone]'
msg_data = dict(Token=token, message=message, toMobile=mobile, ssaction=init.ssaction, senderId=init.senderid)
mysession.post(init.sms_url, data=msg_data, headers=headers)
def main():
credential = init.enter_credentials()
currsession = login_way2sms(credential)
reply = currsession.get(init.home_url)
page_content: str = str(reply.content)
if (reply.status_code == 200) and (page_content.find('send-sms', 10, 200) != -1):
print("Login Successful!\n")
else:
print("Login Failed , Try again\n")
credential = init.enter_credentials()
currsession = login_way2sms(credential)
token = get_token(currsession)
send_msg(currsession, token)
main()
The following method and code worked for me after creating a free account at way2sms (I hope you already did it). Then click on API tab then campaign at left. Then create test API and Secret Key (free with 25 message limit). Then use the following code--
import requests
import json
URL = 'http://www.way2sms.com/api/v1/sendCampaign'
# get request
def sendPostRequest(reqUrl, apiKey, secretKey, useType, phoneNo, senderId, textMessage):
req_params = {
'apikey':'your_apiKey',
'secret':'your_secretKey',
'usetype':'stage'
'phone': 'receiving_phone_number',
'message':'The textMessage I want to send',
'senderid':'Your Name'
}
return requests.post(reqUrl, req_params)
# get response
response = sendPostRequest(URL, 'provided-api-key', 'provided-secret', 'prod/stage', 'valid-to-mobile', 'active-sender-id', 'message-text' )
"""
Note:-
you must provide apikey, secretkey, usetype, mobile, senderid and message values
and then requst to api
"""
# print response if you want
print response.text
Just fill the fields and run in python 2.7. Working perfectly on any Indian number.

Facebook sdk python outputting access token without login?

I am creating a python reaction tester and I wish to share scores to facebook, however the sdk is confusing me greatly. I have got an access token without prompting a log in page, and the token appears in the web browser instead of the login. This is the code I have and an image of the result:
def facebookShare():
appID = '[removed]'
appSecret = '[removed]'
authArguments = dict(client_id = appID,
client_secret = appSecret,
redirect_uri = 'http://localhost:8080/',
grant_type = 'client_credentials',
state='abc123')
authCommand = 'https://graph.facebook.com/v3.2/oauth/access_token?' + urllib.parse.urlencode(authArguments)
authResponse = os.startfile(authCommand)
try:
authAccessToken = urllib.parse.parse_qs(str(authResponse))['access_token']
graph = facebook.GraphAPI(access_token=authAccessToken, version="3.2")
facebookResponse = graph.put_wall_post('I got an average time of ' + averageTime + 'seconds!')
except KeyError:
errorWindow = tkinter.Toplevel(root, bg = "blue")
tkinter.Label(errorWindow, text = "Something Went Wrong.", bg = "red").pack()
Shouldn't it need to log in to generate the access token? How can I make this generate a log in so it can print to the user's wall how it is supposed to? What URL would I need to use to get a login dialog?

Uploading files in Google App Engine. How to get the file to the upload Handler Class

I have a form in google app engine where I want to upload an image and all my text at the same time. Do I have to seperate this into two seperate pages and actions?
Here is my upload handler:
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def upload(self, reseller_id, imgfile):
upload_files = imgfile
blob_info = upload_files[0]
key = blob_info.key()
r = Reseller.get_by_id(reseller_id)
r.blob_key_logo = str(key)
r.put();
Here is my creation of a new reseller object:
class NewReseller(BaseHandler):
def get(self):
if self.user:
self.render("new_reseller.html")
else:
self.redirect("/display_resellers")
def post(self):
name = self.request.get('name')
website = self.request.get('website')
information = self.request.get('information')
address = self.request.get('address')
city = self.request.get('city')
state = self.request.get('state')
zipcode = self.request.get('zipcode')
email = self.request.get('email')
phone = self.request.get('phone')
r = Reseller( name = name,
website = website,
information = information,
address = address,
city = city,
state = state,
zipcode = zipcode,
email = email,
phone = phone)
r.put()
theresellerid = r.key().id()
#And then Upload the image
u = UploadHandler()
logo_img = u.get_uploads('logo_img')
u.upload(theid, logo_img)
self.redirect('/display_resellers')
I think my problem here is this line:
logo_img = u.get_uploads('logo_img')
it pops out the error message
for key, value in self.request.params.items():
AttributeError: 'NoneType' object has no attribute 'params'
Somehow I need this NewReseller class to inherit the .getuploads from BlobstoreUploadHandler so I can do:
logo_img = self.get_uploads('logo_img')
Or there is probably a better way because this seems a little messy.
So my question is how to upload files and data in one form on just one page. I could do it with two seperate pages. One for adding the reseller and one for adding the image but that seems over complicated.
I tried to follow some steps and clues from this question:
Upload files in Google App Engine
******Edit***** Working Implementation Below:
class EditReseller(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
def get(self, reseller_id):
if self.user:
reseller = Reseller.get_by_id(int(reseller_id))
upload_url = blobstore.create_upload_url('/upload')
image = True
if reseller.blob_key_logo is None:
image = False
self.render('edit_reseller.html', r=reseller, reseller_id=reseller_id, upload_url=upload_url, image=image)
else:
self.redirect('/admin')
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
reseller_id = self.request.get('reseller_id')
upload_files = self.get_uploads('logo_img')
if upload_files:
blob_info = upload_files[0]
key = blob_info.key()
r = Reseller.get_by_id(int(reseller_id))
r.blob_key_logo = str(key)
r.put();
name = self.request.get('name')
website = self.request.get('website')
information = self.request.get('information')
address = self.request.get('address')
city = self.request.get('city')
state = self.request.get('state')
zipcode = self.request.get('zipcode')
email = self.request.get('email')
phone = self.request.get('phone')
if name and website and information and email and phone and address and city and state and zipcode:
r = Reseller.get_by_id(int(reseller_id))
r.name = name
r.website = website
r.information = information
r.address = address
r.city = city
r.state = state
r.zipcode = zipcode
r.email = email
r.phone = phone
r.put()
else:
error = "Looks like your missing some critical info"
self.render("edit_reseller.html", name=name, website=website, information=information, address=address, city=city, zipcode=zipcode, email=email, phone=phone, error=error)
self.redirect("/edit_reseller/" + reseller_id)
You just need to put the logic of the UploadHandler inside the Reseller(BaseHandler) and make Reseller inherit from blobstore_handlers.BlobstoreUploadHandler.
The call to get_uploads fails, as the NewReseller Class does not inherit from BlobstoreUploadHandler. The BlobstoreUploadHandler class takes over the upload operation so you do not need to create a post method, just add the corresponding logic from post ( name = self.request.get('name'), r = Reseller(), r.put(), etc. ) and add it to the upload method.
You should not call or create a new a handler instance by hand (unless you know what you are doing), as it would be missing the things that make it work.
The complete app sample at the official docs, might also be helpful.

Categories