Twitter bot that replies to all the tweets of my friend. Python - 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

Related

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)

Can't send tweets with python using Twitter API (foreign letters)

Sooo yeah, pretty much what the title says. Can't seem to tweet foreign letter's to twitter, not quite sure why though, so i'm hoping if anybody can help me there. The foreign letters are "õüöä" Here is my .py file:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tweepy, time, sys
argfile = str(sys.argv[1])
#API details
CONSUMER_KEY = 'xx'
CONSUMER_SECRET = 'xx'
ACCESS_KEY = 'xx'
ACCESS_SECRET = 'xx'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
str.decode('utf-8')
filename=open(argfile,'r')
f=filename.readlines()
filename.close()
for line in f:
api.update_status(line)
time.sleep(120)
My .txt file where tweets are included:
Üks
Kaks
Kolm
Neli
Viis
Kuus
Seitse
Kaheksa
Üheksa
Kümme

Tweet reply tweepy

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,

how to post anything else than strings with tweepy

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.

How to get number of followers on twitter using tweepy

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('...')

Categories