-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbot.py
64 lines (52 loc) · 1.83 KB
/
bot.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
import os
import tweepy
from time import gmtime, strftime
from tweettext import TweetText, TweetTextError
try:
from config import *
except ImportError:
secrets = {
"TWITTER_ACCESS_TOKEN" : os.environ['TWITTER_ACCESS_TOKEN'],
"TWITTER_ACCESS_TOKEN_SECRET" : os.environ['TWITTER_ACCESS_TOKEN_SECRET'],
"TWITTER_CONSUMER_KEY" : os.environ['TWITTER_CONSUMER_KEY'],
"TWITTER_CONSUMER_SECRET" : os.environ['TWITTER_CONSUMER_SECRET']
}
config_vars = { 'LOG_LOCAL' : False }
# ========= Bot configuration =========
bot_name = "WhoseRep"
logfile_name = bot_name + ".log"
# =====================================
def create_tweet():
"""Create the tweet text"""
try:
TT = TweetText()
return TT.get()
except TweetTextError as e:
log(e.message)
return None
def tweet(text):
"""Tweet the text from the bot account"""
# Twitter auth
auth = tweepy.OAuthHandler(secrets['TWITTER_CONSUMER_KEY'], secrets['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(secrets['TWITTER_ACCESS_TOKEN'], secrets['TWITTER_ACCESS_TOKEN_SECRET'])
api = tweepy.API(auth)
try:
api.update_status(text)
except tweepy.TweepError as e:
log(e.message)
else:
log("Tweeted: " + text)
def log(message):
"""Enter message in log file"""
if config_vars['LOG_LOCAL']:
path = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
with open(os.path.join(path, logfile_name), 'a+') as f:
t = strftime("%d %b %Y %H:%M:%S", gmtime())
f.write("\n" + t + " " + message)
else:
# Heroku prints stdout and stderr to its Logplex
print bot_name + ": " + message
if __name__ == "__main__":
tweet_text = create_tweet()
if tweet_text:
tweet(tweet_text)