Skip to content

Instantly share code, notes, and snippets.

@rotten77
Created July 25, 2023 18:16
Show Gist options
  • Save rotten77/5008095cf920f64557266669bbcd558e to your computer and use it in GitHub Desktop.
Save rotten77/5008095cf920f64557266669bbcd558e to your computer and use it in GitHub Desktop.
Send random article from Wiki to Mastodon
# import packages
from mastodon import Mastodon
import wikipedia
# function by Perplexity AI
def truncate_text(text):
if len(text) <= 200:
return text
else:
truncated_text = text[:200]
if text[200].isspace():
return truncated_text.strip() + "..."
else:
return truncated_text[:truncated_text.rfind(" ")] + "..."
# get random article
try:
wikipedia.set_lang('en')
random_page = wikipedia.page(wikipedia.random())
try:
# Mastodon API
mastodon = Mastodon(
access_token='SECRET_ACCESS_TOKEN',
api_base_url='https://mastodon.social')
# send post
mastodon.status_post(f'{random_page.title}\n{random_page.url}\n\n{truncate_text(random_page.summary)}')
except Exception as ex:
print(f"Exception (post article): {ex}")
except Exception as ex:
print(f"Exception (get article): {ex}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment