From 915495b0a32d0124478c1a8567fef6cb914dfd05 Mon Sep 17 00:00:00 2001 From: Blake McNeal Date: Tue, 12 Nov 2024 14:50:29 -0500 Subject: [PATCH] Add GitHub Actions workflow and poll_and_respond script for Slack ChatGPT bot --- .github/workflows/on_demand_chatgpt_bot.yml | 27 ++++++++++++++ scripts/poll_and_respond.js | 41 +++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 .github/workflows/on_demand_chatgpt_bot.yml create mode 100644 scripts/poll_and_respond.js diff --git a/.github/workflows/on_demand_chatgpt_bot.yml b/.github/workflows/on_demand_chatgpt_bot.yml new file mode 100644 index 0000000..3e2a92f --- /dev/null +++ b/.github/workflows/on_demand_chatgpt_bot.yml @@ -0,0 +1,27 @@ +name: Trigger ChatGPT Slack Bot + +on: + workflow_dispatch: # Enables manual triggering from GitHub Actions + +jobs: + run-bot: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Node.js + uses: actions/setup-node@v2 + with: + node-version: '16' + + - name: Install dependencies + run: npm install + + - name: Run ChatGPT Slack Bot + env: + SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + run: | + node scripts/poll_and_respond.js diff --git a/scripts/poll_and_respond.js b/scripts/poll_and_respond.js new file mode 100644 index 0000000..c3365a0 --- /dev/null +++ b/scripts/poll_and_respond.js @@ -0,0 +1,41 @@ +const { WebClient } = require('@slack/web-api'); +const axios = require('axios'); + +const slackToken = process.env.SLACK_BOT_TOKEN; +const openAiKey = process.env.OPENAI_API_KEY; +const slackClient = new WebClient(slackToken); + +(async () => { + try { + // Fetch recent messages mentioning the bot + const result = await slackClient.conversations.history({ + channel: 'YOUR_CHANNEL_ID', // Replace with the channel ID you want to poll + limit: 10, + }); + + for (const message of result.messages) { + if (message.text.includes('<@YOUR_BOT_USER_ID>')) { // Replace with your bot's user ID + // Send message text to ChatGPT for a response + const chatGptResponse = await axios.post( + 'https://api.openai.com/v1/completions', + { + model: 'text-davinci-003', + prompt: message.text, + max_tokens: 50, + }, + { + headers: { Authorization: `Bearer ${openAiKey}` }, + } + ); + + // Post ChatGPT's response back to Slack + await slackClient.chat.postMessage({ + channel: message.channel, + text: chatGptResponse.data.choices[0].text.trim(), + }); + } + } + } catch (error) { + console.error('Error running bot:', error); + } +})();