-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtweet.py
108 lines (84 loc) · 3.47 KB
/
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
105
106
107
108
import getopt
import os
import sys
import configparser
import twitter
TWITTER_DM_LIMIT = 10000
TWITTER_TWEET_LIMIT = 250
UNSUCCESSFUL_REPLY_ERROR = 385
MAX_THREAD_RETRY = 5
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
class TweetRc(object):
def __init__(self, config_section, config_path):
self._config = None
self.config_path = config_path
self.config_section = config_section
def GetConsumerKey(self):
return self._GetOption('consumer_key')
def GetConsumerSecret(self):
return self._GetOption('consumer_secret')
def GetAccessKey(self):
return self._GetOption('access_key')
def GetAccessSecret(self):
return self._GetOption('access_secret')
def GetErrorNotifyUser(self):
return self._GetOption('error_notify_user')
def _GetOption(self, option):
try:
return self._GetConfig().get(self.config_section, option)
except:
return None
def _GetConfig(self):
if not self._config:
self._config = configparser.ConfigParser()
self._config.read(os.path.expanduser(self.config_path))
return self._config
class TwitterHandler():
def __init__(self, config_section, config_path=f'{os.path.dirname(os.path.realpath(__file__))}/.tweetrc'):
self.twitter_config = TweetRc(config_section, config_path)
consumer_key = self.twitter_config.GetConsumerKey()
consumer_secret = self.twitter_config.GetConsumerSecret()
access_key = self.twitter_config.GetAccessKey()
access_secret = self.twitter_config.GetAccessSecret()
if not consumer_key or not consumer_secret or not access_key or not access_secret:
raise ValueError('Missing required twitter credentials')
self._api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret,
access_token_key=access_key, access_token_secret=access_secret)
def tweet(self, message, reply_to=None):
if reply_to:
return self._api.PostUpdate(message,
in_reply_to_status_id=reply_to,
auto_populate_reply_metadata=True
)
else:
return self._api.PostUpdate(message)
def dm(self, message, to=None):
if not to:
to = self.twitter_config.GetErrorNotifyUser()
recipient = self._api.GetUser(screen_name=to, return_json=True)
responses = []
for chunk in chunks(message, TWITTER_DM_LIMIT):
responses.append(self._api.PostDirectMessage(chunk, user_id=recipient['id'], return_json=True) )
return responses
def tweet_thread(self, messages):
thread = self.tweet(messages[0])
prev = thread
for message in messages[1:]:
count = 0
while count < MAX_THREAD_RETRY:
try:
prev = self.tweet(message, reply_to=prev.id)
break
except twitter.error.TwitterError as ex:
if ex.message[0]['code'] == UNSUCCESSFUL_REPLY_ERROR:
count += 1
print(f'Unsuccessful reply of "{message}" to tweet {prev.id}. Attempts: {count}')
continue
else:
raise(ex)
return thread
def retweet(self, status_id):
return self._api.PostRetweet(status_id)