same error, i am getting problem with docusign Getting envelope info - docusignapi

api_client = ApiClient()
api_client.host = base_path
api_client.set_default_header('Authorization', 'Bearer' + token['access_token'])
envelope_api = EnvelopesApi(api_client)
try:
results=envelope_api.create_envelope(account_id=account_id, envelope_definition=envelope_definition)
envelope_id = results.envelope_id
except Exception as e:
logger.error(e.body.decode())
return None
return results

Related

Tinder API Authentication Token Retrieval

I'm working on implementing an AI bot that uses DiauogeFlow to have intelligent conversations with my matches. The link to the github package that contains all the scripts is here: https://github.com/nathan-149/tinderbot
I am at this point just trying to get the authentication token in order to hook up the bot, here is the code for the first script which is supposed to return the API token:
import json
import requests
CODE_REQUEST_URL = "https://api.gotinder.com/v2/auth/sms/send?auth_type=sms"
CODE_VALIDATE_URL = "https://api.gotinder.com/v2/auth/sms/validate?auth_type=sms"
TOKEN_URL = "https://api.gotinder.com/v2/auth/login/sms"
HEADERS = {'user-agent': 'Tinder/11.4.0 (iPhone; iOS 12.4.1; Scale/2.00)', 'content-type': 'application/json'}
def send_otp_code(phone_number):
data = {'phone_number': phone_number}
r = requests.post(CODE_REQUEST_URL, headers=HEADERS, data=json.dumps(data), verify=False)
print(r.url)
response = r.json()
if(response.get("data")['sms_sent'] == False):
return False
else:
return True
def get_refresh_token(otp_code, phone_number):
data = {'otp_code': otp_code, 'phone_number': phone_number}
r = requests.post(CODE_VALIDATE_URL, headers=HEADERS, data=json.dumps(data), verify=False)
print(r.url)
response = r.json()
if(response.get("data")["validated"] == False):
return False
else:
return response.get("data")["refresh_token"]
def get_api_token(refresh_token):
data = {'refresh_token': refresh_token }
r = requests.post(TOKEN_URL, headers=HEADERS, data=json.dumps(data), verify=False)
print(r.url)
response = r.json()
return response.get("data")["api_token"]
phone_number = input("Please enter your phone number under the international format (country code + number): ")
log_code = send_otp_code(phone_number)
otp_code = input("Please enter the code you've received by sms: ")
refresh_token = get_refresh_token(otp_code, phone_number)
print("Here is your Tinder token: " + str(get_api_token(refresh_token)))
Unfortunatley when I run the code and put in the access code from my phone I get the following error:
File "c:\Users\MIS-l\OneDrive\Desktop\tinderbot-master\phone_auth_token.py", line 44, in <module>
print("Here is your Tinder token: " + get_api_token(refresh_token))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\MIS-l\OneDrive\Desktop\tinderbot-master\phone_auth_token.py", line 37, in get_api_token
return response.get("data")["api_token"]
~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable
I have tried accessing the API links at the top of the beginning of the script but I just get Error 404 for all of them.
What can I do to get the access token?
Thank you,
Vercetti

"delete_message" not working on sqs client under moto

I have a code like:
class SqsClientWrapper:
def __init__(self, sqs_client, queue_url):
self.sqs_client = sqs_client
self.queue_url = queue_url
def receive_message(self):
try:
while True:
response = self.sqs_client.receive_message(QueueUrl=self.queue_url, MaxNumberOfMessages=1)
if len(response.get("Messages", [])) > 0:
return response["Messages"][0]
except ClientError as e:
raise e
def delete_message(self, receipt_handle):
try:
response = self.sqs_client.delete_message(
QueueUrl=self.queue_url, ReceiptHandle=receipt_handle
)
except ClientError:
self.__logger.exception(
f"Could not delete the meessage from the - {self.__queue_url}."
)
raise
else:
return response
class Listener:
def listen(self, queue_url):
sqs_client = SqsClientWrapper(boto3.client("sqs"), queue_url)
while True:
try:
message = sqs_client.receive_message()
print(str(message))
sqs_client.delete_message(message["ReceiptHandle"])
except Exception as e:
continue
I'm trying to test the Listener using moto, I have the following test code:
logger = logging.getLogger()
class ListenerTest(unittest.TestCase):
def setUp(self) -> None:
self.executor = ThreadPoolExecutor()
self.futures = []
def tearDown(self) -> None:
for future in self.futures:
future.cancel()
self.executor.shutdown()
#mock_sqs
def test_simple(self):
sqs = boto3.resource("sqs")
queue = sqs.create_queue(QueueName="test-fake-queue")
queue_url = queue.url
listener = Listener()
self.futures.append(
self.executor.submit(listener.listen, queue_url)
)
sqs_client = boto3.client("sqs")
sqs_client.send_message(
QueueUrl=queue_url,
MessageBody=json.dumps({"id": "1234"}),
)
if __name__ == "__main__":
unittest.main()
When I run this, it seems to have received the message okay, but when deleting it from the queue it fails with the following error:
botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the DeleteMessage operation: The security token included in the request is invalid.
Anyone know what might be going on here? Thanks!

Using json.dump and json_enccode format to requests.post ,server return Response [500],serve use tornade.escape.json_decode

Using Python 3.8.10 and requests 2.21.0
The service post handle function below:
from tornado.escape import json_decode
def get_payload(self):
return json_decode(self.request.body)
def post(self):
""" acquire device """
data = self.get_payload()
udid = data["udid"]
idle_timeout = data.get('idleTimeout', 600)
email = self.current_user.email
try:
await D(udid).acquire(email, idle_timeout)
self.write_json({
"success": True,
"description": "Device successfully added"
})
except AcquireError as e:
self.set_status(403) # forbidden
self.write_json({
"success": False,
"description": "Device add failed: " + str(e),
})
The Client post fun below:
def post_occupied_device(self,udid = None,idleTimeout = None):
url = self.SERVER_URL+'/api/v1/user/devices'
occupied_dict = {
"udid": udid
}
try:
resp = requests.post(url,json=json.dumps(occupied_dict),headers=self.headers)
except requests.exceptions.RequestException as e:
print(e)
return "failed,network error"
print(resp)
enter code here
The server return:<Response [500]>
Then i change json data to this :
resp = requests.post(url,json=json_encode(occupied_dict),headers=self.headers)
The server return:<Response [500]>
Then i change json data to this :
requests.post(url,json=occupied_dict,headers=self.headers)
it is ok,The server return:<Response [200]>
i checkout the result and type between json_encode and json.dumps:
import json
from tornado.escape import json_encode
occupied_json = {
"udid": "DFEFDGDSGDF"
}
occupied_dict = {
'udid': "DFEFDGDSGDF"
}
req1 = json.dumps(occupied_json)
req2 = json_encode(occupied_json)
print(req1,type(req1))
print(req2,type(req2))
they are the same:
{"udid": "DFEFDGDSGDF"} <class 'str'>
{"udid": "DFEFDGDSGDF"} <class 'str'>
so,why?

Microsoft Cognitive Services - Speaker Recognition API - Verification - error-SpeakerInvalid

I am still facing the error in the verification process
{"error":{"code":"BadRequest","message":"SpeakerInvalid"}}'
My audio is correct as it is getting enrolled easily
##code for API CALL speaker verification
import http.client, urllib.request, urllib.parse, urllib.error, base64
subscription_key = 'XXXXXXXXXXXXXXXXXXXXXXX'
headers = {
# Request headers
"Content-Type": 'multipart/form-data',
"Ocp-Apim-Subscription-Key": subscription_key,
}
params = urllib.parse.urlencode({
'verificationProfileId':'445b849b-6418-4443-961b-77bd88196223',
})
#body = {
#}
try:
conn = http.client.HTTPSConnection('speaker-recognition-api.cognitiveservices.azure.com')
body = open('pp.wav','rb') //pp.wav is my audio file
conn.request("POST", "/spid/v1.0/verify?verificationProfileId=445b849b-6418-4443-961b-77bd88196223?%s" % params, body, headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
I could reproduce your problem. You are getting this error cause there is a ? in the end of your url, however behind verify there is already a ?. So if you want to add params to your request url you should use & just like the sample code in this API doc:Speaker Recognition - Verification .
Below is my work code.
try:
conn = http.client.HTTPSConnection('geospeaker.cognitiveservices.azure.com')
body=open("output4.wav","rb")
conn.request("POST", "/spid/v1.0/verify?verificationProfileId=1ae143b0-c301-4345-9295-3e34ad367092?%s" % params, body, headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except OSError as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))

why do I still receive insufficient permission error despite giving full mail scope?

import httplib2
import os
import oauth2client
from oauth2client import client, tools
from apiclient import errors, discovery
SCOPES = 'https://mail.google.com/'
APPLICATION_NAME = 'Gmail API Python List Email'
CLIENT_SECRET_FILE = 'client_secret_ishandutta2007.json'# This file will be in local dir
CREDENTIAL_FILE_NAME = 'gmail-python-email-send_ishandutta2007.json'
def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, CREDENTIAL_FILE_NAME)
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
print(('Storing credentials to ' + credential_path))
return credentials
def ListMessagesMatchingQuery(service, user_id, query=''):
try:
response = service.users().messages().list(userId=user_id, q=query).execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user_id, q=query,
pageToken=page_token).execute()
messages.extend(response['messages'])
return messages
except errors.HttpError as error:
print('An error occurred: %s' % error)
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
ListMessagesMatchingQuery(service, "me", query="senior recruit")
if __name__ == '__main__':
main()
An error occurred: https://www.googleapis.com/gmail/v1/users/me/messages?q=senior+recruit&alt=json
returned "Insufficient Permission">
Found the issues,in the code above it was picking up a cached credentials from the file gmail-python-email-send_ishandutta2007.json which has permission to send mails only, changing this filename to something new fixed the issue.

Resources