Posting a Thread on Twitter/X using Playwright


Previously, we wrote about publishing a tweet on Twitter/X using Playwright. Check it out.

This time we go a step further and publish a thread, which is composed of several tweets. These are the steps

  const tweets = loadMessages();
  await clickCompose(page);
  await composeThread(page, tweets);
  await postAll(page);

We start with a list of tweets to post in a thread. Those tweets are in a tweets.jsonl file. The file contains one json object per line and each object contains a tweet property. The tweets were generated by ChatGP4. I will write another blog post about it.

Here’s an example

{"tweet":"1/ The Pareto Principle, also known as the 80/20 Rule, suggests that roughly 80% of effects come from 20% of causes. This can be seen in various domains, like business, health, and personal productivity. #MentalModels #ParetoPrinciple"}

After loading the tweets, we clickCompose and start adding each tweet to the thread.

Composing Thread

As you can see, it’s using tab to select the add button instead of clicking it directly. To be honest, I could’t build the locator to click the button. I’m having issues finding those buttons that don’t have text inside but an svg instead. So I figured I could use tab to focus the add button and then hit enter to “click” it.

async function addTweet(page: Page, firstTime: boolean) {
  const tabs = firstTime ? 7 : 6;
  for (let i = 0; i < tabs; i++) {
    await page.keyboard.press("Tab");
  }

  await page.keyboard.press("Enter");
}

You can see a firstTime variable there 😅. What happens is that a button dissappears when you’re composing a thread: the schedule button. That means I need to press tab less times after adding a second tweet to the thread. It’s not elegant but it works. It’s very likely to break in the future. We will fix it then.

The code

Find the code here and a video demo below. Thanks for reading!