I am quite the novice when it comes to coding. How do I modify this sample code to download tweets using Python?
def get_tweets(api, input_query):
for tweet in tweepy.Cursor(api.search, q=input_query, lang="en").items():
yield tweet
if __name__ == "__version__":
input_query = sys.argv[1]
access_token = "REPLACE_YOUR_KEY_HERE"
access_token_secret = "REPLACE_YOUR_KEY_HERE"
consumer_key = "REPLACE_YOUR_KEY_HERE"
consumer_secret = "REPLACE_YOUR_KEY_HERE"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = get_tweets(api, input_query)
for tweet in tweets:
print(tweet.text)
I entered my keys.
I should be able to download tweets using a command like this print_tweets.py "Enter subject here"
Where do I enter this command? In Python? In the command prompt?
I am getting this error:
NameError Traceback (most recent call
last) in ()
----> 1 print_tweets.py
NameError: name 'print_tweets' is not defined
Please help!
The NameError is saying the python script isn't receiving command line arguments, sys.argv[1] being the "subject". Replace "Enter subject here" with the subject you wish to search.
In this example, springbreak is sys.argv[1]:
C:\> python print_tweets.py springbreak
should return and print out tweet texts containing your "subject".
You may also need to change:
if __name__ == "__version__":
to
if __name__ == "__main__":
as __main__ is the entry-point to the script.
The entire script:
#!/usr/bin/env python
import sys
import tweepy
def get_tweets(api, input_query):
for tweet in tweepy.Cursor(api.search, q=input_query, lang="en").items():
yield tweet
if __name__ == "__main__":
input_query = sys.argv[1]
access_token = "REPLACE_YOUR_KEY_HERE"
access_token_secret = "REPLACE_YOUR_KEY_HERE"
consumer_key = "REPLACE_YOUR_KEY_HERE"
consumer_secret = "REPLACE_YOUR_KEY_HERE"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = get_tweets(api, input_query)
for tweet in tweets:
print(tweet.text)
Related
Hello I am searching how to create a Twitter bot that replies to all the tweets of a specific user in Python.
I already created a developer's account and I am a beginner in Python.
First, visit https://dev.twitter.com, and create a new application.
head your venv or anaconda and execute
pip install tweepy
Now, in your development directory, create a file, keys.py, and add the following code:
#!/usr/bin/env python
#keys.py
#visit https://dev.twitter.com to create an application and get your keys
keys = dict(
consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
)
Replace the ‘x’ fields with your keys and tokens from your newly created Twitter application
create a file, replybot.py, in the same directory as keys.py, and add the following code:
#!/usr/bin/env python
import tweepy
#from our keys module (keys.py), import the keys dictionary
from keys import keys
CONSUMER_KEY = keys['consumer_key']
CONSUMER_SECRET = keys['consumer_secret']
ACCESS_TOKEN = keys['access_token']
ACCESS_TOKEN_SECRET = keys['access_token_secret']
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
twts = api.search(q="Hello World!")
#list of specific strings we want to check for in Tweets
t = ['Hello world!',
'Hello World!',
'Hello World!!!',
'Hello world!!!',
'Hello, world!',
'Hello, World!']
for s in twt:
for i in t:
if i == s.text:
sn = s.user.screen_name
m = "#%s Hello!" % (sn)
s = api.update_status(m, s.id)
Check if your API is working . sleep is you ensure you are not asked to validate you are a bot python <program.py> .txt
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tweepy, time, sys
argfile = str(sys.argv[1])
#enter the corresponding information from your Twitter application:
CONSUMER_KEY = '1234abcd...'#keep the quotes, replace this with your consumer key
CONSUMER_SECRET = '1234abcd...'#keep the quotes, replace this with your consumer secret key
ACCESS_KEY = '1234abcd...'#keep the quotes, replace this with your access token
ACCESS_SECRET = '1234abcd...'#keep the quotes, replace this with your access token secret
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
filename=open(argfile,'r')
f=filename.readlines()
filename.close()
for line in f:
api.update_status(line)
time.sleep(900)#Tweet every 15 minutes
To reply to specific twitter user
toReply = "someonesTwitterName" #user to get most recent tweet
api = tweepy.API(auth)
#get the most recent tweet from the user
tweets = api.user_timeline(screen_name = toReply, count=1)
for tweet in tweets:
api.update_status("#" + toReply + " This is what I'm replying with", in_reply_to_status_id = tweet.id)
you can code whatever logic you want
def get_tweets(api, input_query):
for tweet in tweepy.Cursor(api.search, q=input_query,lang="en").items():
yield tweet
if __name__ == "__version__":
input_query = sys.argv[1]
access_token = "REPLACE_YOUR_KEY_HERE"
access_token_secret = "REPLACE_YOUR_KEY_HERE"
consumer_key = "REPLACE_YOUR_KEY_HERE"
consumer_secret = "REPLACE_YOUR_KEY_HERE"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = get_tweets(api, input_query)
for tweet in tweets:
print(tweet.text)
I am trying to download data from Twitter using the command prompt. I have entered my keys (I just recreated them all), saved the script as "print_tweets" and am entering "python print_tweets.py subject" into the command prompt but nothing is happening, no error message or anything.
I thought the problem might have to do with the path environment, but I created another program that prints out "hello world" and this executed without issue using the command prompt.
Can anyone see any obvious errors with my code above? Does this work for you?
I've even tried changing "version" to "main" but this gives me an error message:
if name == "version":
It seems you are running the script in an ipython interpreter, which won't be receiving any command line arguments. Try this:
import tweepy
def get_tweets(api, input_query):
for tweet in tweepy.Cursor(api.search, q=input_query,lang="en").items():
yield tweet
input_query = "springbreak" # Change this string to the topic you want to search tweets
access_token = "REPLACE_YOUR_KEY_HERE"
access_token_secret = "REPLACE_YOUR_KEY_HERE"
consumer_key = "REPLACE_YOUR_KEY_HERE"
consumer_secret = "REPLACE_YOUR_KEY_HERE"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = get_tweets(api, input_query)
for tweet in tweets:
print(tweet.text)
So I'm trying to get a timeline of a specific user. Here is the code:
import tweepy
consumer_key = 'numbers'
consumer_secret = 'numbers'
access_token = 'numbers'
access_token_secret = 'numbers'
user_list = [list of users]
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
for user in user_list:
for page in api.user_timeline(screen_name =user, count = 200):
print page
I've tried using the old documentation. When I run it I get the "Sorry, that page doesn't exist. Code 34"
I found the answer reading through the code documentation change screen_name to user_name
for user in users:
for page in api.user_timeline(user_id =user, count = 200):
print page
I'm using tweepy to find tweets containing a certain word, but I want to just get the newest tweets from the last five minutes up. How would I go about this? This is my code at the moment.
import tweepy
consumer_key = "**********"
consumer_secret = "**********"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token("**********", "**********")
api = tweepy.API(auth)
public_tweets = api.search(q = "", since = "2015-09-26", language = "EN")
for tweet in public_tweets:
print(tweet.text)
First of all: I edited your post to remove your credentials, I would suggest you get new ones from twitter and never share them again.
Also change your api.search (Rest API) to the Streaming API. This will give you a portion of tweets that match your criteria for the moment you open that connection.
For example
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
consumer_key = '****'
consumer_secret = '****'
access_token = '****'
access_secret = '****'
class Listener(StreamListener):
def on_status(self, status):
try:
print(str(status.text.encode('utf-8')))
except Exception as e:
print(e)
def on_error(self, status_code):
print(status_code)
while True:
try:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
twitterStream = Stream(auth, Listener())
twitterStream.filter(q=['python'])
except Exception as e:
print(e)
I'm trying to post a tweet with the tweepy library. I use this code:
import tweepy
CONSUMER_KEY ="XXXX"
CONSUMER_SECRET = "XXXX"
ACCESS_KEY = "XXXX"
ACCESS_SECRET = "XXXX"
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
api.update_status('Updating using OAuth authentication via Tweepy!')
But when I run the application, I receive this error:
raise TweepError(error_msg, resp)
TweepError: Read-only application cannot POST.
How can I fix this?
In the application's settings, set your Application Type to "Read and Write". Then renegotiate your access token.
the code works for me with only
api.update_status (**status** = 'Updating using OAuth authentication via Tweepy!')
You have to set your app to read and write
After that, you'll be able to run your code.
the following python script will tweet a line from a text file. if you want to tweet multiple tweets just put them on a new line separated by a blank line.
import tweepy
from time import sleep
# import keys from cregorg.py
from credorg import *
client = tweepy.Client(bearer_token, 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)
api = tweepy.API(auth, wait_on_rate_limit=True)
print("Tweet-TXT-Bot v1.0 by deusopus (deusopus#gmail.com)")
# Open text file tweets.txt (or your chosen file) for reading
my_file = open('tweets.txt', 'r')
# Read lines one by one from my_file and assign to file_lines variable
file_lines = my_file.readlines()
# Close file
my_file.close()
# Tweet a line every 5 minutes
def tweet():
for line in file_lines:
try:
print(line)
if line != '\n':
api.update_status(line)
sleep(300)
else:
pass
except tweepy.errors.TweepyException as e:
print(e)
while True:
tweet()