Skip to content

Instantly share code, notes, and snippets.

@Summonshr
Last active July 16, 2023 16:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Summonshr/5f3b3317e7f3b4c449f048688cec31f1 to your computer and use it in GitHub Desktop.
Save Summonshr/5f3b3317e7f3b4c449f048688cec31f1 to your computer and use it in GitHub Desktop.
Tweet automatically from nodejs script using openai and oauth1.0a
const axios = require('axios');
const util = require('util');
const crypto = require('crypto');
const OAuth = require('oauth-1.0a');
const options = [
'coding',
'music',
'sherlock holmes',
'wisdom',
'inspiration',
'peaky blinders'
];
const bearerToken = 'sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const prompt = `Give me one funny quote in ${options[Math.floor(Math.random() * options.length)]} less than 240 characters with 3 popular hashtags to post on Twitter that will get maximum attention. Don't give me what you have already given before.`;
const postAsync = util.promisify(axios.post);
async function generateQuote() {
try {
const response = await postAsync('https://api.openai.com/v1/engines/text-davinci-003/completions', {
prompt,
max_tokens: 500,
n: 1, // Number of quotes to generate
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${bearerToken}`,
},
});
const quotes = response.data.choices.map(choice => choice.text.trim());
return quotes[0];
} catch (error) {
console.error('Error:', error);
throw error;
}
}
async function tweet(data) {
const consumerKey = 'XXXXXXXXXXXXXXXXXX';
const consumerSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const endpointURL = 'https://api.twitter.com/2/tweets';
const oauth = OAuth({
consumer: {
key: consumerKey,
secret: consumerSecret
},
signature_method: 'HMAC-SHA1',
hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
});
const getRequest = async (data) => {
const token = {
key: '3323942491-XXXXXXXXXXXXXXXXXXXXX',
secret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
};
const authHeader = oauth.toHeader(oauth.authorize({
url: endpointURL,
method: 'POST'
}, token));
try {
const req = await axios.post(endpointURL, data, {
headers: {
Authorization: authHeader["Authorization"],
'user-agent': "v2CreateTweetJS",
'content-type': "application/json",
'accept': "application/json"
}
});
if (req.data) {
return req.data;
} else {
throw new Error('Unsuccessful request');
}
} catch (error) {
console.error('Error:', error);
throw error;
}
};
try {
const response = await getRequest({ text: data });
console.dir(response, { depth: null });
} catch (error) {
console.error(error);
process.exit(-1);
}
process.exit();
}
(async () => {
try {
const quote = await generateQuote();
await tweet(quote);
} catch (error) {
console.error(error);
process.exit(-1);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment