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()
Related
I am trying to print all screen_names found on a search result with Twython.
Here is my current code
#Import the required modules
from twython import Twython
#Setting the OAuth
Consumer_Key = ''
Consumer_Secret = ''
Access_Token = '-'
Access_Token_Secret = ''
#Connection established with Twitter API v1.1
twitter = Twython(Consumer_Key, Consumer_Secret,
Access_Token, Access_Token_Secret)
#Twitter is queried
response = twitter.search(q='Roblox', since='2017-02-25', until='2017-02-26')
for tweet in response["statuses"]:
st = tweet["entities"]["user_mentions"]
screen_name = st[0]["screen_name"]
f = open("output.txt", "a")
f.write(str(screen_name, ",\n"))
print(screen_name)
f.close()
but it is not editing or printing in the log file. Right as I start it, the program stops with no apparent error.
(the codes have been filled in, just removed for the post)
I have a Twitter bot that is following one specific account.
When that account Tweets, I want my bot to Tweet.
So far I have the below code:
import tweepy
import time
import sys
import inspect
consumer_key = 'xxxxxxx'
consumer_secret = 'xxxxxxxx'
access_token = 'xxxxxxx'
access_token_secret = 'xxxxxxxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
auth.secure = True
print "Test Message"
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
if status.user.screen_name.encode('UTF-8').lower() == 'xxxxxx': #account I am following
api.update_status('Test Tweet') # tweet that is sent from my bot
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=MyStreamListener())
myStream.filter(track=['xxxxxx'])
However, when I run this code from the command line, it runs without a problem but does not react to any Tweets from the specified account.
It seems like the if statement within your on_status method isn't properly indented.
If that's not the case, to properly debug this, you need to add an on_error method to your MyStreamListener class so that you're able to determine what, if any, error/status code is being returned by Twitter's API.
See the Handling Errors section of the Streaming With Tweepy documentation.
I'm trying to extract tweets using the historical Twitter API from Twitter and then copying them onto a text file. However, the text file is not being written to at all.
I've tried writing to a CSV though that has not worked either. It is being run on Python 3.6 and all the libraries are installed. I am not getting any error messages suggesting a problem with the text file.
import tweepy
import sys
import os
import codecs
CONSUMER_KEY = "" # These are removed for obvious reasons!
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)
f = codecs.open('C:\\Users\\ctrh1\\Desktop\\tweets30apr.txt', "w", encoding="utf-8")
for tweet in tweepy.Cursor(api.search,
q="brexit",
count=100,
since="2019-04-28",
until="2019-04-29",
lang="en").items():
print(tweet.text)
f.write(tweet.text)
I would expect to have the text from some tweets written to file f, but it is blank after I have stopped the code from running.
Maybe you can first try if you are authorized to write with this minimal example:
file_name = 'C:\\Users\\ctrh1\\Desktop\\tweets30apr.txt'
with open(file_name, 'w') as f:
f.write("Hello World!")
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'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)