I am developing a python script to send direct messages to anyone on twitter using python.For that i am using twitter api but i dont know how to that.If anybody knows any method please help me.
See TwitterAPI
from TwitterAPI import TwitterAPI
import json
api = TwitterAPI(<consumer key>,
<consumer secret>,
<access token key>,
<access token secret>)
user_id = <user id of the recipient>
message_text = <the DM text>
event = {
"event": {
"type": "message_create",
"message_create": {
"target": {
"recipient_id": user_id
},
"message_data": {
"text": message_text
}
}
}
}
r = api.request('direct_messages/events/new', json.dumps(event))
print('SUCCESS' if r.status_code == 200 else 'PROBLEM: ' + r.text)
Related
I am attempting to get a refresh token and use it to request a new access token when the temporary access token expires.
Spotify's documentation states the response body should contain the following json data:
{
"access_token": "NgCXRK...MzYjw",
"token_type": "Bearer",
"scope": "user-read-private user-read-email",
"expires_in": 3600,
"refresh_token": "NgAagA...Um_SHo"
}
However, using my code below only provides the following:
{
"access_token": "xxxx....",
"token_type": "Bearer",
"expires_in": 3600
}
I am using the following function to request an access token:
def get_access_token(client_id, client_secret): # getting access token from spotify using client ID
# Encoding Client ID and Client Secret in Base64
token_url = "https://accounts.spotify.com/api/token"
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
token_data = {
"grant_type": "client_credentials"
}
token_headers = {
'Authorization': f"Basic {client_creds_b64.decode()}"
}
r = requests.post(token_url, data=token_data, headers=token_headers)
valid_request = r.status_code in range(200, 299)
token_response_data = r.json()
# pretty print response body
print(json.dumps(token_response_data, indent=2)) # response 200 -> successful attempt
if valid_request:
access_token = token_response_data['access_token']
return access_token
I am unsure why the scope and refresh token are missing from the response body. How can I alter this function to include these?
Thanks in advance for your time!
Spotify documentation: https://developer.spotify.com/documentation/general/guides/authorization/code-flow/
Altering the token data fixes this:
token_data = {
"grant_type": "authorization_code",
"code": "xxxx....",
"redirect_uri": "your redirect uri from Spotify for devs"
}
You need to set up a redirect uri on Spotify for devs, then encode it to use it as a parameter.
To get the 'code' parameter fill-out this URL with your data and you will be redirected to your redirect uri.
https://accounts.spotify.com/authorize?client_id=YOUR CLIENT ID&response_type=code&redirect_uri=YOUR ENCODED REDIRECT URI&scope=playlist-modify-public%20playlist-modify-private
The code will then be in the search bar to copy/paste. It should look something like this:
https://your redirectURI?code=xxx.....
Here is a good video guide for reference:
https://www.youtube.com/watch?v=-FsFT6OwE1A&ab_channel=EuanMorgan
Here is the code
message = {
"default":"Sample fallback message",
"http":{
"data":[
{
"type":"articles",
"id":"1",
"attributes":{
"title":"JSON:API paints my bikeshed!",
"body":"The shortest article. Ever.",
"created":"2015-05-22T14:56:29.000Z",
"updated":"2015-05-22T14:56:28.000Z"
}
}
]
}
}
message_as_json = json.dumps(message)
response = sns_client.publish(TopicArn = "arn:aws:sns:us-east-1:MY-ARN",
Message = message_as_json, MessageStructure = "json")
print(response)
To test, I used ngrok to connect the localhost (which runs my flask app) to the web and created a http subscription.
When I publish the message I can only see default message in that.
Any idea why this happens?
You need to specify the value of the http key as a simple JSON string value according to the AWS boto3 docs:
Keys in the JSON object that correspond to supported transport
protocols must have simple JSON string values.
Non-string values will cause the key to be ignored.
import json
import boto3
sns_client = boto3.client("sns")
message = {
"default": "Sample fallback message",
"http": json.dumps(
{
"data": [
{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON:API paints my bikeshed!",
"body": "The shortest article. Ever.",
"created": "2015-05-22T14:56:29.000Z",
"updated": "2015-05-22T14:56:28.000Z",
},
}
]
}
),
}
response = sns_client.publish(
TopicArn="arn:aws:sns:us-east-1:MY-ARN", Message=json.dumps(message), MessageStructure="json"
)
I am trying to automate my blog writing a bit by using Blogger API v3.0.
I have my API_KEY and by using it I managed to access my blog like that:
import requests
APIKEY = 'XXX-YYY-ZZZ'
BLOGID = '12345678'
get_blog = 'https://www.googleapis.com/blogger/v3/blogs/{BLOGID}?key={APIKEY}'.format(BLOGID=BLOGID, APIKEY=APIKEY)
response = requests.get(get_blog)
Next I tried to create a new post:
params = {
"kind": "blogger#post",
"blog": {
"id": BLOGID
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}
new_post = 'https://www.googleapis.com/blogger/v3/blogs/{blogID}/posts/?key={APIKEY}'.format(blogID=bereshitID, APIKEY=APIKEY)
response = requests.post(get_blog, params=params)
But I got an Error:
{u'error': {u'status': u'PERMISSION_DENIED', u'message': u'The caller does not have permission', u'code': 403, u'errors': [{u'reason': u'forbidden', u'message': u'The caller does not have permission', u'domain': u'global'}]}}
So I figured I need to have OAuth 2.0 credentials. So I created it and now I have client_id and client_secret and I tried to add it to the params:
CLIENT_SECRET = 'ABCD-EFGH'
CLIENT_ID = '1111'
params = {
"client_secret" : CLIENT_SECRET,
"client_id" : CLIENT_ID,
"kind": "blogger#post",
"blog": {
"id": BLOGID
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}
new_post = 'https://www.googleapis.com/blogger/v3/blogs/{blogID}/posts/?key={APIKEY}'.format(blogID=bereshitID, APIKEY=APIKEY)
response = requests.post(get_blog, params=params)
However I am still getting the error as before.
Clearly I am missing something here but I couldn't find a solution... So how should I use the OAuth 2.0 credentials correctly?
I found this guide by Rajashekar Jangam (ImRaj90) very informative.
I followed it and managed to work with my blog using the API.
Thank you Rajashekar.
In the Step Sending an Activity to the bot As per the documentation Here,
https://docs.botframework.com/en-us/restapi/directline3/#navtitle
I should pass this as the body content of the post request
{
"type": "message",
"from": {
"id": "user1"
},
"text": "hello"
}
I am using the following parameters to make POST request in python, but its not working.
msg = {"type": "message","channelId": "directline","conversation":{"id": str(convId)},"from":{"id": "test_user1"},"text": "hello"}
header = {"Authorization":"Bearer q1-Tr4sRrAI.cwA.BmE.n7xMxGl-QLoT7qvJ-tNIcwAd69V-KOn5see6ki5tmOM", "Content-Type":"application/json", "Content-Length": "512"}
send2 = "https://directline.botframework.com/v3/directline/conversations/"+str(convId)+"/activities"
rsa1 = requests.post(send2,data=msg, headers=header)
This gives me this error:
{
"error": {
"code": "MissingProperty",
"message": "Invalid or missing activities in HTTP body"
}
}
Before this step everything is working fine.
Edit 1: Even i added content-length as updated in the code, it gives the same error
Edit 2: If i changed the msg to json.dumps(msg)
rsa1 = requests.post(send2,data=json.dumps(msg), headers=header)
I get response:
{u'error': {u'message': u'Failed to send activity: bot returned an error', u'code': u'ServiceError'}}
{
"error": {
"code": "ServiceError",
"message": "Failed to send activity: bot returned an error"
}
}
The directline API is only not working, on skype client everything is working fine.
According to the code that you've posted, your request body looks like this:
{
"type": "message",
"channelId": "directline",
"conversation": {
"id": str(convId)
},
"from": {
"id": "test_user1"
},
"text": "hello"
}
I'd suspect that your error is caused by the fact that the conversation ID value that you're including in the request body is not surrounded with double quotes in the JSON that's sent over the wire.
For simplicity (and to eliminate the error you're receiving), I'd suggest that you try omitting the channelId property and the conversation property from the request body, as I don't believe that either of these properties are necessary (i.e., you are issuing the request to the Direct Line URI, so the Bot Framework knows that Direct Line is the channel, and the conversation ID is already being specified in the request URI). In other words, try this as your request body:
{
"type": "message",
"from": {
"id": "test_user1"
},
"text": "hello"
}
When passing a dictionary to data it gets urlencoded automatically, so the api returns an error as it expects json data.
You can either use the json lib, or preferably pass your dictionary to the json parameter.
Using json.dumps :
rsa1 = requests.post(send2, data=json.dumps(msg), headers=header)
Using requests only :
rsa1 = requests.post(send2, json=msg, headers=header)
Also you don't have to add "Content-Length" in header and if you use the second example you don't have to add "Content-Type" either.
I have a permissions request that looks like this:
timestamp, signature = genPermissionsAuthHeader.getAuthHeader(str(self.username), str(self.password), str(access_token), str(token_secret), "POST", "https://api-3t.sandbox.paypal.com/nvp") # https://svcs.sandbox.paypal.com/Permissions/GetBasicPersonalData
log.info(timestamp)
log.info(signature)
authorization_header = "timestamp=" + timestamp + ",token=" + access_token + ",signature=" + signature
log.info(authorization_header)
headers = {
"X-PAYPAL-AUTHORIZATION": authorization_header,
}
url = "https://api-3t.sandbox.paypal.com/nvp"
nvp_params = {
"METHOD": "TransactionSearch",
"STARTDATE": "2012-01-01T05:38:48Z",
}
r = requests.post(url, data=nvp_params, headers=headers)
log.info(r.text)
self.response.content_disposition = "text/html"
self.response.write(r.text)
I have an access token and token secret from the permissions API using my PayPal credentials on developer.paypal.com under "Sandbox Accounts"
When I run this method I get the error message:
TIMESTAMP=2014%2d04%2d21T22%3a50%3a18Z&CORRELATIONID=c8f9212035b60
&ACK=Failure&VERSION=0%2e000000&BUILD=10277387&L_ERRORCODE0=10002
&L_SHORTMESSAGE0=Authentication%2f
Authorization%20Faile
d&L_LONGMESSAGE0=You%20do%20not%20have%20permissions%20to%20make%20this%20API%20call
&L_SEVERITYCODE0=ErrorNone
I can make a call to GetBasicPersonalDetails and it seems to work. Any help would be great, thanks!
I found the answer, I was missing the "SUBJECT" parameter on the parameter string being sent for the payment. So just in case anyone else runs across this in the future the full code after getting the permissions tokens to run a test payment for the sandbox is:
def test_sales(self, access_token=None, token_secret=None):
timestamp, signature = genPermissionsAuthHeader.getAuthHeader(str(self.username), str(self.password), str(access_token), str(token_secret), "POST", "https://api-3t.sandbox.paypal.com/nvp") # https://svcs.sandbox.paypal.com/Permissions/GetBasicPersonalData
log.info(timestamp)
log.info(signature)
authorization_header = "timestamp=" + timestamp + ",token=" + access_token + ",signature=" + signature
log.info(authorization_header)
headers = {
"X-PAYPAL-AUTHORIZATION": authorization_header,
}
url = "https://api-3t.sandbox.paypal.com/nvp"
nvp_params = {
"METHOD": "DoDirectPayment",
"PAYMENTACTION": "Sale",
"AMT": "22.00",
"ACCT": "4111111111111111",
"CVV2": "111",
"FIRSTNAME": "Jane",
"LASTNAME": "Smith",
"EXPDATE": "012018",
"IPADDRESS": "127.0.0.1",
"STREET": "123 Street Way",
"CITY": "Englewood",
"STATE": "CO",
"ZIP": "80112",
"VERSION": "86",
"SIGNATURE": self.signature,
"USER": self.username,
"PWD": self.password,
"SUBJECT": "person_who_you_acting_on_behalf_of#domain.com"
}
r = requests.post(url, data=nvp_params, headers=headers)
log.info("Search transaction\n\n" + r.text + "\n\n")
self.response.content_disposition = "text/html"
self.response.write(urllib.unquote(r.text).decode('utf8'))
And for generating the header I used: https://github.com/paypal/python-signature-generator-for-authentication-header
Hope this helps someone, thanks!
Here is some information on the error message you are getting. One reason is invalid API Credentials. Another possibility is you are trying to pass an expired token. Once a transaction is created on PayPal the token is no longer valid. Instead you have a transaction id created.
Below is some more information on PayPal API Error Messages.
PayPal API Error Messages
If you are attempting a transaction search for your most recent transactions in PayPal, then you can use the PaymentDetailsRequest API
Here is an integration guide from the PayPal Developer Site:
Get Payment Details PayPal API Codes
TransactionSearch is not part of the AdaptivePayments API,
so no "X-PAYPAL-AUTHORIZATION" is required with this method.
Assuming that you got the permission for TransactionSearch method on the target account (see https://developer.paypal.com/docs/classic/permissions-service/gs_PermissionsService/)
the following code will works:
import requests
api_username="username"
api_password="password"
api_signature="signature"
target_account_email="xxx.yyy-buyer#zzz.com" #customers email
data_req = {
'METHOD':'TransactionSearch',
'SUBJECT':, target_account_email,
'VERSION':'86.0',
'STARTDATE':'2009-10-11T00:00:00Z',
'USER':api_username,
'PWD':api_password,
'SIGNATURE':api_signature
}
response=requests.post(url_en_point,data=data_req,timeout=3).text
print response