I am trying to fetch all the direct messages in my account. But I tried to use cursor for fetching. But I'm getting an error like
TypeError: cursor() missing 1 required positional argument: 'function'
My code is below.
from twython import Twython
APP_KEY = 'KEY'
APP_SECRET = 'SECRET'
ACCESS_TOKEN = 'TOKEN'
ACCESS_SECRET = 'SECRET'
twitter = Twython(APP_KEY,APP_SECRET,ACCESS_TOKEN,ACCESS_SECRET)
for tweet in Twython.cursor(twitter.get_direct_messages(),since_id=1,count=100):
print (tweet)
Please help on this.
Pretty sure that you need to invoke the .cursor method on the twitter object, not on the Twython class.
So try
for tweet in twitter.cursor(twitter.get_direct_messages(),since_id=1,count=100):
print (tweet)
Specifically, this works for me:
results = twitter.cursor(twitter.get_direct_messages,count=2)
for result in results:
print result['text']
You can also access them directly from the return of get_direct_messages:
messages = twitter.get_direct_messages(count=200)
for message_id in messages:
id = message_id['id']
text = message_id['text']
print text
Related
I have able to successfully connect and read emails using the 'python-o365' library:
Connection.oauth2('Client_ID','Client_Secret',store_token=True)
inbox = FluentInbox()
for message in inbox.fetch_next(2):
print(message.getSubject())
However, when I try to send an email using a more basic example, I am receiving a 401 response from the server.
Connection.oauth2('Client_ID','Client_Secret',store_token=True)
att = Attachment(path=FilePath)
m = Message()
m.setRecipients(EmailTo)
m.setSubject('DBM Errors Identified - ' + FileName)
m.setBody(MessageBody)
m.attachments.append(att)
m.sendMessage()
I have also tried setting the connection object and passing it through as a parameter:
auth = Connection.oauth2('Client_ID','Client_Secret',store_token=True)
m = Message(*auth=auth*)
That however results in an error message of:
TypeError: 'Connection' object is not callable
Thanks for the help!
I was able to bypass the issue by switching to a fork of the 'python-o365' library that I used above. I feel like I am probably missing something obvious with that library but this solved the problem
Here is the simplified version of the authentication flow that I have working in case it interests anyone:
scopes = ['https://graph.microsoft.com/Mail.Read'']
account = Account(('Client_Id', 'Client_Secret'], auth_method='oauth',scopes=scopes)
account.connection.get_authroization_url() #generate the url for user to authenticate
result_url = input('Paste the result URL once you have authenticated...')
account.connection.get_session() #generate a session
m = account.new_message()
m.to.add('EmailTo')
m.body = 'MessageText'
m.send()
I am trying to make an application for an organization which will required to fetch all past as well present tweets with some particular hashtag like #airtel, #airtel etc, how should I get past tweet, I am able to fetch the present tweet with the following url : "https://api.twitter.com/1.1/search/tweets.json?q=%23airtel"
Thanks
You can get up to a maximum of 100 tweets with the twitter rest api see the following twitter documentation. The best you can do is use the count parameter https://api.twitter.com/1.1/search/tweets.json?q=%23airtel&count=100
After various search on Google I found some useful library for fetching tweets e.g:
TwitterSearch [https://github.com/ckoepp/TwitterSearch], you would I find the twitter profile # https://twitter.com/twittersearch
Tweepy [https://github.com/tweepy/tweepy], you could find more info at http://www.tweepy.org/
I have implemented using both. Tweepy implementation is as follows:
import tweepy
import json
consumer_key = "get"
consumer_secret = "From"
access_token = "Twitter"
access_token_secret = "site"
# Authenticate twitter Api
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#made a cursor
c = tweepy.Cursor(api.search, q='%23Coursera')
c.pages(15) # you can change it make get tweets
#Lets save the selected part of the tweets inot json
tweetJson = []
for tweet in c.items():
if tweet.lang == 'en':
createdAt = str(tweet.created_at)
authorCreatedAt = str(tweet.author.created_at)
tweetJson.append(
{'tweetText':tweet.text,
'tweetCreatedAt':createdAt,
'authorName': tweet.author.name,
})
#dump the data into json format
print json.dumps(tweetJson)
If any one have problem, let me know, will provide git repo for this.
Thanks
Krishna
After two days of unsuccessful attempt to use twitter gem I have decided to use tweepy of python for a task. (My original attempt was with ruby and I posted the question here)
My task is to collect all those actresses who have a verified account on twitter. I have taken the list of actresses from wikipedia.
Everything looks fine till now. I have started hitting twitter REST api with each name and I check whether it is a verified account or not.
The only problem I have is that the response is very slow. It takes about 12-15 seconds for every request. Am I doing something wrong here or is it how it is suppose to be.
Below is my code in its entirety :
import tweepy
consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token_key = 'xx-xx'
access_token_secret = 'xxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)
api = tweepy.API(auth)
actresses = []
f = open('final','r')
for line in f:
actresses.append(line)
f.close()
print actresses
for actress in actresses:
print actress
users = api.search_users(actress)
for u in users:
if u.verified == True and u.name == actress:
print u.name + " === https://twitter.com/" + u.screen_name
Also is there any better way to extract the verified actresses using that list?
Unfortunately, there is no faster way to do it, given that you only know the actresses' full names, and not their screen names. Each request will take a long time, as Twitter needs to return the results of users matching the query (there may be quite a few). Each one needs to be loaded and examined, which can take a while, depending on how many results were returned.
I have a twitter account with an App made, currently it's setup so students can tweet from our website and as such their tweets show "via SchoolAppNameHere" at the bottom of their tweets.
Is it possible to use Twython to use the Appkey and secret key and then get auth tokens from a completely different so when I was to run the bit of code below it would tweet from an account what didn't create the app...
from twython import Twython
APP_KEY = ''
APP_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test")
Any ideas would be much appreciated :)
Edit, Updated example/explanation below:
Let's say the following image's are from the account "stackoverflowapp" and the app called "Stackoverflow Test App":
Using the following bit of code would tweet from the account "stackoverflowapp" with the tweet "test" via the applicationg called "Stackoverflow Test App"
from twython import Twython
APP_KEY = 'coN_kEY_123456789'
APP_SECRET = 'cOn_sEcr3t_123456789'
OAUTH_TOKEN = 'Acc3ss_tok3N_123456789'
OAUTH_TOKEN_SECRET = 'aCCeSS_tOkEn_sEcrET_123456789'
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test")
Let's say that the following image is from the account "useraccount1" and the app is called "testing123":
So now that I have the access tokens to login to the account "useraccount1", how can I tweet via the app called "Stackoverflow test app" which was created by the user: "stackoverflowapp" example of what I tried is below:
from twython import Twython
APP_KEY = 'coN_kEY_123456789'
APP_SECRET = 'cOn_sEcr3t_123456789'
OAUTH_TOKEN = 'Acc3ss_123456789'
OAUTH_TOKEN_SECRET = 'aCCeSS_sEcrET_123456789'
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test update")
Unfortunately, I get the error:
TwythonAuthError: Twitter API returned a 401 (Unauthorized), Could not authenticate you
This is of course, possible. When you create an application in Twitter, they give you your own authentication tokens for you to use immediately, as a convenience.
Use the access token string as your "oauth_token" and the access token secret as your "oauth_token_secret" to sign requests with your own Twitter account. Do not share your oauth_token_secret with anyone.
To get keys for other accounts for the same application, you need to request more keys for each account. This is described in detail here: https://dev.twitter.com/docs/auth/obtaining-access-tokens
Since it sounds like you're going to be doing the authorization yourself, the simpler PIN-based approach should probably be used.
You're using twython, obtaining these can be done using the library: https://twython.readthedocs.org/en/latest/usage/starting_out.html#authentication
get_authentication_tokens and get_authorized_tokens are the methods you're looking for.
from twython import Twython
import sys
APP_KEY = 'coN_kEY_123456789'
APP_SECRET = 'cOn_sEcr3t_123456789'
twitter = Twython( APP_KEY, APP_SECRET )
auth = twitter.get_authentication_tokens()
print( 'Visit %s and enter your PIN: ' % auth.get( 'auth_url' ) ),
pin = sys.stdin.readline().strip()
twitter = Twython( APP_KEY, APP_SECRET, auth.get( 'oauth_token' ), auth.get( 'oauth_token_secret' ) )
tokens = twitter.get_authorized_tokens( pin )
print( 'OAUTH_TOKEN: %s' % tokens.get( 'oauth_token' ) )
print( 'OAUTH_TOKEN_SECRET: %s' % tokens.get( 'oauth_token_secret' ) )
Store OAUTH_TOKEN and OAUTH_TOKEN_SECRET some place safe and reuse at will. Also, make sure you authorize the correct account when visiting the URL and getting the PIN.
All your API calls will be made on bahalf the account that authorized access via the tokens and your via line will be your original application. Use the appropriate tokens for each account you'd like to tweet from, it's not possible to mix and match.
I am using Oauth to connect to Twitter, but it results in a 401 error. What am I doing wrong here?
//config
define('CONSUMER_KEY',"");
define('CONSUMER_SECRET',"");
define('OAUTH_TOKEN',"1U");
define('OAUTH_TOKEN_SECRET',"");
require_once('twitteroauth/twitteroauth.php');
$connection = new TwitterOAuth (CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);
$connection->post('statuses/update', array('status' => 'testing'));
$httpc = $connection->http_code;
if($httpc == 200) {
echo 'succesvol';
} else {
echo $httpc;
}
You get a 401 (Not Authorised) error when you do not provide the correct ConsumerKey and ConsumerSecret values.
Looking at the code above, you are passing empty string values for those two variables. Unless u left them out on purpose, you need to double check your values.
For my app, this is where they exist.
(ASSUMPTION: you've created a twitter application # dev.twitter.com )
Good Luck!