> ## 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.

# 如何托管 Discord 机器人

> 了解如何在 Square Cloud 上创建并托管 Discord 机器人。完整教程涵盖配置、部署以及 Node.js 和 Python 的实践示例。

export const RecommendedPlan = ({lang, plan, tier, cpu, appType}) => {
  const url = `https://squarecloud.app/${lang}/pay?plan=${plan.toLowerCase()}&tier=${tier}`;
  if (lang == 'en') {
    return <Note>
        <b>Wondering how much RAM and CPU your plan needs to host {appType}?</b><br />
        Don't worry, we're here to help.
        Our <a href={url}>{plan}</a> plan offers <b>{tier}GB</b> of RAM and <b>{cpu}vCPU</b>, which should be sufficient for most {appType}. 
        However, if you are working on a larger project and seeking extra stability, we recommend considering our <b>Pro</b> plan. With additional resources, you can maintain stability even during demand spikes. 
        To purchase, simply click <a href="https://squarecloud.app/en/pay?plan=pro">here</a>.
      </Note>;
  } else {
    return <Note>
          <b>Está se perguntando quanta RAM e CPU seu plano precisa para hospedar {appType}?</b><br />
          Não se preocupe, estamos aqui para ajudar.
          Nosso plano <a href={url}>{plan}</a> oferece <b>{tier}GB</b> de RAM e <b>{cpu}vCPU</b>, o que deve ser suficiente para a maioria dos {appType}.
          No entanto, se você estiver trabalhando em um projeto maior e precisar de mais estabilidade, recomendamos considerar nosso plano <b>Pro</b>.
          Com recursos adicionais, você pode manter a estabilidade mesmo durante picos de demanda.
          Para comprar, basta clicar <a href={`https://squarecloud.app/${lang}/pay?plan=pro`}>aqui</a>.
        </Note>;
  }
};

export const appType_0 = "a Discord bot"

## 简介

要在 Square Cloud 上开发和托管 {appType_0}，遵循一套结构化的配置和前置条件流程至关重要。本技术指南将涵盖整个过程，从初始设置到生产环境部署。

### 前置条件

* **Square Cloud 账户**：通过[注册页面](https://squarecloud.app/zh/signup)使用你的邮箱进行注册。
* **有效的付费套餐**：为你的应用提供专属资源和优化的性能。查看我们[可用的套餐](https://squarecloud.app/zh/pricing)，选择最适合你需求的方案。

<RecommendedPlan appType="Discord bots" plan="Hobby" tier="2" cpu="2" lang="en" />

## 创建项目

要创建 Discord 机器人，拥有一个 Discord 账户对于在平台上创建和管理机器人至关重要。如果你还没有账户，请访问 [Discord 官方网站](https://discord.com/) 创建你的账户。

### 在 Discord 上创建机器人应用

<Steps>
  <Step title="创建应用" icon="rocket" iconType="solid">
    访问 [开发者门户](https://discord.com/developers/applications) 并点击 "New Application"。为你的机器人指定一个名称，然后点击 "Create" 创建应用。

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/discord/create-an-application.webp" alt="在开发者门户中创建 Discord 应用" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Step>

  <Step title="生成身份验证令牌" icon="key" iconType="solid">
    创建应用后，导航到 "Bot" 选项卡并点击 "Reset Token" 以生成身份验证令牌。复制生成的令牌，以便稍后在代码实现中使用。

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/discord/generating-token.webp" alt="生成 Discord 机器人身份验证令牌" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Step>

  <Step title="启用特权 Intents" icon="message" iconType="solid">
    配置好令牌后，启用所需的 intents。停留在 "Bot" 选项卡，向下滚动并找到 "Privileged Gateway Intents"。按照图中所示启用这些 intents：

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/discord/intent.webp" alt="启用 Discord 特权网关 intents" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Step>
</Steps>

<Warning>
  **关键安全提示**：请对你的机器人令牌绝对保密。此令牌授予对机器人的完全控制权，应当作为机密信息对待。
</Warning>

### 开发项目

现在我们有了机器人令牌，就可以开始编写代码了。你可以使用你喜欢的语言来实现。

<Tabs>
  <Tab title="Discord.js (Node.js)">
    **Node.js 环境搭建**

    1. 确认系统中已安装 Node.js。如果没有，请从 [Node.js 官方网站](https://nodejs.org/) 下载。

    2. 初始化一个新的 Node.js 项目：

    ```bash Terminal theme={null}
    npm init -y
    ```

    3. 安装 Discord.js 库：

    ```bash Terminal theme={null}
    npm install discord.js
    ```

    4. 创建一个 JavaScript 文件（例如 `index.js`），并添加以下代码来创建一个基础的 Discord 机器人：

    ```javascript index.js theme={null}
    const { Client, GatewayIntentBits } = require("discord.js");

    const client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
      ],
    });

    client.on("ready", () => {
      console.log(`${client.user.tag}!`);
    });

    client.on("messageCreate", (message) => {
      if (message.content === "!hello") {
        message.reply("Hello!");
      }
    });

    client.login("your token here");
    ```
  </Tab>

  <Tab title="Discord.py (Python)">
    **Python 环境搭建**

    1. 确认系统中已安装 Python。如果没有，请从 [Python 官方网站](https://www.python.org/) 下载。

    2. 使用 pip 安装 discord.py 库：

    ```bash Terminal theme={null}
    pip install discord.py
    ```

    3. 创建一个 Python 文件（例如 `main.py`），并添加以下代码来创建一个基础的 Discord 机器人：

    ```python main.py theme={null}
    import discord
    from discord.ext import commands

    intents = discord.Intents.default()
    intents.message_content = True

    client = commands.Bot(command_prefix='!', intents=intents)

    @client.event
    async def on_ready():
        print(f'{client.user}')

    @client.command()
    async def hello(ctx):
        await ctx.reply('Hello!')

    client.run('your token here')
    ```

    4. 创建一个 `requirements.txt` 文件，列出项目所需的所有外部库：

    ```txt requirements.txt theme={null}
    discord.py
    ```
  </Tab>
</Tabs>

## 部署

准备好项目文件后，你现在可以将它们上传到 Square Cloud 并托管你的项目。
为此，请创建一个包含所有项目文件的 ZIP 文件。

### 通过控制面板

<Steps>
  <Step title="访问上传页面">
    访问[上传页面](https://squarecloud.app/zh/dashboard/new)并上传你的项目 zip 文件。
  </Step>

  <Step title="配置你的环境">
    上传 zip 后，你需要为项目配置名称、主文件或运行时环境以及其他设置。\
    如果你上传的是 Web 项目，请务必选择 "Web Publication" 并为项目设置子域名。
  </Step>

  <Step title="部署你的项目">
    最后，点击 "Deploy" 按钮，即可将项目托管到 Square Cloud。\
    部署完成后，你可以在控制面板中监控项目的状态和日志。

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/dashboard/uploading.gif" alt="正在上传应用到 Square Cloud" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Step>
</Steps>

### 通过 CLI

要使用此方法，你需要在项目根目录中创建一个名为 `squarecloud.app` 的配置文件。该文件将包含项目所需的配置。

<Card title="了解更多：如何为 Square Cloud 创建配置文件。" icon="link" href="/zh/getting-started/config-file">
  squarecloud.app 文件是一个配置文件，用于配置你的应用；它将用于定义你的环境。
</Card>

<Steps>
  <Step title="安装 CLI">
    首先，你的环境中需要已安装 CLI。如果尚未安装，请在终端中运行以下命令：

    ```
    npm install -g @squarecloud/cli
    ```

    如果你已经安装，我们建议对其进行更新。为此，请在终端中运行以下命令：

    <Tabs>
      <Tab title="Windows">
        ```bash theme={null}
        squarecloud update
        ```
      </Tab>

      <Tab title="Linux、macOS 和 WSL">
        ```bash theme={null}
        curl -fsSL https://cli.squarecloud.app/install | bash
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="进行身份验证">
    现在，要进行身份验证并使用其他 CLI 命令，你可以在[此处](https://squarecloud.app/zh/account/security)点击 "Request API Key" 找到你的授权密钥。获取授权密钥后，运行以下命令：

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

  <Step title="上传你的项目">
    最后，要使用 CLI 将应用部署到 Square Cloud，你需要运行以下命令：

    ```bash theme={null}
    squarecloud upload 
    ```

    或者，如果你手动创建了 zip 文件，可以使用：

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

## 测试机器人

如果你正确地完成了所有步骤，下一步就是邀请你的机器人进行测试。为此，请按照以下步骤操作：

1. 访问 [开发者门户](https://discord.com/developers/applications)。
2. 选择你的机器人。
3. 导航到 "OAuth2" 选项卡。
4. 进入 "OAuth2 URL Generator"。
5. 勾选 "bot" 选项。
6. 选择使用此邀请链接邀请机器人时它将拥有的权限。
7. 在权限下方，会生成一个机器人的邀请链接。它应该类似于这样：

```txt theme={null}
https://discord.com/oauth2/authorize?client_id=00000000000000&permissions=8&scope=bot
```

请记住，URL 中的 `client_id` 应替换为你机器人的实际 ID。`permissions` 值可能也需要根据你希望机器人拥有的权限进行调整。

现在，要测试是否一切正常，请在你的服务器上执行以下命令：`!hello`。

<Frame>
  <img src="https://cdn.squarecloud.app/docs/articles/discord/testing-bot.gif" alt="部署后测试 Discord 机器人" style={{ borderRadius: "0.2rem" }} />
</Frame>

## 更多资源

有关使用 discord.py 和 discord.js 创建机器人的更多信息，请访问 [discord.py 官方文档](https://discordpy.readthedocs.io/en/latest/) 和 [discord.js 官方指南](https://discordjs.guide/)。在那里，你会找到详细的指南、教程和 API 文档，帮助你充分利用这些库。

## 联系我们

如果你仍然遇到**技术问题**，我们的**专业支持团队**可以为你提供帮助。[**联系我们**](https://squarecloud.app/zh/support)，我们很乐意协助你解决任何问题。
