Skip to content

Commit aa804e2

Browse files
committed
Move to Tweepy for v2 API support
1 parent 78b4da6 commit aa804e2

File tree

2 files changed

+15
-26
lines changed

2 files changed

+15
-26
lines changed

requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
python-twitter
1+
tweepy
22
requests

tweet_events.py

+14-25
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,13 @@
44
import json
55
import os
66
import sys
7-
import time
87

98
import requests
109

1110
try:
12-
import twitter
11+
import tweepy
1312
except ImportError:
14-
twitter = None
13+
tweepy = None
1514

1615

1716
class DatatrackerTracker:
@@ -62,7 +61,7 @@ def process_events(self, events, last_seen_id):
6261
if not self.args.dry_run:
6362
try:
6463
self.tweet(message)
65-
except twitter.error.TwitterError:
64+
except tweepy.TweepyException:
6665
break # didn't tweet so we should bail
6766
last_seen_id = event["id"]
6867
return last_seen_id
@@ -102,37 +101,27 @@ def format_message(self, event, template):
102101

103102
def init_twitter(self):
104103
try:
105-
self.twitter_api = twitter.Api(
104+
self.twitter_api = tweepy.Client(
106105
consumer_key=os.environ["TWITTER_CONSUMER_KEY"],
107106
consumer_secret=os.environ["TWITTER_CONSUMER_SECRET"],
108-
access_token_key=os.environ["TWITTER_TOKEN_KEY"],
107+
access_token=os.environ["TWITTER_TOKEN_KEY"],
109108
access_token_secret=os.environ["TWITTER_TOKEN_SECRET"],
109+
wait_on_rate_limit=True,
110110
)
111111
except KeyError as why:
112112
self.error(f"Environment variable not found: {why}")
113+
except tweepy.TweepyException as why:
114+
self.error(str(why))
113115

114-
def tweet(self, message, retry_count=0):
116+
def tweet(self, message):
115117
if self.twitter_api is None:
116118
self.init_twitter()
117119
try:
118-
status = self.twitter_api.PostUpdate(message)
119-
except twitter.error.TwitterError as why:
120-
details = why[0][0]
121-
# https://developer.twitter.com/en/support/twitter-api/error-troubleshooting#error-codes
122-
code = details.get("code", None)
123-
message = details.get("message", "unknown issue")
124-
if code in [88, 130]:
125-
if retry_count < self.RETRY_MAX:
126-
self.warn(f"{message}. Retrying.")
127-
time.sleep(self.RETRY_DELAY)
128-
self.tweet(message, retry_count + 1)
129-
else:
130-
self.warn(f"Exceeded max retries. Giving up.")
131-
elif code == 187:
132-
self.warn(f"Duplicate tweet '{message}'")
133-
else:
134-
self.warn(f"Tweet error code {code} ({message}). Aborting run.")
135-
raise # not an error, so we can remember what we read up to.
120+
status = self.twitter_api.create_tweet(text=message)
121+
except tweepy.HTTPException as why:
122+
for message in why.api_messages:
123+
self.warn(f"Tweet error: {message}")
124+
raise # not self.error, so we can remember what we read up to.
136125

137126
def parse_args(self, argv):
138127
parser = argparse.ArgumentParser(

0 commit comments

Comments
 (0)