/
send_tweet.py
104 lines (73 loc) · 2.45 KB
/
send_tweet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python
#
# Sends tweets
# @author John Van Note <johnlvannote@protonmail.com>
#
"""Consumes Tweets"""
import ConfigParser
import tweepy
import os
from MarkovChain import MarkovChain
PROP_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'twitter_keys.properties')
KEYS = 'Keys'
CON_KEY = 'consumer_key'
CON_SEC = 'consumer_secret'
TOKEN = 'access_token'
TOKEN_SEC = 'access_token_secret'
SRC_USER_ID = 'src_user_id'
def parse_properties(file_name, header):
"""Parses Properties File"""
config = ConfigParser.RawConfigParser()
config.read(file_name)
keys = dict()
keys[CON_KEY] = config.get(header, CON_KEY)
keys[CON_SEC] = config.get(header, CON_SEC)
keys[TOKEN] = config.get(header, TOKEN)
keys[TOKEN_SEC] = config.get(header, TOKEN_SEC)
keys[SRC_USER_ID] = config.get(header, SRC_USER_ID)
return keys
def generate_api(keys):
"""Users Twitter API to get tweets"""
auth = tweepy.OAuthHandler(keys[CON_KEY], keys[CON_SEC])
auth.set_access_token(keys[TOKEN], keys[TOKEN_SEC])
return tweepy.API(auth)
def generate_dict(api, user_id):
"""Generates Dictionary, no RT no @"""
tweets = list()
for tweet in tweepy.Cursor(api.user_timeline, id=user_id).items():
tweet_text = tweet._json['text'].encode('utf-8')
#tweet_text = json.dumps(tweet).encode('utf-8')
if not str.startswith(tweet_text, 'RT') and not str.startswith(tweet_text, '@'):
tweets.append(tweet_text)
markov_chain = MarkovChain(tweets)
return markov_chain
def send_tweet(api, tweet):
"""Sends a Tweet"""
if not isinstance(tweet, str):
raise TypeError('Tweet must be a String object')
if len(tweet) > 140:
raise Exception('Tweet is over maximum length')
api.update_status(tweet)
def decode(string):
"""Decodes a String"""
dec_string = string \
.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>')
return dec_string
def main():
"""Main function"""
props = parse_properties(PROP_FILE, KEYS)
api = generate_api(props)
markov_chain = generate_dict(api, props[SRC_USER_ID])
# print markov_chain.get_dictionary()
tweetable = False
while not tweetable:
tweet = markov_chain.generate_line()
tweet = decode(tweet)
print tweet
if len(tweet) < 280:
tweetable = True
send_tweet(api, tweet)
if __name__ == "__main__":
main()