Tuesday, November 28, 2023

How to automate cross posting between Mastodon and Twitter using IFTTT

I recently moved from Twitter (X) to Mastodon and as part of this, I wanted to automate cross-posting between the two even though I mostly interact with Mastodon. I have an account with IFTTT but unfortunately, it does not support Mastodon natively yet with some scripting magic you can achieve this relatively easily.

The first thing you need to deal with is that depending on if you have an image in your post or not would want to use two different actions in IFTTT. The way I solved this was to set up my chain of triggers and actions like this by adding both of the Twitter actions in the same recipe.

The RSS feed you want to feed is the URL of your account with the string .rss appended at the end. For my account, the whole URL is https://fosstodon.org/@hpj.rss. Finally, you need a little bit of filter script magic listed below.

const message = Feed.newFeedItem.EntryContent.replace( /(<([^>]+)>)/ig, '');

if (Feed.newFeedItem.EntryImageUrl && 
    Feed.newFeedItem.EntryImageUrl !== "https://ifttt.com/images/no_image_card.png") {
  Twitter.postNewTweetWithImage.setPhotoUrl(Feed.newFeedItem.EntryImageUrl);
  Twitter.postNewTweetWithImage.setTweet(message);
  Twitter.postNewTweet.skip("Had photo: \"" + Feed.newFeedItem.EntryImageUrl + "\"");
} else {
  Twitter.postNewTweetWithImage.skip("No photo");
  Twitter.postNewTweet.setTweet(message);
}

The two things you need to fix in the script are that Mastodon adds a whole bunch of tags and stuff to their RSS feed that Twitter will not like so we filter that out. Secondly, we determine if there is a picture associated or not and this is done by checking if the image URL is either empty or pointing to the IFTT "no picture" placeholder. Then we post the tweaked entry to the correct action and skip the one that doesn't match if we have an image or not.