Ask ChatGPT from Slack command


Get Started

Not the template you're looking for? Browse more.

About the template


This integration allows to ask questions from ChatGPT via Slack slash command. Get started to learn more.

About ScriptRunner Connect


What is ScriptRunner Connect?

ScriptRunner Connect is an AI assisted code-first (JavaScript/TypeScript) integration platform (iPaaS) for building complex integrations and automations.

Can I try it out for free?

Yes. ScriptRunner Connect comes with a forever free tier.

Can I customize the integration logic?

Absolutely. The main value proposition of ScriptRunner Connect is that you'll get full access to the code that is powering the integration, which means you can make any changes to the the integration logic yourself.

Can I change the integration to communicate with additional apps?

Yes. Since ScriptRunner Connect specializes in enabling complex integrations, you can easily change the integration logic to connect to as many additional apps as you need, no limitations.

What if I don't feel comfortable making changes to the code?

First you can try out our AI assistant which can help you understand what the code does, and also help you make changes to the code. Alternatively you can hire our professionals to make the changes you need or build new integrations from scratch.

Do I have to host it myself?

No. ScriptRunner Connect is a fully managed SaaS (Software-as-a-Service) product.

What about security?

ScriptRunner Connect is ISO 27001 and SOC 2 certified. Learn more about our security.

Template Content


README

Scripts

TypeScriptOnSlackSlashCommand
Slash Command

README


๐Ÿ“‹ Overview

This integration allows to ask questions from ChatGPT via Slack slash command.

๐Ÿ–Š๏ธ Setup

  • Configure API Connections and an Event Listener by creating connectors for Slack and our Generic Connector for OpenAI, or use existing ones.
  • To setup a Generic connector for OpenAI API, visit API keys page to create a new Secret key, copy generated API key and add a custom header for your Generic connector.
  • Go to Parameters and configure the model version.
  • URL for your Generic connector: https://api.openai.com
    • Header name: Authorization
    • Header value: Bearer YOUR_OPENAI_API_KEY
  • (Optional) If you need to enable using a slash command inside direct messages with your Slack app, visit Slack apps page, select your app and then click Add features and functionality -> Bots -> Show Tabs, enable Messages Tab and check Allow users to send Slash commands

๐Ÿš€ Usage

  • Add your slack Slack app to a channel under the 'Integrations' tab in channel's options.
  • In the channel send a message to AI using your slash command: /your-slash-command <message to AI>. You will recieve a response to your Direct Messages to keep your conversations with AI private.
  • This template utilises continuous conversation with AI by storing the conversation in the Record Storage.
  • You can clear the context and start a new chat by sending "NEW CHAT" message, for example /your-command NEW CHAT. This feature will delete the context only for the Slack user who sent this message.

API Connections


TypeScriptOnSlackSlashCommand

import { SlashCommandEvent } from '@sr-connect/slack/events';
import OpenAI from "./api/generic";
import Slack from "./api/slack";
import { RecordStorage } from '@sr-connect/record-storage';

export default async function (event: SlashCommandEvent, context: Context): Promise<void> {
    if (context.triggerType === 'MANUAL') {
        console.error('This script is designed to be triggered externally or manually from the Event Listener. Please consider using Event Listener Test Event Payload if you need to trigger this script manually.');
        return;
    }

    const MODEL_VERSION = context.environment.vars.MODEL_VERSION;
    
    const storedMessagesContextCache: Message[] = [];
    const userId = event.user_id;
    const prompt = event.text;
    const storage = new RecordStorage();
    const storedValues = await storage.getValue<Message[]>(userId);

    // Check if prompt was added by the user
    if (prompt) {
        // Check if the slash command contains actual prompt or a request to start a new chat 
        if (prompt === 'NEW CHAT') {
            await storage.deleteValue(userId);
            await Slack.Chat.postMessage({
                body: {
                    channel: userId,
                    text: 'Previous context cleared.'
                }
            });
            return;
        } else {
            // If a question was asked, echo it back to Slack
            await Slack.Chat.postMessage({
                body: {
                    channel: userId,
                    text: `*You asked:* ${prompt}`
                }
            });
        }
    } else {
        // If not, then send appropriate reply
        await Slack.Chat.postMessage({
            body: {
                channel: userId,
                text: `No message. Please type your prompt after command: *${event.command} <your message>*.`
            }
        });
        return;
    }

    const userMessage = { role: "user", content: prompt };

    if (!storedValues) {
        storedMessagesContextCache.push(userMessage);
    } else {
        storedMessagesContextCache.push(...storedValues, userMessage)
    }

    try {
        // Send a request to OpenAI
        const response = await OpenAI.fetch('/v1/chat/completions', {
            method: 'POST',
            body: JSON.stringify({
                model: MODEL_VERSION,
                messages: storedMessagesContextCache,
            })
        });

        // Check if the response is OK
        if (!response.ok) {
            // If not, then throw an error
            throw new Error(`Invalid response while getting GPT response: ${response.status}`)
        }

        // Extract the response message
        const responseMessage = await response.json<OpenAIResponse>();

        // Check if the message contains an error
        if (responseMessage.error) {
            // If so, then throw an error
            throw new Error(responseMessage.error.message);
        }

        // Store the reply in record storage
        await storage.setValue(userId, [...storedMessagesContextCache, ...responseMessage.choices.map(ch => ch.message)]);

        // Extract the message
        const messageOutput = responseMessage.choices.map(ch => ch.message.content).join(' ');

        // Finally reply to the user in Slack
        await Slack.Chat.postMessage({
            body: {
                channel: userId,
                text: messageOutput
            }
        });
    } catch (e) {
        // If something went wrong, then log it out
        console.log('Something when wrong while processing AI request', e);

        // And reply to user
        await Slack.Chat.postMessage({
            body: {
                channel: userId,
                text: `Something went wrong while processing your prompt: ${prompt}`,
            }
        });
    }
}

interface OpenAIResponse {
    choices: {
        message: Message;
    }[];
    error?: {
        message: string;
    }
}

interface Message {
    role: string;
    content: string;
}
Documentation ยท Support ยท Suggestions & feature requests