Skip to content

Update Threads Access Token #22

Update Threads Access Token

Update Threads Access Token #22

name: Update Threads Access Token
on:
schedule:
- cron: "0 0 */10 * *" # Runs every 10 days at midnight
workflow_dispatch: # Allows manual triggering from GitHub Actions UI
jobs:
update-token:
runs-on: ubuntu-latest
environment: deployment
steps:
- name: Get long-lived Threads access token
run: |
# Use your existing short-lived access token and app secret
SHORT_LIVED_TOKEN=${{ secrets.THREADS_ACCESS_TOKEN }}
APP_SECRET=${{ secrets.THREADS_APP_SECRET }}
# Exchange short-lived token for a long-lived token
RESPONSE=$(curl -i -X GET "https://graph.threads.net/access_token?grant_type=th_exchange_token&client_secret=$APP_SECRET&access_token=$SHORT_LIVED_TOKEN")
# Extract the long-lived access token from the response
THREADS_ACCESS_TOKEN=$(echo "$RESPONSE" | grep -oP '(?<=access_token":")[^"]*')
if [ -z "$THREADS_ACCESS_TOKEN" ]; then
echo "Failed to retrieve long-lived token"
exit 1 # Fail fast if the token isn't found
fi
echo "Long-lived access token retrieved successfully."
# Save the long-lived token as a GitHub secret
echo "::add-mask::$THREADS_ACCESS_TOKEN"
echo "THREADS_ACCESS_TOKEN=$THREADS_ACCESS_TOKEN" >> $GITHUB_ENV
- uses: actions/setup-node@v3
with:
node-version: 20
- name: Install LibSodium
run: |
npm install --global sodium-native@4.0.4
echo "NODE_PATH=$(npm root -g)" >> $GITHUB_ENV
- name: Update GitHub Secret with new token
uses: actions/github-script@v7
with:
result-encoding: string
github-token: ${{ secrets.UPDATE_THREADS_TOKEN_PAT }} # Use the PAT here for updating secrets
script: |
const sodium = require('sodium-native');
const { data: {key: publicKey, key_id: keyId} } = await github.rest.actions.getRepoPublicKey({...context.repo});
if (publicKey) {
const key = Buffer.from(publicKey, 'base64');
const message = Buffer.from(process.env.THREADS_ACCESS_TOKEN);
const ciphertext = Buffer.alloc(message.length + sodium.crypto_box_SEALBYTES);
sodium.crypto_box_seal(ciphertext, message, key);
const encryptedToken = ciphertext.toString('base64');
await github.rest.actions.createOrUpdateRepoSecret({
...context.repo,
secret_name: 'THREADS_ACCESS_TOKEN',
encrypted_value: encryptedToken,
key_id: keyId,
});
} else {
core.error('Failed to fetch the public key. Unable to update secret');
}