Last active
April 15, 2022 14:16
-
-
Save rojvv/871dfbbcd66d18fdc850b46560bc2ed2 to your computer and use it in GitHub Desktop.
Tweet with Deno using Puppeteer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { Browser } from "https://deno.land/x/puppeteer@9.0.2/mod.ts"; | |
// I do not like having the functions here as class methods because they are meant to be used as utilities. | |
// But you could have them in a class. :) | |
const endpoint = "https://twitter.com"; | |
/** | |
* Visits Twitter and signs in with the provided credentials if not already signed in. | |
*/ | |
export async function authenticate( | |
browser: Browser, | |
credentials: { username: string; password: string } | |
) { | |
const page = await browser.newPage(); | |
await page.goto(endpoint, { waitUntil: "networkidle2" }); | |
if ((await page.$("[data-testid=loginButton]")) != null) { | |
await page.goto(`${endpoint}/login`, { waitUntil: "networkidle2" }); | |
await (await page.waitForXPath( | |
'//*[text() = "Phone, email, or username"]' | |
))!.click(); | |
await page.keyboard.type(credentials.username); | |
await (await page.waitForXPath('//*[text() = "Next"]'))!.click(); | |
await (await page.waitForXPath('//*[text() = "Password"]'))!.click(); | |
await page.keyboard.type(credentials.password); | |
await (await page.waitForSelector( | |
'[data-testid="LoginForm_Login_Button"]' | |
))!.click(); | |
await page.waitForNavigation(); | |
} | |
await page.close(); | |
} | |
/** | |
* Visits Twitter and makes a tweet. | |
* | |
* - No time will be wasted, and | |
* - an error will be thrown unless the tweet is successful. :P | |
*/ | |
export async function tweet(browser: Browser, text: string) { | |
const page = await browser.newPage(); | |
await page.goto(`${endpoint}/home`, { waitUntil: "networkidle2" }); | |
await (await page.waitForSelector(".DraftEditor-root"))!.click(); | |
await page.keyboard.type(text); | |
await (await page.waitForSelector( | |
"[data-testid=tweetButtonInline]" | |
))!.click(); | |
await page.waitForXPath('//span[text() = "Your Tweet was sent."]'); | |
await page.close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment