This repository has been archived by the owner on Feb 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtwitter.py
73 lines (55 loc) · 2.18 KB
/
twitter.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
import os
import logging
import tweepy
from tweepy.errors import *
def connect_twitter():
"""Authenticates to Twitter using credentials from environment vars.
Returns:
tweepy.Client: a Twitter API object.
"""
consumer_key = os.environ["TW_CONSUMER_KEY"]
consumer_secret = os.environ["TW_CONSUMER_KEY_SECRET"]
access_token = os.environ["TW_ACCESS_TOKEN"]
access_token_secret = os.environ["TW_ACCESS_TOKEN_SECRET"]
try:
client = tweepy.Client(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret)
except TooManyRequests as error:
logging.error("Twitter error: too many requests: %s", str(error))
raise
except TwitterServerError as error:
logging.error("An error happend on Twitter's server: %s", str(error))
raise
except Exception as error:
logging.error("Authenticating to Twitter failed. Cause: %s", str(error))
raise
logging.info("Authenticated to Twitter successfully.")
return client
def tweet(client, text, in_reply_to=None):
"""Tweets text, optionally replying to another tweet, and handles occuring errors.
Arguments:
client (tweepy.Client): a Twitter API object.
text (str): text of the tweet.
in_reply_to (int): id of the tweet to which this one will be replying. None by default.
Returns:
int: Posted tweet's id.
"""
try:
tweet = client.create_tweet(text=text, in_reply_to_tweet_id=in_reply_to)
logging.info("Successfully tweeted the message!")
return int(tweet.data["id"])
except TooManyRequests as error:
logging.error("Twitter error: too many requests: %s", str(error))
raise
except TwitterServerError as error:
logging.error("An error happend on Twitter's server: %s", str(error))
raise
except Forbidden as error:
logging.error("Posting a tweet failed because access is forbidden: %s", str(error))
raise
except Exception as error:
logging.error("Posting a tweet failed with an error: %s", str(error))
raise