I am trying to connect to the Twitter REST API. I downloaded the twitter packages with pi in the command line. In another program I did I could connect to the stream Twitter API. This is my code:
Import the necessary package to process data in JSON format
try:
import json
except ImportError:
import simplejson as json
# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = ''
ACCESS_SECRET = ''
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter = Twitter(auth=OAuth)
twitter.statuses.home_timeline()
I am getting this error:
line 263, in __call__
headers.update(self.auth.generate_headers())
TypeError: generate_headers() missing 1 required positional argument: 'self'
How can I fix it?
I believe what you are trying to do is
twitter = Twitter(auth=oauth)
Related
I am trying to a send a basic direct message on Twitter, but it isn't recognizing 'create_direct_message'. This is the code I am using:
Client.create_direct_message(participant_id = '129593148134547046', text = 'Hello')
This is the error message:
AttributeError: 'Client' object has no attribute 'create_direct_message'
This is how the tweepy website says how to do it on their website, so I'm not sure why my computer is not recognizing it. Is there some way to update tweepy? Could I be running an old version? Please help!
https://docs.tweepy.org/en/stable/client.html#manage-direct-messages
The following is steps to send a direct message using Tweepy.
On the Twitter developer portal you will need to upgrade your account to elevated.
Once elevated access is approved and create your app, then got user authentication settings.
Set it to the following:
Read and write and Direct message
Native App
Fill in Callback URL and website URL. (its not used by Tweepy, but must be filled)
Going back to the App view select the "Keys and Tokens" tab.
Store all the information but you need the following.
consumer_key
consumer_secret
access_token
access_token_secret
Once you have that information the following sample code should work (fill in the variables).
import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitter = tweepy.API(auth)
recipient_id = '129593148134547046' # As per example above.
text = 'hello'
direct_message = api.send_direct_message(recipient_id, text)
print(direct_message.message_create['message_data']['text'])
If it works the print will be your message.
I'm trying to set up a Retweet bot using the Tweepy module for Twitter's API, and have been working through errors bit by bit as the tutorial I was following was an older version of Tweepy. I'm new-ish to Python coding, and certainly haven't integrated API's before, so bear with me on this :)
Here's my code:
# import dependencies
import tweepy
import os
from dotenv import load_dotenv
from streamlistener import StreamListener
# load our .env file to make use of the environment variables
load_dotenv()
# import and assign our environment variables
API_KEY = os.getenv('twitter_api_key')
API_SECRET = os.getenv('twitter_api_secret')
ACCESS_TOKEN = os.getenv('twitter_access_token')
TOKEN_SECRET = os.getenv('twitter_access_secret')
# instantiate oauth handler and set access token
twitter_oauth = tweepy.OAuthHandler(API_KEY, API_SECRET)
twitter_oauth.set_access_token(ACCESS_TOKEN, TOKEN_SECRET)
# instantiate tweepy api object using the authentication handler object
twitter_api = tweepy.API(twitter_oauth)
# attempt credential verification. prints exception if something is wrong
try:
print(twitter_api.verify_credentials())
print("Successfully logged in")
except tweepy.errors.TweepyException as e:
print(e)
except Exception as e:
print(e)
# instantiate a StreamListener object
tweets_listener = StreamListener(twitter_api)
#instantiate a tweepy.Stream object
tweet_stream = tweepy.Stream(twitter_api.auth, tweets_listener)
# Use the filter method
tweet_stream.filter(track=["#VTuber", "#ENVTuber", "vtuber", "Vtuber", "VTuberEN"], languages=["en"])
And the error I'm getting is:
Traceback (most recent call last): File "C:\Python\bot.py", line 36, in <module> tweet_stream = tweepy.Stream(twitter_api.auth, tweets_listener) TypeError: Stream.__init__() missing 2 required positional arguments: 'access_token' and 'access_token_secret'
I've tried adding ACCESS_TOKEN and TOKEN_SECRET into line 36 (tweepy.Stream arguments), but either I did it wrong or that's not the fix.
You're using syntax from an older version of Tweepy.
Tweepy v4.0.0 changed Stream to accept consumer_key, consumer_secret, access_token, and access_token_secret parameters for initialization.
I am trying to access twitter api via tweepy. And I get tweepy.error.TweepError: [{'code': 215, 'message': 'Bad Authentication data.'}] error.
My API access is decribed in twitter_client.py:
import os
import sys
from tweepy import API
from tweepy import OAuthHandler
def get_twitter_auth():
"""Setup twitter authentication
Return: tweepy.OAuthHandler object
"""
try:
consumer_key = os.environ['TWITTER_CONSUMER_KEY']
consumer_secret = os.environ['TWITTER_CONSUMER_SECRET']
access_token = os.environ['TWITTER_ACCESS_TOKEN']
access_secret = os.environ['TWITTER_ACCESS_SECRET']
except KeyError:
sys.stderr.write("TWITTER_* environment variable not set\n")
sys.exit(1)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
return auth
def get_twitter_client():
"""Setup twitter api client
Return: tweepy.API object
"""
auth = get_twitter_auth()
client = API(auth)
return client
Then I try to get my last 4 tweets:
from tweepy import Cursor
from twitter_client import get_twitter_client
if __name__ == '__main__':
client = get_twitter_client()
for status in Cursor(client.home_timeline()).items(4):
print(status.text)
And get that error. How do I fix it?
I am using python 3.6 and I've installed tweepy via pip whithout specifying a version, so it should be the last version of tweepy.
Upd: I found out that the problem is in environ variables. Somehow twitter api can't get it. However, when I just print(consumer_key, consumer_secret, access_token, access_secret), everything is on it's place
import tweepy
Importing this way improves code readability especially when using it.
eg tweepy.API()
client.home_timeline()
The brackets after home_timeline shouldn't be there.
should be
for status in Cursor(client.home_timeline).items(4):
print(status.text)
.
import tweepy
auth = tweepy.OAuthHandler(<consumer_key>, <consumer_secret>)
auth.set_access_token(<access_token>, <access_secret>)
client = tweepy.API(auth)
for status in tweepy.Cursor(client.user_timeline).items(200):
process_status(status.text)
You may solve this problem by importing load dotenv, which will get .env variables.
import os
import sys
from tweepy import API
from tweepy import OAuthHandler
from dotenv import load_dotenv
def get_twitter_auth():
"""Setup twitter authentication
Return: tweepy.OAuthHandler object
"""
try:
consumer_key = os.getenv('CONSUMER_KEY')
consumer_secret = os.getenv('CONSUMER_SECRET')
access_token = os.getenv('ACCESS_TOKEN')
access_secret = os.getenv('TWITTER_ACCESS_SECRET')
except KeyError:
sys.stderr.write("TWITTER_* environment variable not set\n")
sys.exit(1)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
return auth
def get_twitter_client():
"""Setup twitter api client
Return: tweepy.API object
"""
auth = get_twitter_auth()
client = API(auth)
return client
from tweepy import Cursor
if __name__ == '__main__':
client = get_twitter_client()
for status in Cursor(client.home_timeline()).items(4):
print(status.text)
I am quite new to installing modules on python. I'm trying to get started with Tweepy but I'm hitting an error.
I have run
import tweepy
auth = tweepy.OAuthHandler(MYCONSUMERKEY, MYCONSUMERSECRET)
But the following error is returned:
File "<stdin>", line 1
auth = tweepy.OAuthHandler(MYCONSUMERKEY, MYCONSUMERSECRET)
^
SyntaxError: invalid syntax
Any idea what could be going wrong here? Im using Python 2.7 on OSX El Capitan
I presume you have your Twitter Apps credentials (otherwise, nothing will work).
Use the following portion of code (assuming you have the required credentials)
import tweepy
# Fill this up with the Twitter Apps Credentials (get them # apps.twitter.com)
consumer_key = "Your consumer Key"
consumer_secret = "Your consumer Key Secret"
access_token = "Your access Token"
access_token_secret = "Your access Token Secret"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
print "User Name:", api.me().name
print "Account (#):", api.me().screen_name
With this, you have the basic framework to start interacting with the Twitter API using Tweepy (the last two lines, based on your Twitter credentials, should print your name and #username in Twitter.
I want to get the all of a user tweets from one Twitter user and so far this is what I came up with:
import twitter
import json
import sys
import tweepy
from tweepy.auth import OAuthHandler
CONSUMER_KEY = ''
CONSUMER_SECRET= ''
OAUTH_TOKEN=''
OAUTH_TOKEN_SECRET = ''
auth = twitter.OAuth(OAUTH_TOKEN,OAUTH_TOKEN_SECRET,CONSUMER_KEY,CONSUMER_SECRET)
twitter_api =twitter.Twitter(auth=auth)
print twitter_api
statuses = twitter_api.statuses.user_timeline(screen_name='#realDonaldTrump')
print [status['text'] for status in statuses]
Please ignore the unnecessary imports. One problem is that this only gets a user's recent tweets (or the first 20 tweets). Is it possible to get all of a users tweet? To my knowledge, the GEt_user_timeline (?) only allows a limit of 3200. Is there a way to get at least 3200 tweets? What am I doing wrong?
There's a few issues with your code, including some superfluous imports. Particularly, you don't need to import twitter and import tweepy - tweepy can handle everything you need. The particular issue you are running into is one of pagination, which can be handled in tweepy using a Cursor object like so:
import tweepy
# Consumer keys and access tokens, used for OAuth
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Creation of the actual interface, using authentication
api = tweepy.API(auth)
for status in tweepy.Cursor(api.user_timeline, screen_name='#realDonaldTrump', tweet_mode="extended").items():
print(status.full_text)