This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmastodon_postbot.py
209 lines (187 loc) · 9.15 KB
/
mastodon_postbot.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
import os.path
import sys
import re
import sqlite3
from datetime import datetime, timedelta
import feedparser
from mastodon import Mastodon
import requests, json, time, logging
from bs4 import BeautifulSoup
def main():
# sqlite db to store processed tweets (and corresponding post ids)
sql = sqlite3.connect('/config/tootbot.db')
db = sql.cursor()
db.execute('''CREATE TABLE IF NOT EXISTS tweets (tweet text, toot text,
twitter text, mastodon text, instance text)''')
if os.environ.get('RSS_BRIDGE_URL'):
d = requests.get(url=f'{os.environ.get("RSS_BRIDGE_URL")}').json()
elif os.environ.get('RSS_BRIDGE_BASE_URL'):
if os.environ.get('TWITTER_USER'):
twitter = os.environ.get('TWITTER_USER')
d = requests.get(
url=
f'{os.environ.get("RSS_BRIDGE_BASE_URL")}/?action=display&bridge=TwitterBridge&context=By+username&u={twitter}&norep=on&nopinned=on&format=Json'
).json()
elif os.environ.get('TWITTER_SEARCH'):
twitter = os.environ.get('TWITTER_SEARCH')
d = requests.get(
url=
f'{os.environ.get("RSS_BRIDGE_BASE_URL")}/?action=display&bridge=TwitterBridge&context=By+keyword+or+hashtag&q=%23{twitter}&format=Json'
).json()
else:
print(f'TWITTER_USER or TWITTER_SEARCH must be set')
raise
else:
print(f'RSS_BRIDGE_URL or RSS_BRIDGE_BASE_URL must be set')
raise
if not os.environ.get('MASTODON_INSTANCE'):
print(f'MASTODON_INSTANCE must be set')
else:
instance = os.environ.get('MASTODON_INSTANCE')
if not os.environ.get('MASTODON_TOKEN'):
print(f'MASTODODN_TOKEN must be set')
else:
access_token = os.environ.get('MASTODON_TOKEN')
mastodon_api = None
days = os.environ.get('DAYS') if os.environ.get('DAYS') else 1
tags = os.environ.get('TAGS')
delay = os.environ.get('DELAY') if os.environ.get('DELAY') else 0
mastodon = 'bot_account'
if d.get('items'):
items_sorted = sorted(d['items'],
key=lambda item: item['date_modified'],
reverse=False)
for t in items_sorted:
# check if this tweet has been processed
if t.get('id'):
id = t['id'].translate({ord("\\"): None})
else:
id = t['title'].translate({ord("\\"): None})
db.execute(
'SELECT * FROM tweets WHERE tweet = ? AND twitter = ? and mastodon = ? and instance = ?',
(id, twitter, mastodon, instance)) # noqa
last = db.fetchone()
dt = datetime.strptime(t['date_modified'],
'%Y-%m-%dT%H:%M:%S+00:00')
age = datetime.now() - dt
# process only unprocessed tweets less than 1 day old, after delay
if last is None and age < timedelta(days=days) and age > timedelta(
days=delay):
mastodon_api = Mastodon(access_token=access_token,
api_base_url=f'https://{instance}')
try:
soup = BeautifulSoup(t['content_html'])
c = soup.blockquote.text
except Exception as e:
raise
post_media = []
media_embed = {}
author_string = t['_rssbridge']['username']
# get the pictures...
if t.get('attachments'):
# Return a set of positive indexes for video links and/or -1 for all non-video links (usually thumbnails for videos)
check_urls_for_video = set([
x['url'].find('video.twimg') for x in t['attachments']
])
# Discard the non-video link
check_urls_for_video.discard(-1)
if len(check_urls_for_video) >= 1:
for a in t['attachments']:
url = a['url'].translate({ord("\\"): None})
print(url)
for p in re.finditer(
r"https://video.twimg.com/[^ \xa0\"]*",
url):
print(f'P: {p}')
media = requests.get(p.group(0))
try:
media_posted = mastodon_api.media_post(
media.content,
mime_type=media.headers.get(
'content-type'))
post_media.append(media_posted['id'])
except:
media_embed[
'error'] = 'Media too large to embed. Please visit original URL'
pass
elif len(check_urls_for_video) == 0:
for a in t['attachments']:
url = a['url'].translate({ord("\\"): None})
for p in re.finditer(
r"https://pbs.twimg.com/[^ \xa0\"]*", url):
media = requests.get(p.group(0))
try:
media_posted = mastodon_api.media_post(
media.content,
mime_type=media.headers.get(
'content-type'))
post_media.append(media_posted['id'])
except:
media_embed[
'error'] = 'Media too large to embed. Please visit original URL'
pass
# replace short links by original URL
# m = re.search(r"http[^ \xa0]*", c)
# if m is not None:
# l = m.group(0)
# r = requests.get(l, allow_redirects=False)
# if r.status_code in {301, 302}:
# c = c.replace(l, r.headers.get('Location'))
# remove pic.twitter.com links
m = re.search(r"pic.twitter.com[^ \xa0]*", c)
if m is not None:
l = m.group(0)
c = c.replace(l, ' ')
# remove ellipsis
c = c.replace('\xa0…', ' ')
c = t['url'].translate({ord('\\'): None}) + '\n\n' + c
if os.environ.get('TWITTER_USER'):
if twitter and twitter.lower() not in author_string.lower(
):
c = (u"\U0001F501 " + f'Re-Tweeted from ') + c
else:
c = (f'Original Post: ') + c
elif os.environ.get('TWITTER_SEARCH'):
c = (f'Original Post: ') + c
if tags:
c = c + '\n' + tags
if media_embed.get('error'):
c = c + f"\n\n({media_embed['error']})"
if post_media != []:
print('Posting Tweet: %s' % t['title'])
try:
post = mastodon_api.status_post(c,
in_reply_to_id=None,
media_ids=post_media,
sensitive=False,
visibility='public',
spoiler_text=None)
if "id" in post:
db.execute(
"INSERT INTO tweets VALUES ( ? , ? , ? , ? , ? )",
(id, post["id"], twitter, mastodon, instance))
sql.commit()
except Exception as e:
print(e)
else:
print('Posting Tweet: %s' % t['title'])
try:
post = mastodon_api.status_post(c,
in_reply_to_id=None,
media_ids=None,
sensitive=False,
visibility='public',
spoiler_text=None)
if "id" in post:
db.execute(
"INSERT INTO tweets VALUES ( ? , ? , ? , ? , ? )",
(id, post["id"], twitter, mastodon, instance))
sql.commit()
except Exception as e:
print(e)
else:
Exception('RSS Feed is not compatible')
if __name__ == "__main__":
while True:
main()
time.sleep(300)