> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Host a Slack Bot

> Host a Slack bot on Square Cloud with Bolt for JavaScript or Python: create the tokens, run it in Socket Mode with no public URL, deploy and test it.

export const RecommendedPlan = ({lang, plan, tier, cpu, appType, min}) => {
  const t = {
    'en': {
      q: <>Which plan should you choose for {appType}?</>,
      rec: p => <>We recommend the {p} plan: its <b>{tier} GB</b> of RAM and <b>{cpu} vCPU</b> handle most projects of this kind, with headroom for traffic spikes.</>,
      min: m => <> Lighter projects also run on the {m} plan.</>,
      pro: p => <> For larger projects, the {p} plan adds more RAM and CPU.</>
    },
    'pt-br': {
      q: <>Qual plano escolher para {appType}?</>,
      rec: p => <>Recomendamos o plano {p}: seus <b>{tier} GB</b> de RAM e <b>{cpu} vCPU</b> atendem a maioria dos projetos desse tipo, com folga para picos de tráfego.</>,
      min: m => <> Projetos mais leves também rodam no plano {m}.</>,
      pro: p => <> Para projetos maiores, o plano {p} oferece mais RAM e CPU.</>
    },
    'es': {
      q: <>¿Qué plan elegir para {appType}?</>,
      rec: p => <>Te recomendamos el plan {p}: sus <b>{tier} GB</b> de RAM y <b>{cpu} vCPU</b> cubren la mayoría de los proyectos de este tipo, con margen para picos de tráfico.</>,
      min: m => <> Los proyectos más ligeros también funcionan en el plan {m}.</>,
      pro: p => <> Para proyectos más grandes, el plan {p} ofrece más RAM y CPU.</>
    },
    'fr': {
      q: <>Quel plan choisir pour héberger {appType} ?</>,
      rec: p => <>Nous recommandons le plan {p} : ses <b>{tier} Go</b> de RAM et <b>{cpu} vCPU</b> suffisent pour la plupart des projets de ce type, avec une marge pour les pics de trafic.</>,
      min: m => <> Les projets plus légers fonctionnent aussi avec le plan {m}.</>,
      pro: p => <> Pour les projets plus importants, le plan {p} offre davantage de RAM et de CPU.</>
    },
    'de': {
      q: <>Welcher Plan eignet sich für {appType}?</>,
      rec: p => <>Wir empfehlen den {p}-Plan: <b>{tier} GB</b> RAM und <b>{cpu} vCPU</b> reichen für die meisten Projekte dieser Art, mit Reserven für Lastspitzen.</>,
      min: m => <> Kleinere Projekte laufen auch mit dem {m}-Plan.</>,
      pro: p => <> Für größere Projekte bietet der {p}-Plan mehr RAM und CPU.</>
    },
    'it': {
      q: <>Quale piano scegliere per {appType}?</>,
      rec: p => <>Ti consigliamo il piano {p}: i suoi <b>{tier}GB</b> di RAM e <b>{cpu}vCPU</b> bastano per la maggior parte dei progetti di questo tipo, con margine per i picchi di traffico.</>,
      min: m => <> I progetti più leggeri funzionano anche con il piano {m}.</>,
      pro: p => <> Per progetti più grandi, il piano {p} offre più RAM e CPU.</>
    },
    'ja': {
      q: <>{appType}にはどのプランを選べばよいですか？</>,
      rec: p => <>{p}プランをおすすめします。<b>{tier}GB</b>のRAMと<b>{cpu}vCPU</b>があれば、この種のプロジェクトの多くをトラフィックのピークにも余裕を持って動かせます。</>,
      min: m => <>軽量なプロジェクトは{m}プランでも動作します。</>,
      pro: p => <>より大規模なプロジェクトには、RAMとCPUが増える{p}プランをご検討ください。</>
    },
    'zh': {
      q: <>托管{appType}应该选择哪个套餐？</>,
      rec: p => <>我们推荐 {p} 套餐：<b>{tier}GB</b> RAM 和 <b>{cpu}vCPU</b> 足以运行大多数此类项目，并能从容应对流量高峰。</>,
      min: m => <>较轻量的项目也可以在 {m} 套餐上运行。</>,
      pro: p => <>对于更大的项目，{p} 套餐提供更多 RAM 和 CPU。</>
    }
  };
  const siteLang = t[lang] ? lang : 'en';
  const c = t[siteLang];
  const pay = (name, query) => <a href={`https://squarecloud.app/${siteLang}/pay?${query}`}>{name}</a>;
  const isPro = plan.toLowerCase() === 'pro';
  return <Note>
      <b>{c.q}</b><br />
      {c.rec(pay(plan, `plan=${plan.toLowerCase()}&tier=${tier}`))}
      {min ? c.min(pay(min, `plan=${min.toLowerCase()}`)) : null}
      {isPro ? null : c.pro(pay('Pro', 'plan=pro'))}
    </Note>;
};

export const appType_0 = "a Slack bot"

## Introduction

To develop and host {appType_0} on Square Cloud, it's essential to follow a structured sequence of configurations and prerequisites. This technical guide will cover the entire process, from initial setup to production deployment.

### Prerequisites

* **Square Cloud Account**: Register through the [signup page](https://squarecloud.app/en/signup) using your email.
* **Active plan**: Ensures dedicated resources and optimized performance for your application. Check our [available plans](https://squarecloud.app/en/pricing) and choose the most suitable for your needs.

<RecommendedPlan appType="Slack bots" plan="Standard" tier="4" cpu="4" min="Hobby" lang="en" />

This guide runs on the [Node.js runtime](/en/articles/getting-started-with-nodejs) or the [Python runtime](/en/articles/getting-started-with-python).

## Create the project

To create a Slack bot, you will need an account and permissions to create apps on Slack. Create or access your account on [Slack](https://slack.com/) before following the next steps.

### Bot application on Slack

1. Go to the [Slack API - Your Apps](https://api.slack.com/apps) and click "Create New App".
2. Choose "From scratch", give the app a name and select the workspace where you will install it.
3. In the "Socket Mode" section, enable Socket Mode and generate an *app-level token* with the `connections:write` scope. Copy it (it starts with `xapp-`): this is your `SLACK_APP_TOKEN`.
4. In the "OAuth & Permissions" section, add the scopes your bot needs (e.g. `chat:write`, `app_mentions:read`, `commands`), install the app to your workspace and copy the *Bot User OAuth Token* (it starts with `xoxb-`): this is your `SLACK_BOT_TOKEN`.
5. In "Event Subscriptions", enable events and subscribe to the `app_mention` bot event. In "Slash Commands", create the `/hello` command. With Socket Mode enabled, neither asks for a Request URL.

<Warning>**Security:** Never expose the app-level token or the Bot Token publicly. Treat them as sensitive credentials: the examples below read them from environment variables, never from your code.</Warning>

With Socket Mode, the bot opens the connection to Slack itself, so it runs like any other bot: no public URL or port is needed. If you prefer Slack to send events over HTTP, see [Use HTTP mode instead of Socket Mode](#use-http-mode-instead-of-socket-mode).

## Develop the bot

Use the tab for the language you choose. Both examples reply to mentions and to the `/hello` slash command.

<Tabs>
  <Tab title="Node.js - @slack/bolt">
    1. Make sure Node.js is installed.
    2. Initialize a project and install dependencies:

    ```bash Terminal theme={"system"}
    npm init -y
    npm install @slack/bolt
    ```

    3. Create an `index.js` file with the following content:

    ```javascript index.js theme={"system"}
    const { App } = require('@slack/bolt');

    const app = new App({
      token: process.env.SLACK_BOT_TOKEN,
      appToken: process.env.SLACK_APP_TOKEN,
      // Socket Mode: the bot connects to Slack, so no public URL is needed
      socketMode: true,
    });

    // Responds when mentioned
    app.event('app_mention', async ({ event, say }) => {
      await say(`<@${event.user}> Thanks for mentioning me!`);
    });

    // Example slash command
    app.command('/hello', async ({ ack, respond }) => {
      await ack();
      await respond('Hello from Square Cloud!');
    });

    (async () => {
      await app.start();
      console.log('⚡️ Slack Bolt app is running!');
    })();
    ```
  </Tab>

  <Tab title="Python - slack_bolt">
    1. Make sure Python and pip are installed.
    2. Install the Bolt for Python library:

    ```bash Terminal theme={"system"}
    pip install slack_bolt
    ```

    3. Create an `app.py` file with the following content:

    ```python app.py theme={"system"}
    import os

    from slack_bolt import App
    from slack_bolt.adapter.socket_mode import SocketModeHandler

    app = App(token=os.environ.get('SLACK_BOT_TOKEN'))

    @app.event('app_mention')
    def handle_mention(event, say):
        user = event.get('user')
        say(f'<@{user}> Thanks for mentioning me!')

    @app.command('/hello')
    def hello_command(ack, respond):
        ack()
        respond('Hello from Square Cloud!')

    if __name__ == '__main__':
        # Socket Mode: the bot connects to Slack, so no public URL is needed
        SocketModeHandler(app, os.environ.get('SLACK_APP_TOKEN')).start()
    ```

    4. For Python projects, include a `requirements.txt` with:

    ```txt requirements.txt theme={"system"}
    slack_bolt
    ```
  </Tab>
</Tabs>

## Configure Square Cloud

Create a `squarecloud.app` file at the root of your project, next to your main file. It tells Square Cloud how to run your bot:

<CodeGroup>
  ```systemd Node.js theme={"system"}
  DISPLAY_NAME=My Slack Bot
  MAIN=index.js
  MEMORY=512
  VERSION=recommended
  AUTORESTART=true
  ```

  ```systemd Python theme={"system"}
  DISPLAY_NAME=My Slack Bot
  MAIN=app.py
  MEMORY=512
  VERSION=recommended
  AUTORESTART=true
  ```
</CodeGroup>

* `MAIN` is the file Square Cloud runs, and `MEMORY` is the bot's RAM in MB. Bots need at least 256 MB; 512 MB leaves room to grow.
* `AUTORESTART=true` starts the bot again if it crashes. See [how auto restart works](https://help.squarecloud.app/en-us/article/how-to-use-auto-restart-on-square-cloud-nmhvh0/).
* There is no `SUBDOMAIN`: in Socket Mode, the bot needs no public URL.

See the [configuration file reference](/en/getting-started/config-file) for every field.

## Set the tokens

Your code reads both tokens from the `SLACK_BOT_TOKEN` and `SLACK_APP_TOKEN` environment variables, so they never go into your files. Set them in one of these ways:

* **Dashboard**: on the upload page, open **Advanced configuration** and add both variables. For a bot that is already deployed, add them on the application's **Environment Variables** page and restart the bot.
* **CLI**: right after you upload the bot (see [Deploy and verify](#deploy-and-verify)), set them with [`squarecloud app env set`](/en/cli-reference/environment-variables#squarecloud-app-env-set) and restart the bot:

```bash theme={"system"}
squarecloud app env set SLACK_BOT_TOKEN=xoxb-your-token SLACK_APP_TOKEN=xapp-your-token
squarecloud app restart
```

The bot reads its environment variables when it starts, so restart it after every change. See [Environment variables](/en/platform/environment-variables) for the other ways to manage them.

## What goes in the ZIP

* Your main file (`index.js` or `app.py`) and your other source files.
* `package.json` or `requirements.txt`.
* `squarecloud.app`.

Leave out `node_modules`, `.venv` and `__pycache__`: Square Cloud installs your dependencies when the bot starts.

## Deploy and verify

Create the ZIP described above, then upload it:

### Via dashboard

<Steps>
  <Step title="Access the Upload Page">
    Access the [upload page](https://squarecloud.app/en/dashboard/new) and upload your project zip file.
  </Step>

  <Step title="Configure Your Environment">
    After uploading your zip, you will need to configure the name, main file or runtime environment and other settings for your project.\
    If you are uploading a web project, make sure to select "Web Publication" and set a subdomain to your project.
  </Step>

  <Step title="Deploy Your Project">
    Finally, click on the "Deploy" button to host your project on Square Cloud.\
    After deployment, you can monitor your project's status and logs from the dashboard.

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/dashboard/uploading.gif" alt="Uploading application to Square Cloud" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Step>

  <Step title="Confirm Your App Is Live">
    Your first deploy usually takes less than a minute. In the [dashboard](https://squarecloud.app/en/dashboard), wait for your application status to show as running and check the logs for any startup errors.\
    If you deployed a website or API, open `https://<your-subdomain>.squareweb.app` in your browser: you should see your application responding. If you deployed a bot, send it a command to confirm it is online.
    <Tip>App not starting? See the [Troubleshooting guide](/en/platform/troubleshooting/app-wont-start) for the most common causes and fixes.</Tip>
  </Step>
</Steps>

### Via CLI

To use this method, your project needs a configuration file named `squarecloud.app` at its root. It tells Square Cloud how to run your application.

<Card title="Configuration file guide" icon="link" href="/en/getting-started/config-file">
  Learn how to create the `squarecloud.app` configuration file that defines your application's environment.
</Card>

<Steps>
  <Step title="Install the CLI">
    Install the [Square Cloud CLI](/en/cli-reference/installation). If you already have it, run the same command to update it:

    <CodeGroup>
      ```bash macOS, Linux, and WSL theme={"system"}
      curl -fsSL https://cli.squarecloud.app/install | bash
      ```

      ```bash Windows with npm theme={"system"}
      npm install -g @squarecloud/cli@latest
      ```
    </CodeGroup>
  </Step>

  <Step title="Log In">
    Run the command below. It opens your browser: approve the login there and the CLI is ready. There is no API key to copy. For scripts and CI, see [CLI authentication](/en/cli-reference/authentication).

    ```bash theme={"system"}
    squarecloud auth login
    ```
  </Step>

  <Step title="Upload Your Project">
    From your project folder, run the command below. The CLI zips the current folder, leaving out what [`squarecloud.ignore`](/en/getting-started/squarecloud-ignore) lists, and uploads it:

    ```bash theme={"system"}
    squarecloud upload
    ```

    To upload a zip you created yourself, pass it with `--file`:

    ```bash theme={"system"}
    squarecloud upload --file <path/to/zip>
    ```
  </Step>

  <Step title="Confirm Your App Is Live">
    Your first deploy usually takes less than a minute. Check your application status and logs directly from the terminal:

    ```bash theme={"system"}
    squarecloud app status
    squarecloud app logs
    ```

    If you deployed a website or API, open `https://<your-subdomain>.squareweb.app` in your browser: you should see your application responding. If you deployed a bot, send it a command to confirm it is online.
    <Tip>App not starting? See the [Troubleshooting guide](/en/platform/troubleshooting/app-wont-start) for the most common causes and fixes.</Tip>
  </Step>
</Steps>

### Test the bot

1. In the Slack app settings, under "OAuth & Permissions", install the app to the workspace (if you haven't already).
2. Check the application logs in the Square Cloud dashboard for startup errors. With Socket Mode there is no Request URL to configure: the bot connects to Slack as soon as it starts.
3. Invite the bot to a channel, then mention it or run the `/hello` command to validate responses.

Example install link (replace the client\_id):

```txt theme={"system"}
https://slack.com/oauth/v2/authorize?client_id=000000000000.000000000000&scope=commands,chat:write,app_mentions:read
```

## Common errors

### You must provide an appToken when socketMode is set to true

Bolt for JavaScript stops at startup with this message when `SLACK_APP_TOKEN` is not set. Set the app-level token (the one that starts with `xapp-`) and restart the bot.

### Either an env variable `SLACK_BOT_TOKEN` or `token` argument in the constructor is required

Bolt for Python stops at startup with this message when `SLACK_BOT_TOKEN` is not set. Set the Bot User OAuth Token (the one that starts with `xoxb-`) and restart the bot.

### The bot doesn't answer mentions

Check that the bot is a member of the channel, that "Event Subscriptions" subscribes to the `app_mention` bot event, and that you reinstalled the app after adding scopes.

## Use HTTP mode instead of Socket Mode

Apps that use Socket Mode can't be listed in the public Slack Marketplace. If you need Slack to send events over HTTP instead, run the bot as a web application:

1. In the Slack app settings, disable Socket Mode and copy the *Signing Secret* (under "Basic Information") into a `SLACK_SIGNING_SECRET` environment variable, set the same way as the tokens.
2. Create the app with the signing secret instead of the app-level token, and listen on the port in the `PORT` environment variable:

<CodeGroup>
  ```javascript index.js theme={"system"}
  const app = new App({
    token: process.env.SLACK_BOT_TOKEN,
    signingSecret: process.env.SLACK_SIGNING_SECRET,
  });

  (async () => {
    // Square Cloud sets PORT=80
    await app.start(Number(process.env.PORT) || 80);
    console.log('⚡️ Slack Bolt app is running!');
  })();
  ```

  ```python app.py theme={"system"}
  app = App(
      token=os.environ.get('SLACK_BOT_TOKEN'),
      signing_secret=os.environ.get('SLACK_SIGNING_SECRET')
  )

  if __name__ == '__main__':
      # Square Cloud sets PORT=80
      app.start(port=int(os.environ.get('PORT', 80)))
  ```
</CodeGroup>

Both servers listen on all network interfaces (`0.0.0.0`), which Square Cloud requires.

3. Add a `SUBDOMAIN` to your configuration file (or select "Web Publication" and set a subdomain when uploading from the dashboard) so the bot gets a public URL. Web applications need at least `MEMORY=512`:

```systemd squarecloud.app theme={"system"}
DISPLAY_NAME=My Slack Bot
MAIN=index.js
MEMORY=512
VERSION=recommended
AUTORESTART=true
SUBDOMAIN=my-slack-bot
```

<Note>An application uploaded without a subdomain can't get one later. If your bot already runs in Socket Mode, upload the HTTP version as a new application.</Note>

4. In "Event Subscriptions" and in the `/hello` slash command, set the Request URL to `https://<subdomain>.squareweb.app/slack/events`.

## Next steps

<CardGroup cols={3}>
  <Card title="App won't start" icon="triangle-exclamation" href="/en/platform/troubleshooting/app-wont-start">
    Fix missing modules, memory errors and other startup failures.
  </Card>

  <Card title="Environment variables" icon="key" href="/en/platform/environment-variables">
    Manage your bot's tokens and other secrets.
  </Card>

  <Card title="Discord bot" icon="discord" href="/en/tutorials/bots/discord">
    Host a Discord bot next to your Slack bot.
  </Card>
</CardGroup>

For more about Bolt, see the official Slack documentation for [Bolt for JavaScript](https://docs.slack.dev/tools/bolt-js/) and [Bolt for Python](https://docs.slack.dev/tools/bolt-python/).

## Contact us

If you continue facing **technical difficulties**, our **specialized support team** is available to assist you. [**Contact us**](https://squarecloud.app/en/support) and we'll be happy to help you resolve any issue: support quality is a big part of why developers rate Square Cloud [**4.9/5 across 402 reviews**](https://www.trustpilot.com/review/squarecloud.app) on Google and Trustpilot.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.