I am trying to make a script in Python to reply to certain keywords on Twitter with Tweepy. I found this code on Google and tried it out. For some reason the Python screen automaticly closes without doing anything.
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)
twt = 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)
am I doing something wrong? I tried to open it in the module but I get this:
>>> ================================ RESTART ================================
Im not a coder or progammer but I would like to know how to get this working.
Thanks,
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
import tweepy
CONSUMER_KEY = 'My key'
CONSUMER_SECRET = 'My secret'
ACCESS_KEY = 'my key'
ACCESS_SECRET = 'my secret'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication OK")
except:
print("Error during authentication")
api.update_status("Hello")
Obviously at the top I don’t actually have my secret, my key, etc. up there, but I have the actual keys and it connects just fine. The problem is I keep getting an error whenever I try to send the tweet hello. Can anyone help?
You need to catch such exception.
I bet that the api throws DuplicateError (or similar as you don't show the stacktrace) when the status you set is identical.
something like:
from contextlib import suppress
from <your api module> import DuplicateError
...
with suppress(DuplicateError):
api.update_status("Hello")
...
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)
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)
I am trying to output the number of followers one user has on twitter using tweepy, I have searched high and low to find some answers and I managed to get some code:
import oauth, tweepy, sys, locale, threading
from time import localtime, strftime, sleep
def init():
global api
consumer_key = "..."
consumer_secret = "..."
access_key = "..."
access_secret = "..."
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
user = tweepy.api.get_user('...')
print user.screen_name
print user.followers_count
when I run this in python, i get errors of bad authentication,
could someone please explain why this is?
Thanks
You create the api object with the authentication, but then you don't use it and call tweepy directly.
This line:
user = tweepy.api.get_user('...')
Should be:
user = api.get_user('...')