Tweepy raises bad authentication data error - python-2.7

I am working on a twitter bot using tweepy. The bot auto-replies to specific users whose tweet handle it receives as input. The bot was working fine for weeks and then suddenly started throwing this 'Bad Authentication Data' or the following to be more precise :
tweepy.error.TweepError: [{'message': 'Bad Authentication data.', 'code': 215}]
Apparently the problem is in this particular part of the code :
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
ts=api.user_timeline(screen_name=s,count=1)
I have entered the correct keys for the twitter application. I read about this problem on blogs where people say that it is an issue with POSTFIELDS and that it can be fixed by passing the status as URL in the api.update_status function. Is that right? If yes, please give me an example of how it can be done. I'm passing the message and tweet reply id in the update_status function. Thanks in advance.

I wrote
auth.secure = True
and it fixed in my case, hope it helps!

Related

Why am I getting this Authentication required error even though I am using my client id and client secret for the Foursquare API?

I getting back into Python and wanted to use the pyfoursquare package to access the Foursquare API. I'm trying to get information about venues using the venues method in the API class. I'm primarily trying to find out whether a venue page is verified with Foursquare or not. When I provide my client id, client secret, and venue id I keep getting back an error that states "Authentication required", which doesn't makes sense because I'm providing that information. Any help would be great. Thank you.
import pyfoursquare as foursquare
client_id = ""
client_secret = ""
callback = ""
auth = foursquare.OAuthHandler(client_id, client_secret, callback)
api = foursquare.API(auth)
result = api.venues("4e011a3e62843b639cfa9449")
print result[0].name
Let me know if you would like to see the error message. Thanks again.
I believe you are skipping the step of grabbing your OAuth2 access token, so you're not technically authenticated.
Have a look at the following instructions, under "How to Use It":
https://github.com/marcelcaraciolo/foursquare
The lines that might be useful to you are:
#First Redirect the user who wish to authenticate to.
#It will be create the authorization url for your app
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
#If the user accepts, it will be redirected back
#to your registered REDIRECT_URI.
#It will give you a code as
#https://YOUR_REGISTERED_REDIRECT_URI/?code=CODE
code = raw_input('The code: ').strip()
#Now your server will make a request for
#the access token. You can save this
#for future access for your app for this user
access_token = auth.get_access_token(code)
print 'Your access token is ' + access_token

Jsoup captcha login with cookie

I have been trying to develop a small application that gets captcha from my academics page, displays it to the user, the user enters captcha and the program should display details. However, I am stuck at login page itself. I used jsoup to get the cookie,save captcha to a folder, submit captcha along with form data, using the previous cookie. But I get the same login page again. Please help!
This is the get request. Website url https://academics.vit.ac.in/parent/parent_login.asp
Response res = Jsoup.connect(webSiteURL).method(Method.GET).execute();
Map<String,String> cook = res.cookies();
String sessionid = res.cookie("ASPSESSIONIDSQHDAQRQ");
After getting the captcha, this is the post request.
Response login = Jsoup.connect(webSiteURL)
.userAgent("Mozilla/5.0")
.cookie("ASPSESSIONIDSQHDAQRQ", sessionid).
data("message","Enter Verification Code of 6 characters exactly as shown.")
.data("vrfcd",captcha).data("wdpswd","somedata").data("wdregno","somedata")
.method(Method.POST).execute();
System.out.println(login.parse());
When I tried this
System.out.println(login.cookies());
The value is null, is that a clue?? Help me out!! Thanks!!
Are you sure you are retrieving the captcha using the cookie too?. Please check that. I mean, you can download the captcha with something like:
Response res1 = Jsoup.connect("https://academics.vit.ac.in/parent/captcha.asp")
.cookie("ASPSESSIONIDSQHDAQRQ", sessionid)
.ignoreContentType(true)
.method(Method.GET).timeout(30000).execute();
Then be sure that in the login post you are using the correct url, that is:
https://academics.vit.ac.in/parent/parent_login_submit.asp
Then it should work fine.
Hope it helps.

Unit test through an oauth flow in Django

I have an oauth flow in which a user grants access to a certain scope and then my application can do stuff. For this to work, I need an access token with the defined scope.
I implemented this (with the django allauth package) and it works great. But...
I would like to test it.
This is what I have so far (request package is like an urllib on steroids):
login = self.client.login(username='test_user', password='test')
self.assertTrue(login)
resp = self.client.post(reverse('oauth_login'))
self.assertEqual(resp.status_code, 302)
payload = {'session_key': 'email', 'session_password': 'pw', }
resp2 = requests.post(resp['location'], data=payload)
resp3 = self.client.get(reverse('do_stuff_with_access_token'))
self.assertEqual(resp.status_code, 302)
The issue here is that I do not get the access token in my request variables. My guess is that I am going out of the scope of the application and Django does not get the variable in its request scope.
How can you test this in an elegant manner? Mocking an access_token seems a bit wrong to me. I am now trying to go Selenium for filling in the form, but even that is not really a success so far...
Thanks!
Kudos to Mark!
To help anyone on their way.
Mocking worked out. In my case (django 1.4) you need to add your tokens to the session. A lot of different advices can be found on the net, but I like simple things and this works in Django at least with the test suite:
session = self.client.session
session['request_token'] = {...}
session['access_token'] = {...}
session.save()
I faced the same problem and found the following solved my dilemma:
user = User.objects.get(username='lauren')
client = APIClient()
client.force_authenticate(user=user)
This was taken directly from the Django documentation:
http://www.django-rest-framework.org/api-guide/testing/#force_authenticateusernone-tokennone
Unfortunately it took a number of searches before getting to this point. I hope this saves someone else some time.

Sending email not working on heroku

I have this function in forms.py. There is currently no email specifications in my settings.py.
def send_email(FROM_NAME,FROM,TO,SUB,MSG,EXISTING_EMAIL,EXISTING_PASSWORD):
FROMADDR = "%s <%s>" % (FROM_NAME, FROM)
LOGIN = EXISTING_EMAIL
PASSWORD = EXISTING_PASSWORD
TOADDRS = [TO]
SUBJECT = SUB
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += MSG+"\r\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
I call it my views.py like so
send_email('my_name','from_me#gmail.com','to_som1#gmail.com','my subject','mymessage','my_existing_email#gmail.com','password_to_existing_email')
This works locally. I have tested it with yahoomail and gmail. But when I upload to heroku it gives the error "(535, '5.7.1 Please log in with your web browser and then try again. Learn more at\n5.7.1 support.google.com/mail/bin/answer.py?answer=78754 et6sm2577249qab.8')"
Can anyone help?
You want to use this:
FROMADDR = "%s <%s>" % (your_name, your_email)
You shouldn't be building emails with string interpolation, that's a good way to get your site used to send spam via header injections. See my answer here for details on how to construct emails securely.
Generally speaking, when formatting from addresses, you should use the format Display Name <email#example.com>. See RFC 5322 for details.
Have you read the page linked to in the error message?
If you're repeatedly prompted for your username and password, or if
you're getting an 'invalid credentials' or 'web login required' error,
make sure your password is correct. Keep in mind that password are
case-sensitive.
If you’re sure your password is correct, sign in to your account from
the web version of Gmail instead at http://mail.google.com
In most cases signing in from the web should resolve the issue
Here is what worked for me. After getting the error Please log in with your web browser and then try again. Learn more etc. when trying to send email from my web application, I logged in to the email via browser from my local computer.
After I logged in, there was a yellow notification bar on top which asking me if I want to allow external application access my mail. I confirmed this and Google asked me to log in to the account from the application within the next 10 mins. This will white-list the application.

Django-social-auth google oauth token usage

I'm using Django-socila-auth plugin. It uses google API for Oauth 1.0 Authentication. Question is have anybody used it with google python API (gdata). I mean how to apply auth session_token, stored in django-social-auth model to my api call.
Can you help me with code to get this token from model and apply to gdata.PhotoService() instance. For now it is like this:
#getting model instance from django-social-auth model
association = Association.objects.get(user=request.user)
google_session_token=association.handle
google_secret=association.secret
#token string from django-social-auth
#model Association field "handle" looks like:
#google_session_token = '.......XG84PjwytqJkvr8WQhDxm1w-JplWK5zPndSHB13f.........'
gd_client = gdata.photos.service.PhotosService()
gd_client.debug = 'true'
gd_client.auth_token = google_session_token
#image.image is a file field, but problem not in this.
#it tries to send file in debug text.
#It just recieves 403 unauthorised callback.
photo = gd_client.InsertPhotoSimple(
'/data/feed/api/user/default/albumid/default', 'New Photo',
'Uploaded using the API', image.image, content_type='image/jpeg')
I'm recieving error
403 Invalid token string.
I understand that it needs secret too but how to apply it to API for auth?(To receive authorization to post photos.). BTW I added Picassa feed URL, as an option string for social-auth to ask permissions, so token I have asks for Picassa feed permissions when authorizing with google.
BTW. Google tutorial I've used is: here
I understand it's Oauth 1.0 rather than AusSub, but question is:
how to authenticate with token and secret I have and post a photo with this permission?
Just to answer my own problem. I used wrong way to do it, because problem in 'gd_client' and AuthSub.
It must check token on server. And it can not do it on localhost. You need to look ahead to Oauth/Oauth2 for better debugging and so on... No matter that it is much complex than AuthSub