Skip to content

Instantly share code, notes, and snippets.

@ChristianOConnor
Last active April 25, 2022 00:37
Show Gist options
  • Save ChristianOConnor/9f301705bccd678fa76c07f01b1f2e90 to your computer and use it in GitHub Desktop.
Save ChristianOConnor/9f301705bccd678fa76c07f01b1f2e90 to your computer and use it in GitHub Desktop.
Sanitized Cloudflare Worker Tweet Through API Example (handler.ts)
function getRandomString(length) {
const randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for ( let i = 0; i < length; i++ ) {
result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
}
return result;
}
function hexToBase64(str) {
const stringChange = str.toString()
return btoa(String.fromCharCode.apply(null, stringChange.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}
async function postTweet() {
const oauth_consumer_key = '<OAUTH CONUMER KEY>'
const oauth_consumer_secret = '<OAUTH CONSUMER SECRET>'
const oauth_token = '<OAUTH TOKEN>'
const oauth_token_secret = 'OAUTH TOKEN SECRET'
const oauth_signature_method = 'HMAC-SHA1'
const oauth_version = '1.0'
const oauth_nonce = getRandomString(42)
const oauth_timestamp = Math.round(Date.now() / 1000)
const endpointURL = 'https://api.twitter.com/1.1/statuses/update.json?status';
const tweetData = {
status: 'The new NFT asset was uploaded to the blockchain'
}
const encodedTweet = encodeURIComponent(tweetData.status).replace(/!/g, '%21')
const params = 'POST&' + encodeURIComponent('https://api.twitter.com/1.1/statuses/update.json') + '&include_entities' + encodeURIComponent('=true&') + 'oauth_consumer_key' + encodeURIComponent('='+oauth_consumer_key+'&') + 'oauth_nonce' + encodeURIComponent('='+oauth_nonce+'&') + 'oauth_signature_method' + encodeURIComponent('='+oauth_signature_method+'&') + 'oauth_timestamp' + encodeURIComponent('='+oauth_timestamp+'&') + 'oauth_token' + encodeURIComponent('='+oauth_token+'&') + 'oauth_version' + encodeURIComponent('='+oauth_version+'&') + 'status' + encodeURIComponent('='+encodedTweet)
console.log(params)
console.log('')
console.log('')
const signingKey = encodeURIComponent(oauth_consumer_secret) + '&' + encodeURIComponent(oauth_token_secret)
console.log(signingKey)
//////HMAC-SHA1 Functionality//////
const keyReady = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(signingKey),
{ name: 'HMAC', hash: 'SHA-1' },
false,
['sign', 'verify'],
)
const hexStr = await crypto.subtle.sign('HMAC', keyReady, new TextEncoder().encode(params));
//const hexStr = CryptoJS.HmacSHA1(params, signingKey)
console.log(hexStr)
const signature = hexToBase64(hexStr)
const oauth_signature = encodeURIComponent(signature)
fetch('https://api.twitter.com/1.1/statuses/update.json', {
method: 'post',
headers: {
'Authorization': 'OAuth oauth_consumer_key="'+oauth_consumer_key+'",oauth_token="'+oauth_token+'",oauth_signature_method="HMAC-SHA1",oauth_timestamp="'+oauth_timestamp+'",oauth_nonce="'+oauth_nonce+'",oauth_version="1.0",oauth_signature="'+oauth_signature+'"',
'Content-Type': 'application/x-www-form-urlencoded' // 'application/json'
},
body: JSON.stringify(tweetData)
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
});
console.log('postTweet ran')
}
export async function handleRequest(request: Request): Promise<Response> {
await postTweet()
return new Response(`Hello worker! this is a ${request.method} request`, {
headers: { 'content-type': 'text/plain' },
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment