-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
beatles_lyrics_bot.py
118 lines (99 loc) · 2.96 KB
/
beatles_lyrics_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
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
109
110
111
112
113
114
115
116
117
118
"""Beatles lyrics bot module"""
import random
import logging
from datetime import datetime, timezone
import tweepy
import requests
from mastodon import Mastodon
from masto_auth import ACCESS_TOKEN_MASTODON
from bluesky_auth import BLUESKY_HANDLE, BLUESKY_APP_PASSWORD
from auth import ACCESS_TOKEN, ACCESS_TOKEN_SECRET, API_KEY, API_SECRET_KEY
logging.basicConfig(filename='beatles.log', level=logging.DEBUG)
client = tweepy.Client(
consumer_key=API_KEY,
consumer_secret=API_SECRET_KEY,
access_token=ACCESS_TOKEN,
access_token_secret=ACCESS_TOKEN_SECRET
)
mastodon = Mastodon(access_token=ACCESS_TOKEN_MASTODON, api_base_url="https://mastodon.world")
def random_line(afile):
"""
Get a random line from a given file.
Parameters
----------
afile : int
File handle to get the random line from.
Returns
-------
line : str
Random line from the file.
"""
line = next(afile)
for num, aline in enumerate(afile, 2):
if random.randrange(num):
continue
line = aline
return line
def bluesky_post(text):
"""
Send a post to BlueSky.
Parameters
----------
text : str
Text to send to BlueSky
"""
resp = requests.post(
"https://bsky.social/xrpc/com.atproto.server.createSession",
json={"identifier": BLUESKY_HANDLE, "password": BLUESKY_APP_PASSWORD},
timeout=10,
)
resp.raise_for_status()
session = resp.json()
now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
hashtag = "#TheBeatles"
hashtag_start = text.find(hashtag)
hashtag_end = hashtag_start + len(hashtag)
post = {
"$type": "app.bsky.feed.post",
"text": text,
"createdAt": now,
"facets": [
{
"index": {
"byteStart": hashtag_start,
"byteEnd": hashtag_end
},
"features": [
{
"$type": "app.bsky.richtext.facet#tag",
"tag": "TheBeatles"
}
]
}
]
}
post["langs"] = ["en-US"]
resp = requests.post(
"https://bsky.social/xrpc/com.atproto.repo.createRecord",
headers={"Authorization": "Bearer " + session["accessJwt"]},
json={
"repo": session["did"],
"collection": "app.bsky.feed.post",
"record": post,
},
timeout=10,
)
resp.raise_for_status()
try:
with open('data/lyrics.txt', 'r', encoding="UTF-8") as f:
rline = random_line(f).split('\n')[0]
rline = f'{rline} #TheBeatles'
# print(rline)
try:
mastodon.toot(rline)
bluesky_post(rline)
client.create_tweet(text=rline)
except tweepy.errors.TweepyException as tw:
logging.error("Couldn't send the tweet: %s", tw)
except OSError:
logging.error("Couldn't open lyrics file")