-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
277 lines (235 loc) Β· 6.84 KB
/
main.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# SPDX-FileCopyrightText: 2024 Deren Vural [email protected]
# SPDX-License-Identifier: MIT
##
# Title: OSRSBlueskyBot
# Author: Deren Vural
# Notes:
# https://docs.bsky.app/docs/starter-templates/bots
# https://docs.bsky.app/blog/rate-limits-pds-v3#pds-distribution-v3
#
# https://atproto.blue/en/latest/
# https://github.com/bluesky-hack/bot/blob/main/main.py
# https://sperea.es/blog/bot-bluesky-rss
#
# https://github.com/bluesky-social/atproto/tree/main/packages/api
# https://docs.python.org/3/library/typing.html
##
# imports
from atproto import (
Client,
models
)
import os
import dotenv
import feedparser
import requests
# main function
def main() -> bool:
# Status message
print("π€ Starting bot..")
# Fetch config from environment variables
configData = fetchConfig()
# Validate environment variables fetched
if(configData):
# Status message
print("π€ Bot fetched environment variables..")
else:
# Status message
print("π€ Bot was unable to fetch environment variables..")
# Return failure
return False
# Create client
client = Client("https://bsky.social")
# Log in to Bluesky
loginSuccess = loginBluesky(
client,
configData['BLUESKY_USERNAME'],
configData['BLUESKY_PASSWORD']
)
# Validate log in
if(loginSuccess):
# Status message
print("π€ Bot is logged in to Bluesky..")
else:
# Status message
print("π€ Bot failed to log in to Bluesky..")
# Return failure
return False
# Get last post
lastPost = getLastPost(
client
)
if(lastPost == ""):
# Status message
print("π€ Bot cannot get previous post..")
else:
# Output title of last post to log
print("π€ Last Bluesky post: " + lastPost)
# Status message
print("π€ Bot fetched previous post..")
# Fetch RSS content to post
RSSContent = fetchRSS(
configData['OSRS_RSS_URL'],
lastPost
)
# If new RSS item found
if(RSSContent):
# Status message
print("π€ Bot has found a new RSS item..")
else:
# Status message
print("π€ Bot has not found a new RSS item..")
# Return failure
return False
# Post to Bluesky
postSuccess = sendPost(
client,
RSSContent
)
# Validate post
if(postSuccess):
# Status message
print("π€ Bot has posted to Bluesky..")
else:
# Status message
print("π€ Bot has failed to post to Bluesky..")
# Return failure
return False
# Return success
return True
# Fetch login info from environment variables
def fetchConfig() -> dict[str, str]:
# Status message
print(f"π€ Bot loading environment variables..")
if "BLUESKY_USERNAME" not in os.environ:
print(f"π€ Bot cannot find key \'BLUESKY_USERNAME\' in environment variables..")
return {}
if "BLUESKY_PASSWORD" not in os.environ:
print(f"π€ Bot cannot find key \'BLUESKY_PASSWORD\' in environment variables..")
return {}
if "OSRS_RSS_URL" not in os.environ:
print(f"π€ Bot cannot find key \'OSRS_RSS_URL\' in environment variables..")
return {}
# Return in dictionary
return {
'BLUESKY_USERNAME' : os.environ['BLUESKY_USERNAME'],
'BLUESKY_PASSWORD' : os.environ['BLUESKY_PASSWORD'],
'OSRS_RSS_URL' : os.environ['OSRS_RSS_URL']
}
def getLastPost(
client: Client
) -> str:
# Attempt to get last post
try:
# Return text of last post
posts = client.app.bsky.feed.post.list(client.me.did, limit=1)
for uri, post in posts.records.items():
return post.text
except Exception as e:
# Return failure
print(e)
return ""
# Log in client to Bluesky
# TODO: return & check success
def loginBluesky(
client: Client,
username: str,
password: str
) -> bool:
# Log in
try:
client.login(username, password)
except Exception as e:
# Return failure
print(e)
return False
# Return success
return True
# Get RSS feed
def fetchRSS(
RSSUrl: str,
lastPost: str
) -> dict[str, str]:
# Parse the RSS feed
feed = feedparser.parse(
RSSUrl
)
try:
# Output title of last RSS post to log
print("π€ Title: " + feed.entries[0].title)
print("π€ Content: " + feed.entries[0].summary)
# Check if is new item
if feed.entries[0].summary != lastPost:
# Return feed item content as dictionary
return {
'TITLE' : feed.entries[0].title,
'SUMMARY' : feed.entries[0].summary,
'URL' : feed.entries[0].link,
'DATE' : feed.entries[0].published,
'IMAGEURL' : feed.entries[0].links[0].href
}
else:
# Return empty dictionary
return {}
except:
print("π€ Bot cannot find content in RSS feed..")
return {}
# Download image
def downloadImage(
url: str
):
# Attempt to download image
try:
return requests.get(url).content
except Exception as e:
# Return 'None'
print(e)
return
# Post to Bluesky
# TODO: return & check success
def sendPost(
client: Client,
RSSContent: dict[str, str]
) -> bool:
# Validate RSS content
if "TITLE" not in RSSContent:
print(f"π€ Bot cannot find key \'TITLE\' in dictionary..")
return {}
if "SUMMARY" not in RSSContent:
print(f"π€ Bot cannot find key \'SUMMARY\' in dictionary..")
return {}
if "URL" not in RSSContent:
print(f"π€ Bot cannot find key \'URL\' in dictionary..")
return {}
if "IMAGEURL" not in RSSContent:
print(f"π€ Bot cannot find key \'IMAGEURL\' in dictionary..")
return {}
# Create & send post
try:
# Attempt to download image
image = downloadImage(RSSContent['IMAGEURL'])
# Create thumbnail
thumb = client.upload_blob(image)
# Create embedded link
embed = models.AppBskyEmbedExternal.Main(
external=models.AppBskyEmbedExternal.External(
title=RSSContent['TITLE'],
description=RSSContent['SUMMARY'],
uri=RSSContent['URL'],
thumb=thumb.blob,
)
)
# Send post with text
client.send_post(RSSContent['SUMMARY'], embed=embed)
except Exception as e:
# Return failure
print(e)
return False
# Return success
return True
# Run main() function
if __name__ == '__main__':
if(main() == True):
print("π€ Bot succeeded!")
else:
print("π€ Bot failed!")