how to post anything else than strings with tweepy - python

I'm trying to update my Twitter status with generated text. So far generating the text works well, but I cannot post to Twitter.
import tweepy
import SentenceGenerator
with open('Ratschlaege.txt','r') as textfile: #load the text to analyze
sample_text = textfile.read()
#Generating one sentence:
#print SentenceGenerator.generate_sentence(sample_text)
#Generating a paragraph:
sentences = 1
print ' '.join([SentenceGenerator.generate_sentence(sample_text) for i in xrange(sentences)])
# Consumer keys and access tokens, used for OAuth
consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token = 'xxx'
access_token_secret = 'xxx'
# 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)
# Sample method, used to update a status
api.update_status(' '.join([SentenceGenerator.generate_sentence(sample_text) for i in xrange(sentences)]))
As far as I have found you can either post strings or from a file, but not the new generated text.
Is there any way?
——EDIT——
okay i tried to build a function inside my script like this
def tweet (tweet):
tweet = ' '.join([SentenceGenerator.generate_sentence(sample_text) for i in xrange(sentences)])
# Consumer keys and access tokens, used for OAuth
consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token = 'xxx'
access_token_secret = 'xxx'
# 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)
# Sample method, used to update a status
api.update_status(tweet)
time.sleep(10)
now it runs, every ten seconds in a loop (to test it out), and there is no error displayed but the status won't update. it runs like its supposed to do, only it doesn't tweet.
what am i missing??
——EDIT——
i also added a part that should insert the generated text into a MySQL db
db = MySQLdb.connect ( host ='127.0.0.1',
user = 'Daniel',
passwd = 'localhost')
cur = db.cursor()
cur.execute("insert into multigram (Ratschlag) value ('%s')" % (tweet))
Same here: No error message but also no entry in the db.
i am sure it's so simple to resolve, but i don't see what i am doing wrong.

Related

Twitter bot that replies to all the tweets of my friend. Python

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

Using twython to log all screen_names of users who posted about a certain keyword on a certain date

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)

Getting whole user timeline of a Twitter user

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)

Error scraping friend list from Twitter user w/ api.lookup_users: Too many terms specified in query

The code below was provided to another user who was scraping the "friends" (not followers) list of a specific Twitter user. For some reason, I get an error when using "api.lookup_users". The error states "Too many terms specified in query". Ideally, I would like to scrape the followers and output a csv with the screen names (not ids). I would like their descriptions as well, but can do this in a separate step unless there is a suggestion for pulling both pieces of information. Below is the code that I am using:
import time
import tweepy
import csv
#Twitter API credentials
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
ids = []
for page in tweepy.Cursor(api.friends, screen_name="").pages():
ids.extend(page)
time.sleep(60)
print(len(ids))
users = api.lookup_users(user_ids=ids) #iterates through the list of users and prints them
for u in users:
print(u.screen_name)
From the error you get, it seems that you are putting too many ids at once in the api.lookup_users request. Try splitting you list of ids in smaller parts and make a request for each part.
import time
import tweepy
import csv
#Twitter API credentials
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
ids = []
for page in tweepy.Cursor(api.friends, screen_name="").pages():
ids.extend(page)
time.sleep(60)
print(len(ids))
idChunks = [ids[i:i + 300] for i in range(0, len(ids), 300)]
users = []
for idChunk in idChunks:
try:
users.append(api.lookup_users(user_ids=idChunk))
except tweepy.error.RateLimitError:
print("RATE EXCEDED. SLEEPING FOR 16 MINUTES")
time.sleep(16*60)
users.append(api.lookup_users(user_ids=idChunk))
for u in users:
print(u.screen_name)
print(u.description)
This code has not been tested, and does not writes the CSV, but it should help you getting past that error you were having. The size of 300 for the chunks is completely arbitrary, adjust it if it is too small (or too big).

How to get the tweet id for the tweet generated using tweepy library's update_status method

To post a new tweet via tweepy, I've used the below code
#Twitter credentials - Augrav
access_token = config.get('twitter_credentials', 'access_token')
access_token_secret = config.get('twitter_credentials', 'access_token_secret')
consumer_key = config.get('twitter_credentials', 'consumer_key')
consumer_secret = config.get('twitter_credentials', 'consumer_secret')
account_id = config.get('twitter_credentials', 'account_id')
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
msg = "Howdy howdy"
api.update_status(status=msg)
How to get this newly generated tweet id ?
There's no info about this in the official tweepy docs.
Ref: http://docs.tweepy.org/en/v3.2.0/api.html
This is more trivial than you would probably want to believe.
From the documentation you can see that the update_status method returns a status object. As do most methods in the API. This status object essentially contains all the information about that tweet.
# after establishing a connection
In [15]: msg = "Tweeting from tweepy"
# retain the object returned
In [16]: tweet = api.update_status(status=msg)
# the id (and practically any attribute, print a tweet to view them!)
# can be easily accessed via
In [17]: tweet.id_str
Out[17]: u'646306396464656384'

Categories