From 1335da82da99591abc88d55a5122491f7ea8935a Mon Sep 17 00:00:00 2001 From: m33m33 <m33@tok715.net> Date: Sat, 15 Aug 2020 23:48:37 +0200 Subject: [PATCH] Better error management when requesting source assets --- tootbot.py | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/tootbot.py b/tootbot.py index 1bc7b79..ddead15 100755 --- a/tootbot.py +++ b/tootbot.py @@ -71,7 +71,7 @@ for t in reversed(d.entries): try: Mastodon.create_app('tootbot', api_base_url='https://'+instance, to_file='/var/run/lock/'+instance+'.secret') except: - print('ERROR: failed to create app on instance '+instance) + print('ERROR: Failed to create app on instance '+instance) sys.exit(1) try: @@ -82,7 +82,7 @@ for t in reversed(d.entries): ) if debug: print(" ok.") except: - print("ERROR: can't connect") + print("ERROR: Can't connect to Mastodon instance") sys.exit(1) if debug: print("Login with email ",mastodon_account_email," ...", end='') @@ -94,7 +94,7 @@ for t in reversed(d.entries): ) if debug: print(" ok.") except: - print("ERROR: First Login Failed! ",) + print("ERROR: First Login Failed !") sys.exit(1) c = t.title @@ -106,17 +106,23 @@ for t in reversed(d.entries): toot_media = [] # get the pictures... for p in re.finditer(r"https://pbs.twimg.com/[^ \xa0\"]*", t.summary): - media = requests.get(p.group(0)) - media_posted = mastodon_api.media_post(media.content, mime_type=media.headers.get('content-type')) - toot_media.append(media_posted['id']) + try: + media = requests.get(p.group(0)) + media_posted = mastodon_api.media_post(media.content, mime_type=media.headers.get('content-type')) + toot_media.append(media_posted['id']) + except: + print("ERROR: Can't get media !") # 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')) + try: + r = requests.get(l, allow_redirects=False) + if r.status_code in {301, 302}: + c = c.replace(l, r.headers.get('Location')) + except: + print("ERROR: Can't get links !") # remove pic.twitter.com links m = re.search(r"pic.twitter.com[^ \xa0]*", c) @@ -128,10 +134,11 @@ for t in reversed(d.entries): c = c.replace('\xa0…', ' ') if twitter is None: - c = c + '\nSource: '+ t.authors[0].name +'\n\n' + t.link + c = c + '\n\nSource: ' + t.authors[0].name + ' ' + t.link if tags: - c = c + '\n' + tags + if len(tags) > 2: + c = c + '\n' + tags if toot_media is not None: toot = mastodon_api.status_post(c, in_reply_to_id=None, @@ -143,7 +150,7 @@ for t in reversed(d.entries): db.execute("INSERT INTO tweets VALUES ( ? , ? , ? , ? , ? )", (t.id, toot["id"], source, mastodon, instance)) sql.commit() - sleep(0.1) + sleep(0.2) else: if debug: print(".",end='') -- GitLab