Romolo  Morelli

Romolo Morelli

1677170040

Costruire un Discord Chat Bot in Rust

Scopri come costruire un robot Discord in Rust con Shuttle e Serenity. Scopri come creare un bot in Discord, aggiungere il bot al tuo server e connettere il tuo codice Rust al tuo bot.

I robot Discord possono far risparmiare molto tempo e fatica ai proprietari di server e ai membri dello staff, fornendo allo stesso tempo una varietà di funzioni utili agli utenti. Puoi utilizzare i robot in Discord per automatizzare attività ripetitive e attività che altrimenti richiederebbero molto tempo e fatica.

In questo articolo imparerai come creare un bot in Discord, aggiungere il bot al tuo server e connettere il tuo codice Rust al tuo bot.

Sommario:

  • Configurazione del robot Discord
    • Creazione di un'applicazione in Discord
    • Creazione di un bot per l'applicazione
    • Installazione del bot sul tuo server Discord
  • Configurazione dell'ambiente del codice Rust
  • Collegamento della base di codice di Rust al tuo bot Discord
  • Creazione di comandi per il bot Discord
    • Abilitazione della modalità sviluppatore sul tuo account Discord
    • Consentire al tuo bot di rispondere a un comando
  • Distribuzione del bot Discord sul server Shuttle

Per seguire questo articolo, è necessario almeno un certo livello di familiarità con Discord. Dovresti anche avere un account Discord, un server Discord di tua proprietà e una certa esperienza di programmazione con Rust.


Configurazione del robot Discord

Configurare il bot in Discord può essere un po' complicato, specialmente se è la prima volta che lo fai. In questa sezione, ti guiderò attraverso la configurazione del bot per il tuo server.

Creazione di un'applicazione in Discord

A Discord application is a service that provides an interface between Discord users and your code. The interface that the application provides is called a bot. A bot receives messages from users and sends a response.

To create a Discord application, first log in to your Discord account in your browser. Next, open the Discord developer portal in your browser and click the button labeled “New Application” at the top right of the page:

Portale per sviluppatori Discord in modalità oscura con pulsante blu per creare una nuova applicazione in alto a destra

Enter a name for your application:

Richiedi di inserire il nome per l'applicazione o verifica con il supporto degli sviluppatori per vedere se l'app esiste già

Click the button labeled “Create” to create the application. If the action completes successfully, you’ll be greeted with a dashboard that looks like this:

Pannello di controllo dell'applicazione Discord

Creating a bot for the application

In this section, you’ll create the bot for your Discord application. On the left pane of the webpage, click “Bot” to open the bot menu:

Voce di menu Bot evidenziata in blu nell'elenco delle impostazioni

Nella sezione "Build-A-Bot", fai clic sul pulsante "Aggiungi bot" per creare il bot:

Discord Crea una sezione Bot con il pulsante blu per aggiungere Bot in alto a destra

Dopo aver fatto clic su questo pulsante, avrai creato con successo il Discord bot. Per finire, attiva l'opzione "INTENTO DEL CONTENUTO DEL MESSAGGIO" in modo che il bot possa ricevere messaggi dagli utenti nel tuo server Discord:

Opzione Intento contenuto messaggio attivata per consentire a Discord Bot di ricevere messaggi dagli utenti

Installazione del bot sul tuo server Discord

L'ultima cosa che devi fare per impostare il tuo bot è installarlo sul tuo server. Nel riquadro di navigazione a sinistra, fai clic sulla voce di menu "OAuth2" per attivare o disattivare un menu a discesa. In questo menu a discesa, fai clic sull'opzione "Generatore URL":

Voce di menu Oauth2 evidenziata con l'opzione di sottomenu del generatore di URL delineata con scatola blu più chiara

Nel menu del generatore di URL sotto "AMBITI", seleziona l'opzione "bot":

Menu del generatore di URL con caselle di controllo per vari elementi in ambiti con l'opzione Bot selezionata

Scorri più in basso nella pagina fino a "PERMESSI BOT" e seleziona l'opzione "Amministratore" per concedere i privilegi di amministratore del bot:

Sottomenu Autorizzazioni bot con voci aggiuntive della casella di controllo con l'opzione amministratore selezionata in Autorizzazioni generali

Scorri fino alla fine della pagina e copia l'URL generato in basso, quindi apri l'URL generato nel tuo browser:

Richiedi di selezionare la destinazione del server per l'installazione di Discord Bot e informazioni sulle autorizzazioni

In the webpage that opens after you navigate to the generated URL, select the server that you want to install the bot in. Click “Continue” to proceed.

On the next screen, click “Authorize.” The webpage will then prompt you to verify that you are human:

Schermata di conferma per l'aggiunta dell'applicazione al server Discord

When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.

Setting up the Rust code environment

In this section, I’ll guide you through setting up the Rust code environment for your Discord bot. The code environment will have the necessary code and packages for you to get started with building the bot.

To set up the project, we’ll use a tool called Shuttle. Shuttle lets you initialize, build, and deploy a variety of projects in Rust.

For this project, we’ll use Shuttle to initialize a Serenity project. Serenity is a framework for building Discord chat bots in Rust.

To initialize the Serenity project, create a new directory for where you want your project to be. Then, install Shuttle with the command below:

cargo install cargo-shuttle

Next, initialize a project in the directory:

cargo shuttle init --serenity

Finally, build the project:

cargo build

If you followed these steps correctly, you should see your directory filled with the necessary code for getting started.

Connecting the Rust codebase to your Discord bot

The src/lib.rs code — which we generated in the previous section — is a basic project that you can connect to your bot, which we will do step-by-step in this section.

Per connettere correttamente il tuo codice al tuo bot, devi prima ottenere il token del tuo bot. Un token bot è un riferimento al tuo bot. Ogni bot ha un riferimento univoco che puoi utilizzare per connettere una base di codice al tuo bot.

Per recuperare il tuo token bot, apri prima la dashboard per sviluppatori Discord. Fai clic su "Bot" nel riquadro di navigazione a sinistra. Quindi, fai clic sul pulsante "Ripristina token":

Costruisci una schermata Bot della dashboard per sviluppatori Discord con informazioni sull'applicazione e pulsante per reimpostare il token

Fare clic su "Copia" per copiare il token:

Crea una schermata Bot di Discord Dashboard per sviluppatori con token generato per connettere il codice Rust a Discord Bot

Per connettere la codebase al tuo bot, crea un Secrets.tomlfile nella directory principale del progetto. Scrivi quanto segue nel Secrets.tomlfile e sostituiscilo * bot_token *con il token del tuo bot:

DISCORD_TOKEN="* bot_token *"

Esegui il progetto con questo comando:

cargo shuttle run

Al termine di questi passaggi, dovresti vedere il tuo Discord bot online sul tuo server. Se digiti !hellosul server, il bot dovrebbe rispondere con world!.

Per capire come risponde il bot !hello, dai un'occhiata al gestore di eventi dalle righe 12-24 del src/lib.rsfile:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

Il gestore di eventi ha un messagemetodo che viene chiamato ogni volta che qualcuno invia un messaggio sul server. La messagefunzione ha un ifblocco che controlla se il nuovo messaggio dice !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

Se il messaggio corrisponde !hello, il programma invia il world!messaggio al server con questa istruzione:

msg.channel_id.say(&ctx.http, "world!").await

Puoi programmare il bot per rispondere a qualsiasi messaggio personalizzato con risposte personalizzate seguendo i passaggi precedenti.

Creazione di comandi per il bot Discord

I comandi sono un modo più diretto per interagire con un bot. A differenza dei messaggi, i comandi iniziano con una /barra, ad esempio /hello.

You can send commands in Discord the same way you send messages, but they are the preferred way of interacting with bots because you can easily tell what messages are commands and what messages are not.

To allow your bot to respond to commands, you’ll need the ID of the server in which you installed the bot. In order to get the server ID, you need to enable developer mode on your account first.

Enabling developer mode on your Discord account

Developer mode is a Discord setting that gives developers elevated privileges in a server. In this section, I’ll guide you through enabling developer mode on your system so you can copy your server ID and enable your bot to respond to commands.

On Windows or Mac

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Appearance” under “APP SETTINGS.”

In the appearance settings menu, click “Advanced” to open the advanced settings menu, where you can then toggle the “Developer Mode” option. Finally, right-click the server name and select “Copy ID” to copy the server ID.

On Linux

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Advanced” under “APP SETTINGS” to open the advanced settings menu, where you can then toggle the “Developer Mode” option.

Then, right-click the server name and select “Copy ID” to copy the server ID:

Impostazioni avanzate dell'app Discord abilitate in modalità sviluppatore con il menu del server aperto e l'opzione per copiare l'ID del server in fondo all'elenco

Enabling your bot to respond to a command

With the server ID ready, follow these steps to enable your bot to respond to a command. First, write the ready method below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Next, write the interaction_create handler below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

In the ready method of the event handler, replace * guild_id * on the third line with your server ID.

If your code is still running in the terminal, restart it. When you see your bot online on your server, send a /hello message. You should see a response from the bot saying hello in response.

As with message responses, you can program your bot to respond to any custom commands with custom responses by following the steps we covered above.

Deploying the Discord bot to the Shuttle server

Running your project on your system can have disadvantages. More complex bots may require large resources to run and serve every user.

Deploying your bot gives your bot the advantage of not using your computer’s resources to run. It also keeps your bot online, even if you’re not.

Shuttle ti consente di distribuire il tuo bot sul server Shuttle. Per distribuire il tuo bot, esegui questo comando nella directory del tuo progetto:

cargo shuttle deploy

Conclusione

Costruire un chatbot Discord in Rust può essere un compito impegnativo. Ma con le conoscenze e gli strumenti giusti, può essere fatto facilmente.

Con le istruzioni dettagliate fornite in questo articolo, chiunque abbia esperienza di programmazione in Rust e un account Discord può imparare a creare il proprio chat bot Discord. Se stai cercando alcuni robot Discord da costruire, ecco alcune idee:

  • Bot di benvenuto per dare il benvenuto a nuovi utenti su un server o un canale
  • Robot di gioco per giocare a trivia, quiz, tris e altri giochi
  • Robot multimediali che riproducono musica o consentono agli utenti di creare o selezionare video, immagini o GIF da condividere
  • Poll bot per aiutare gli utenti a creare e inviare sondaggi
  • Robot di utilità per automatizzare le funzioni del server come rispondere alle domande frequenti e altro ancora

Per ulteriori letture sui bot di Rust Discord, dai un'occhiata ad alcuni bot di esempio di Serenity Discord o alla documentazione di Serenity .

Fonte: https://blog.logrocket.com

#rust #discord #chatbot

Costruire un Discord Chat Bot in Rust
许 志强

许 志强

1677166392

用 Rust 構建一個 Discord 聊天機器人

了解如何使用 Shuttle 和 Serenity 在 Rust 中構建 Discord 機器人。了解如何在 Discord 中創建機器人,將機器人添加到您的服務器,並將您的 Rust 代碼連接到您的機器人。

Discord 機器人可以為服務器所有者和員工節省大量時間和精力,同時還可以為用戶提供各種有用的功能。您可以在 Discord 中使用機器人來自動執行重複性任務和任務,否則這些任務會佔用大量時間和精力。

在本文中,您將學習如何在 Discord 中創建機器人,將機器人添加到您的服務器,以及將您的 Rust 代碼連接到您的機器人。

目錄:

  • 設置 Discord 機器人
    • 在 Discord 中創建應用程序
    • 為應用程序創建機器人
    • 將機器人安裝到您的 Discord 服務器
  • 設置 Rust 代碼環境
  • 將 Rust 代碼庫連接到您的 Discord 機器人
  • 為 Discord 機器人創建命令
    • 在您的 Discord 帳戶上啟用開發者模式
    • 使您的機器人能夠響應命令
  • 將 Discord 機器人部署到 Shuttle 服務器

要閱讀本文,您至少需要對 Discord 有一定程度的熟悉。您還應該擁有一個 Discord 帳戶、您擁有的 Discord 服務器以及一些 Rust 編程經驗。


設置 Discord 機器人

在 Discord 中設置機器人可能有點棘手,尤其是如果這是您第一次這樣做的話。在本節中,我將指導您為您的服務器設置機器人。

在 Discord 中創建應用程序

Discord 應用程序是一種在 Discord 用戶和您的代碼之間提供接口的服務。應用程序提供的界面稱為機器人。機器人接收來自用戶的消息並發送響應。

要創建 Discord 應用程序,請首先在瀏覽器中登錄您的 Discord 帳戶。接下來,在瀏覽器中打開Discord 開發人員門戶,然後單擊頁面右上角標有“新建應用程序”的按鈕:

Discord 開發者門戶在暗模式下帶有藍色按鈕以在右上角創建新應用程序

為您的應用程序輸入一個名稱:

提示輸入應用程序名稱或檢查開發支持以查看應用程序是否已存在

單擊標有“創建”的按鈕創建應用程序。如果操作成功完成,您將看到如下所示的儀表板:

Discord 應用程序儀表板

為應用程序創建機器人

在本節中,您將為 Discord 應用程序創建機器人。在網頁的左側窗格中,單擊“Bot”以打開 bot 菜單:

機器人菜單項在設置列表中以藍色突出顯示

在“Build-A-Bot”部分下,單擊“Add Bot”按鈕創建機器人:

Discord 使用藍色按鈕構建機器人部分以在右上角添加機器人

單擊此按鈕後,您將成功創建 Discord 機器人。最後,激活“MESSAGE CONTENT INTENT”選項,以便機器人可以接收來自您 Discord 服務器中用戶的消息:

啟用消息內容意圖選項以允許 Discord Bot 接收來自用戶的消息

將機器人安裝到您的 Discord 服務器

在設置你的機器人時你需要做的最後一件事是將它安裝到你的服務器上。在左側導航窗格中,單擊“OAuth2”菜單項以切換下拉菜單。在此下拉列表中,單擊“URL 生成器”選項:

Oauth2 菜單項突出顯示 Url 生成器子菜單選項大綱與淺藍色框

在“SCOPES”下的 URL Generator 菜單中,勾選“bot”選項:

帶有復選框的 Url 生成器菜單,用於選中 Bot 選項的範圍內的各種項目

向下滾動頁面至“BOT PERMISSIONS”並勾選“管理員”選項以授予機器人管理員權限:

Bot 權限子菜單,帶有附加複選框項目,在一般權限下勾選了管理員選項

滾動到頁面底部並複制底部生成的 URL,然後在瀏覽器中打開生成的 URL:

提示為 Discord Bot 安裝選擇服務器目標和有關權限的信息

在導航到生成的 URL 後打開的網頁中,選擇要安裝機器人的服務器。單擊“繼續”繼續。

在下一個屏幕上,單擊“授權”。然後該網頁將提示您驗證您是人類:

將應用程序添加到 Discord 服務器的確認屏幕

完成這些步驟後,打開服務器的成員列表。您應該會看到您的機器人被列為成員。

設置 Rust 代碼環境

在本節中,我將指導您為 Discord 機器人設置 Rust 代碼環境。代碼環境將包含開始構建機器人所需的代碼和包。

要設置項目,我們將使用一個名為 Shuttle 的工具。Shuttle 允許您在 Rust 中初始化、構建和部署各種項目。

對於這個項目,我們將使用 Shuttle 來初始化一個 Serenity 項目。Serenity 是一個用 Rust 構建 Discord 聊天機器人的框架

要初始化 Serenity 項目,請為您希望項目所在的位置創建一個新目錄。然後,使用以下命令安裝 Shuttle:

cargo install cargo-shuttle

接下來在目錄下初始化一個項目:

cargo shuttle init --serenity

最後,構建項目:

cargo build

如果您正確地執行了這些步驟,您應該會看到您的目錄中充滿了入門所需的代碼。

將 Rust 代碼庫連接到您的 Discord 機器人

我們在上一節中生成的代碼src/lib.rs是一個基本項目,您可以連接到您的機器人,我們將在本節中逐步執行此操作。

為了成功地將您的代碼連接到您的機器人,您首先需要獲取您的機器人令牌。機器人令牌是對您的機器人的引用。每個機器人都有一個唯一的參考,您可以使用它來將代碼庫連接到您的機器人。

要檢索您的機器人令牌,請先打開 Discord 開發人員儀表板。單擊左側導航窗格中的“機器人”。然後,單擊“重置令牌”按鈕:

使用應用程序信息和重置令牌的按鈕構建 Discord 開發人員儀表板的機器人屏幕

點擊“複製”複製令牌:

使用生成的令牌構建 Discord 開發人員儀表板的機器人屏幕,以將 Rust 代碼連接到 Discord Bot

要將代碼庫連接到您的機器人,請Secrets.toml在項目的根目錄中創建一個文件。將以下內容寫入文件Secrets.toml並替換* bot_token *為您的機器人令牌:

DISCORD_TOKEN="* bot_token *"

使用此命令運行項目:

cargo shuttle run

在這些步驟結束時,您應該會在您的服務器上看到在線的 Discord 機器人。如果您!hello在服務器上鍵入,機器人應該以world!.

要了解機器人如何響應!hello,請查看文件第 12-24 行的事件處理程序src/lib.rs

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

事件處理程序有一個message方法,只要有人在服務器上發送消息,該方法就會被調用。該message函數有一個if塊檢查新消息是否說!hello

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

如果消息匹配!hello,程序world!使用以下語句將消息發送回服務器:

msg.channel_id.say(&ctx.http, "world!").await

您可以按照上述步驟對機器人進行編程,以使用自定義響應來響應任何自定義消息。

為 Discord 機器人創建命令

命令是與機器人交互的更直接的方式。與消息不同,命令以/斜杠開頭——例如,/hello

您可以像發送消息一樣在 Discord 中發送命令,但它們是與機器人交互的首選方式,因為您可以輕鬆分辨哪些消息是命令,哪些消息不是。

要讓您的機器人響應命令,您需要安裝機器人的服務器的 ID。為了獲取服務器ID,您需要先在您的帳戶上啟用開發者模式。

在您的 Discord 帳戶上啟用開發者模式

開發人員模式是一種 Discord 設置,可讓開發人員在服務器中提升權限。在本節中,我將指導您在您的系統上啟用開發者模式,以便您可以復制您的服務器 ID 並使您的機器人能夠響應命令。

在 Windows 或 Mac 上

在窗口底部,單擊用戶名旁邊的設置圖標。在左窗格中,選擇“應用程序設置”下的“外觀”。

在外觀設置菜單中,單擊“高級”以打開高級設置菜單,然後您可以在其中切換“開發人員模式”選項。最後,右鍵單擊服務器名稱並選擇“複製ID”以復制服務器ID。

在 Linux 上

在窗口底部,單擊用戶名旁邊的設置圖標。在左側窗格中,選擇“APP SETTINGS”下的“Advanced”以打開高級設置菜單,然後您可以在其中切換“Developer Mode”選項。

然後,右鍵單擊服務器名稱並選擇“複製ID”以復制服務器ID:

在開發人員模式下啟用 Discord 高級應用程序設置,打開服務器菜單並選擇在列表底部複製服務器 ID

使您的機器人能夠響應命令

準備好服務器 ID 後,按照以下步驟使您的機器人能夠響應命令。首先,將ready下面的方法寫入事件處理程序:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

接下來,將interaction_create下面的處理程序寫入事件處理程序:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

ready事件處理程序的方法中,將* guild_id *第三行替換為您的服務器 ID。

如果您的代碼仍在終端中運行,請重新啟動它。當您在服務器上看到在線機器人時,請發送消息/hello。您應該會看到機器人的回复說hello作為回應。

與消息響應一樣,您可以按照我們上面介紹的步驟對您的機器人進行編程,以使用自定義響應來響應任何自定義命令。

將 Discord 機器人部署到 Shuttle 服務器

在您的系統上運行您的項目可能有缺點。更複雜的機器人可能需要大量資源才能運行並為每個用戶提供服務。

部署您的機器人可以讓您的機器人獲得不使用計算機資源運行的優勢。它還可以使您的機器人保持在線,即使您不在線也是如此。

Shuttle 允許您將機器人部署到 Shuttle 服務器。要部署您的機器人,請在您的項目目錄中運行此命令:

cargo shuttle deploy

結論

在 Rust 中構建 Discord 聊天機器人可能是一項具有挑戰性的任務。但是有了正確的知識和工具,它可以很容易地完成。

通過本文中提供的分步說明,任何具有 Rust 編程經驗和 Discord 帳戶的人都可以學習構建自己的 Discord 聊天機器人。如果你正在尋找一些要構建的 Discord 機器人,這裡有一些想法:

  • 歡迎機器人歡迎新用戶訪問服務器或頻道
  • 用於玩知識問答、測驗、井字遊戲和其他遊戲的遊戲機器人
  • 播放音樂或允許用戶創建或選擇要共享的視頻、圖像或 GIF 的媒體機器人
  • 投票機器人幫助用戶創建和發送投票
  • 用於自動化服務器功能(例如回答常見問題解答等)的實用程序機器人

如需進一步閱讀 Rust Discord 機器人,請查看一些Serenity Discord 示例機器人Serenity 文檔

資料來源: https: //blog.logrocket.com

#rust #chatbot #discord

用 Rust 構建一個 Discord 聊天機器人

Rust'ta Discord Sohbet Botu Oluşturma

Shuttle ve Serenity ile Rust'ta Discord botu oluşturmayı öğrenin. Discord'da nasıl bot oluşturacağınızı, botu sunucunuza nasıl ekleyeceğinizi ve Rust kodunuzu botunuza nasıl bağlayacağınızı öğrenin.

Discord botları, kullanıcılara çeşitli yararlı özellikler sağlarken, sunucu sahiplerine ve personel üyelerine çok fazla zaman ve emek kazandırabilir. Aksi takdirde çok fazla zaman ve çaba gerektirecek tekrarlayan görevleri ve görevleri otomatikleştirmek için Discord'da botları kullanabilirsiniz.

Bu yazımızda Discord'da bot oluşturmayı, botu sunucunuza eklemeyi ve Rust kodunuzu botunuza bağlamayı öğreneceksiniz.

İçindekiler:

  • Discord botunu kurma
    • Discord'da uygulama oluşturma
    • Uygulama için bot oluşturma
    • Botu Discord sunucunuza yüklemek
  • Rust kodu ortamını ayarlama
  • Connecting the Rust codebase to your Discord bot
  • Creating commands for the Discord bot
    • Enabling developer mode on your Discord account
    • Enabling your bot to respond to a command
  • Deploying the Discord bot to the Shuttle server

To follow along with this article, you need at least some level of familiarity with Discord. You should also have a Discord account, a Discord server that you own, and some programming experience with Rust.


Setting up the Discord bot

Setting up the bot in Discord can be a little tricky, especially if this is your first time doing it. In this section, I’ll guide you through setting up the bot for your server.

Creating an application in Discord

A Discord application is a service that provides an interface between Discord users and your code. The interface that the application provides is called a bot. A bot receives messages from users and sends a response.

To create a Discord application, first log in to your Discord account in your browser. Next, open the Discord developer portal in your browser and click the button labeled “New Application” at the top right of the page:

Sağ Üstte Yeni Uygulama Oluşturmak İçin Mavi Düğmeli Karanlık Modda Discord Geliştirici Portalı

Enter a name for your application:

Uygulama İçin Ad Girmenizi İstemi Veya Uygulamanın Halihazırda Var Olduğunu Görmek İçin Dev Desteği İle Kontrol Edin

Click the button labeled “Create” to create the application. If the action completes successfully, you’ll be greeted with a dashboard that looks like this:

Discord Uygulama Kontrol Paneli

Creating a bot for the application

In this section, you’ll create the bot for your Discord application. On the left pane of the webpage, click “Bot” to open the bot menu:

Ayarlar Listesinde Mavi Renkle Vurgulanan Bot Menü Öğesi

Under the “Build-A-Bot” section, click the “Add Bot” button to create the bot:

Discord Sağ Üstte Bot Eklemek İçin Mavi Düğmeli Bir Bot Bölümü Oluşturun

After clicking this button, you will have successfully created the Discord bot. To finish off, activate the “MESSAGE CONTENT INTENT” option so that the bot can receive messages from users in your Discord server:

Discord Bot'un Kullanıcılardan Mesaj Almasına İzin Vermek İçin Mesaj İçeriği Niyet Seçeneği Açıldı

Installing the bot to your Discord server

The last thing you need to do in setting your bot is to install it to your server. On the left navigation pane, click the “OAuth2” menu item to toggle a dropdown. In this dropdown, click the “URL Generator” option:

Oauth2 Menü Öğesi Url Oluşturucu ile Vurgulanır Alt Menü Seçeneği Daha Açık Mavi Kutuyla Anahat

In the URL Generator menu under “SCOPES,” tick the “bot” option:

Bot Seçeneği İşaretli Kapsamlar Altındaki Çeşitli Öğeler İçin Onay Kutuları Olan Url Oluşturucu Menüsü

Scroll farther down the page to “BOT PERMISSIONS” and tick the “Administrator” option to give the bot admin privileges:

Genel İzinler Altında Yönetici Seçeneği İşaretlenmiş Ek Onay Kutusu Öğeleriyle Bot İzinleri Alt Menüsü

Scroll to the bottom of the page and copy the generated URL on the bottom, then open the generated URL in your browser:

Discord Bot Kurulumu İçin Sunucu Hedefi Seçme İstemi ve İzinler Hakkında Bilgi

In the webpage that opens after you navigate to the generated URL, select the server that you want to install the bot in. Click “Continue” to proceed.

On the next screen, click “Authorize.” The webpage will then prompt you to verify that you are human:

Discord Sunucusuna Uygulama Eklemek İçin Onay Ekranı

When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.

Setting up the Rust code environment

In this section, I’ll guide you through setting up the Rust code environment for your Discord bot. The code environment will have the necessary code and packages for you to get started with building the bot.

To set up the project, we’ll use a tool called Shuttle. Shuttle lets you initialize, build, and deploy a variety of projects in Rust.

For this project, we’ll use Shuttle to initialize a Serenity project. Serenity is a framework for building Discord chat bots in Rust.

To initialize the Serenity project, create a new directory for where you want your project to be. Then, install Shuttle with the command below:

cargo install cargo-shuttle

Next, initialize a project in the directory:

cargo shuttle init --serenity

Finally, build the project:

cargo build

If you followed these steps correctly, you should see your directory filled with the necessary code for getting started.

Connecting the Rust codebase to your Discord bot

The src/lib.rs code — which we generated in the previous section — is a basic project that you can connect to your bot, which we will do step-by-step in this section.

In order to successfully connect your code to your bot, you first need to get your bot token. A bot token is a reference to your bot. Every bot has a unique reference that you can use to connect a codebase to your bot.

To retrieve your bot token, first open the Discord developer dashboard. Click “Bot” on the left navigation pane. Then, click the “Reset Token” button:

Uygulama Bilgileri ve Belirteci Sıfırlama Düğmesi ile Discord Geliştirici Panosunun Bot Ekranını Oluşturun

Click “Copy” to copy the token:

Rust Kodunu Discord Bot'a Bağlamak İçin Oluşturulan Jetonla Discord Geliştirici Kontrol Panelinin Bot Ekranını Oluşturun

To connect the code base to your bot, create a Secrets.toml file in the project’s root directory. Write the following into the Secrets.toml file and replace * bot_token * with your bot token:

DISCORD_TOKEN="* bot_token *"

Run the project with this command:

cargo shuttle run

At the end of these steps, you should see your Discord bot online on your server. If you type !hello on the server, the bot should respond with world!.

To understand how the bot responds to !hello, take a look at the event handler from lines 12–24 of the src/lib.rs file:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

The event handler has a message method that gets called anytime someone sends a message on the server. The message function has an if block checking if the new message says !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

If the message matches !hello, the program sends the world! message back to the server with this statement:

msg.channel_id.say(&ctx.http, "world!").await

You can program the bot to respond to any custom messages with custom responses following the steps above.

Creating commands for the Discord bot

Commands are a more direct way to interact with a bot. Unlike messages, commands begin with a / slash — e.g., /hello.

You can send commands in Discord the same way you send messages, but they are the preferred way of interacting with bots because you can easily tell what messages are commands and what messages are not.

To allow your bot to respond to commands, you’ll need the ID of the server in which you installed the bot. In order to get the server ID, you need to enable developer mode on your account first.

Enabling developer mode on your Discord account

Developer mode is a Discord setting that gives developers elevated privileges in a server. In this section, I’ll guide you through enabling developer mode on your system so you can copy your server ID and enable your bot to respond to commands.

On Windows or Mac

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Appearance” under “APP SETTINGS.”

In the appearance settings menu, click “Advanced” to open the advanced settings menu, where you can then toggle the “Developer Mode” option. Finally, right-click the server name and select “Copy ID” to copy the server ID.

On Linux

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Advanced” under “APP SETTINGS” to open the advanced settings menu, where you can then toggle the “Developer Mode” option.

Then, right-click the server name and select “Copy ID” to copy the server ID:

Discord Gelişmiş Uygulama Ayarları, Sunucu Menüsü Açıkken Geliştirici Modunda Etkinleştirildi ve Sunucu Kimliğini Listenin Altında Kopyalama Seçeneği

Enabling your bot to respond to a command

With the server ID ready, follow these steps to enable your bot to respond to a command. First, write the ready method below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Next, write the interaction_create handler below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

In the ready method of the event handler, replace * guild_id * on the third line with your server ID.

If your code is still running in the terminal, restart it. When you see your bot online on your server, send a /hello message. You should see a response from the bot saying hello in response.

As with message responses, you can program your bot to respond to any custom commands with custom responses by following the steps we covered above.

Deploying the Discord bot to the Shuttle server

Running your project on your system can have disadvantages. More complex bots may require large resources to run and serve every user.

Deploying your bot gives your bot the advantage of not using your computer’s resources to run. It also keeps your bot online, even if you’re not.

Shuttle, botunuzu Shuttle sunucusuna konuşlandırmanıza izin verir. Botunuzu konuşlandırmak için proje dizininizde şu komutu çalıştırın:

cargo shuttle deploy

Çözüm

Rust'ta bir Discord sohbet botu oluşturmak zorlu bir görev olabilir. Ancak doğru bilgi ve araçlarla kolayca yapılabilir.

Bu makalede sağlanan adım adım talimatlarla, Rust'ta programlama deneyimi ve Discord hesabı olan herkes kendi Discord sohbet botunu oluşturmayı öğrenebilir. Oluşturmak için bazı Discord botları arıyorsanız, işte bazı fikirler:

  • Yeni kullanıcıları bir sunucuya veya kanala davet etmek için hoş geldiniz botları
  • Trivia, quiz, tic-tac-toe ve diğer oyunları oynamak için oyun botları
  • Müzik çalan veya kullanıcıların paylaşmak üzere videolar, resimler veya GIF'ler oluşturmasına veya seçmesine izin veren medya botları
  • Kullanıcıların anket oluşturmasına ve göndermesine yardımcı olan anket botları
  • SSS'leri yanıtlamak ve daha fazlası gibi sunucu işlevlerini otomatikleştirmek için yardımcı program botları

Rust Discord botları hakkında daha fazla bilgi için, bazı Serenity Discord bot örneklerini veya Serenity belgelerini inceleyin .

Kaynak: https://blog.logrocket.com

#rust #discord #chatbot

Rust'ta Discord Sohbet Botu Oluşturma

สร้าง Discord Chat Bot ใน Rust

เรียนรู้วิธีสร้างบอท Discord ใน Rust ด้วย Shuttle และ Serenity เรียนรู้วิธีสร้างบอทใน Discord เพิ่มบอทไปยังเซิร์ฟเวอร์ของคุณ และเชื่อมต่อรหัส Rust กับบอทของคุณ

บอท Discord สามารถช่วยเจ้าของเซิร์ฟเวอร์และพนักงานลงแรงและเวลาได้มาก ในขณะเดียวกันก็มอบคุณสมบัติที่มีประโยชน์มากมายให้กับผู้ใช้ คุณสามารถใช้บอทใน Discord เพื่อทำงานซ้ำๆ โดยอัตโนมัติและงานที่ต้องใช้เวลาและความพยายามมาก

ในบทความนี้ คุณจะได้เรียนรู้วิธีสร้างบอทใน Discord เพิ่มบอทไปยังเซิร์ฟเวอร์ของคุณ และเชื่อมต่อรหัส Rust กับบอทของคุณ

สารบัญ:

  • การตั้งค่าบอท Discord
    • การสร้างแอปพลิเคชันใน Discord
    • การสร้างบอทสำหรับแอปพลิเคชัน
    • การติดตั้งบอทไปยังเซิร์ฟเวอร์ Discord ของคุณ
  • การตั้งค่าสภาพแวดล้อมรหัสสนิม
  • การเชื่อมต่อฐานข้อมูลรหัส Rust กับบอท Discord ของคุณ
  • การสร้างคำสั่งสำหรับบอท Discord
    • เปิดใช้งานโหมดผู้พัฒนาในบัญชี Discord ของคุณ
    • เปิดใช้งานบอทของคุณเพื่อตอบสนองต่อคำสั่ง
  • การปรับใช้บอท Discord กับเซิร์ฟเวอร์ Shuttle

หากต้องการติดตามบทความนี้ คุณต้องมีความคุ้นเคยกับ Discord ในระดับหนึ่งเป็นอย่างน้อย คุณควรมีบัญชี Discord เซิร์ฟเวอร์ Discord ที่คุณเป็นเจ้าของ และประสบการณ์ในการเขียนโปรแกรมด้วย Rust


การตั้งค่าบอท Discord

การตั้งค่าบอทใน Discord อาจเป็นเรื่องยุ่งยากเล็กน้อย โดยเฉพาะอย่างยิ่งหากนี่เป็นครั้งแรกที่คุณทำ ในส่วนนี้ ฉันจะแนะนำคุณตลอดการตั้งค่าบอทสำหรับเซิร์ฟเวอร์ของคุณ

การสร้างแอปพลิเคชันใน Discord

แอปพลิเคชัน Discord เป็นบริการที่ให้อินเทอร์เฟซระหว่างผู้ใช้ Discord และรหัสของคุณ อินเทอร์เฟซที่แอปพลิเคชันจัดเตรียมให้เรียกว่าบอท บอทได้รับข้อความจากผู้ใช้และส่งการตอบกลับ

หากต้องการสร้างแอปพลิเคชัน Discord ให้ลงชื่อเข้าใช้บัญชี Discord ในเบราว์เซอร์ของคุณก่อน ถัดไป เปิดพอร์ทัลผู้พัฒนา Discordในเบราว์เซอร์ของคุณ แล้วคลิกปุ่ม "แอปพลิเคชันใหม่" ที่ด้านบนขวาของหน้า:

พอร์ทัลนักพัฒนาที่ไม่ลงรอยกันในโหมดมืดพร้อมปุ่มสีน้ำเงินเพื่อสร้างแอปพลิเคชันใหม่ที่ด้านบนขวา

ป้อนชื่อสำหรับแอปพลิเคชันของคุณ:

แจ้งให้ป้อนชื่อสำหรับแอปพลิเคชันหรือตรวจสอบกับฝ่ายสนับสนุน Dev เพื่อดูว่ามีแอปอยู่แล้วหรือไม่

คลิกปุ่ม "สร้าง" เพื่อสร้างแอปพลิเคชัน หากการดำเนินการเสร็จสมบูรณ์ คุณจะได้รับการต้อนรับด้วยแดชบอร์ดที่มีลักษณะดังนี้:

แดชบอร์ดแอปพลิเคชัน Discord

การสร้างบอทสำหรับแอปพลิเคชัน

ในส่วนนี้ คุณจะสร้างบอทสำหรับแอปพลิเคชัน Discord ของคุณ ที่บานหน้าต่างด้านซ้ายของหน้าเว็บ คลิก “บอท” เพื่อเปิดเมนูบอท:

รายการเมนูบอทที่ไฮไลต์เป็นสีน้ำเงินในรายการการตั้งค่า

ภายใต้ส่วน “สร้างบอท” ให้คลิกปุ่ม “เพิ่มบอท” เพื่อสร้างบอท:

Discord สร้างส่วน Bot ด้วยปุ่มสีน้ำเงินเพื่อเพิ่ม Bot ที่ด้านบนขวา

หลังจากคลิกปุ่มนี้ คุณจะสร้างบอท Discord ได้สำเร็จ หากต้องการสิ้นสุด ให้เปิดใช้งานตัวเลือก “ข้อความแสดงเจตนา” เพื่อให้บอทสามารถรับข้อความจากผู้ใช้ในเซิร์ฟเวอร์ Discord ของคุณ:

ตัวเลือกความตั้งใจของเนื้อหาข้อความเปิดใช้งานเพื่ออนุญาตให้บอท Discord รับข้อความจากผู้ใช้

การติดตั้งบอทไปยังเซิร์ฟเวอร์ Discord ของคุณ

สิ่งสุดท้ายที่คุณต้องทำในการตั้งค่าบอทคือติดตั้งลงในเซิร์ฟเวอร์ของคุณ ในบานหน้าต่างนำทางด้านซ้าย คลิกรายการเมนู “OAuth2” เพื่อสลับรายการแบบเลื่อนลง ในดร็อปดาวน์นี้ ให้คลิกตัวเลือก “ตัวสร้าง URL”:

รายการเมนู Oauth2 ที่เน้นด้วยตัวเลือกเมนูย่อยของตัวสร้าง Url พร้อมกล่องสีฟ้าอ่อน

ในเมนูตัวสร้าง URL ใต้ “ขอบเขต” ให้ทำเครื่องหมายที่ตัวเลือก “บอท”:

เมนูตัวสร้าง URL พร้อมช่องทำเครื่องหมายสำหรับรายการต่างๆ ภายใต้ขอบเขตพร้อมตัวเลือก Bot ที่ทำเครื่องหมายไว้

เลื่อนลงไปด้านล่างของหน้าไปที่ “BOT PERMISSIONS” และทำเครื่องหมายที่ตัวเลือก “Administrator” เพื่อให้สิทธิ์ของผู้ดูแลระบบ bot:

เมนูย่อยสิทธิ์ของ Bot พร้อมรายการช่องทำเครื่องหมายเพิ่มเติมพร้อมตัวเลือกผู้ดูแลระบบทำเครื่องหมายภายใต้สิทธิ์ทั่วไป

เลื่อนไปที่ด้านล่างของหน้าและคัดลอก URL ที่สร้างขึ้นที่ด้านล่าง จากนั้นเปิด URL ที่สร้างขึ้นในเบราว์เซอร์ของคุณ:

แจ้งให้เลือกปลายทางเซิร์ฟเวอร์สำหรับการติดตั้ง Discord Bot และข้อมูลเกี่ยวกับสิทธิ์

ในหน้าเว็บที่เปิดขึ้นหลังจากที่คุณนำทางไปยัง URL ที่สร้างขึ้น ให้เลือกเซิร์ฟเวอร์ที่คุณต้องการติดตั้งบอท คลิก “ดำเนินการต่อ” เพื่อดำเนินการต่อ

ในหน้าจอถัดไป ให้คลิก "อนุญาต" หน้าเว็บจะแจ้งให้คุณยืนยันว่าคุณเป็นมนุษย์:

หน้าจอยืนยันการเพิ่มแอปพลิเคชันไปยังเซิร์ฟเวอร์ Discord

เมื่อทำตามขั้นตอนเหล่านี้เสร็จแล้ว ให้เปิดรายชื่อสมาชิกของเซิร์ฟเวอร์ คุณควรเห็นบอตของคุณแสดงรายการเป็นสมาชิก

การตั้งค่าสภาพแวดล้อมรหัสสนิม

ในส่วนนี้ ฉันจะแนะนำคุณตลอดการตั้งค่าสภาพแวดล้อมรหัสสนิมสำหรับบอท Discord ของคุณ สภาพแวดล้อมรหัสจะมีรหัสและแพ็คเกจที่จำเป็นสำหรับคุณในการเริ่มต้นสร้างบอท

ในการตั้งค่าโครงการ เราจะใช้เครื่องมือที่เรียกว่า Shuttle Shuttle ช่วยให้คุณเริ่มต้น สร้าง และปรับใช้โครงการต่างๆ ใน ​​Rust

สำหรับโครงการนี้ เราจะใช้ Shuttle เพื่อเริ่มต้นโครงการ Serenity Serenity เป็นเฟรมเวิร์กสำหรับสร้างบอทแชท Discord ใน Rust

ในการเริ่มต้นโครงการ Serenity ให้สร้างไดเร็กทอรีใหม่สำหรับตำแหน่งที่คุณต้องการให้โครงการของคุณอยู่ จากนั้นติดตั้ง Shuttle ด้วยคำสั่งด้านล่าง:

cargo install cargo-shuttle

ถัดไป เริ่มต้นโครงการในไดเร็กทอรี:

cargo shuttle init --serenity

สุดท้าย สร้างโครงการ:

cargo build

หากคุณทำตามขั้นตอนเหล่านี้อย่างถูกต้อง คุณควรเห็นไดเร็กทอรีของคุณเต็มไปด้วยโค้ดที่จำเป็นสำหรับการเริ่มต้นใช้งาน

การเชื่อมต่อฐานข้อมูลรหัส Rust กับบอท Discord ของคุณ

โค้ดsrc/lib.rs— ที่เราสร้างขึ้นในส่วนที่แล้ว — เป็นโปรเจ็กต์พื้นฐานที่คุณสามารถเชื่อมต่อกับบอทของคุณ ซึ่งเราจะทำทีละขั้นตอนในส่วนนี้

ในการเชื่อมต่อรหัสของคุณกับบอทให้สำเร็จ คุณต้องได้รับโทเค็นบอทของคุณก่อน โทเค็นบอทคือการอ้างอิงถึงบอทของคุณ บอททุกตัวมีการอ้างอิงที่ไม่ซ้ำกันซึ่งคุณสามารถใช้เชื่อมต่อฐานรหัสกับบอทของคุณได้

ในการดึงโทเค็นบอทของคุณ ก่อนอื่นให้เปิดแดชบอร์ดสำหรับนักพัฒนา Discord คลิก “บอท” ในบานหน้าต่างนำทางด้านซ้าย จากนั้นคลิกปุ่ม "รีเซ็ตโทเค็น":

สร้างหน้าจอบอทของแดชบอร์ดผู้พัฒนา Discord พร้อมข้อมูลแอปพลิเคชันและปุ่มเพื่อรีเซ็ตโทเค็น

คลิก “คัดลอก” เพื่อคัดลอกโทเค็น:

สร้างหน้าจอ Bot ของแดชบอร์ดผู้พัฒนา Discord ด้วยโทเค็นที่สร้างขึ้นเพื่อเชื่อมต่อรหัสสนิมกับบอท Discord

หากต้องการเชื่อมต่อโค้ดเบสกับบอท ให้สร้างSecrets.tomlไฟล์ในไดเร็กทอรีรากของโปรเจ็กต์ เขียนสิ่งต่อไปนี้ลงในSecrets.tomlไฟล์และแทนที่* bot_token *ด้วยโทเค็นบอทของคุณ:

DISCORD_TOKEN="* bot_token *"

เรียกใช้โครงการด้วยคำสั่งนี้:

cargo shuttle run

ในตอนท้ายของขั้นตอนเหล่านี้ คุณควรเห็นบอท Discord ออนไลน์บนเซิร์ฟเวอร์ของคุณ หากคุณพิมพ์!helloบนเซิร์ฟเวอร์ บอทควรตอบกลับworld!ด้วย

หากต้องการทำความเข้าใจว่าบอทตอบสนองอย่างไร!helloให้ดูที่ตัวจัดการเหตุการณ์จากบรรทัดที่ 12–24 ของไฟล์src/lib.rs:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

ตัวจัดการเหตุการณ์มีmessageเมธอดที่เรียกทุกครั้งที่มีคนส่งข้อความบนเซิร์ฟเวอร์ ฟังmessageก์ชั่นมีifการตรวจสอบการบล็อกหากข้อความใหม่ระบุว่า!hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

หากข้อความตรงกัน!helloโปรแกรมจะส่งworld!ข้อความกลับไปยังเซิร์ฟเวอร์พร้อมกับคำสั่งนี้:

msg.channel_id.say(&ctx.http, "world!").await

คุณสามารถตั้งโปรแกรมบอทให้ตอบกลับข้อความที่กำหนดเองด้วยการตอบกลับที่กำหนดเองตามขั้นตอนด้านบน

การสร้างคำสั่งสำหรับบอท Discord

คำสั่งเป็นวิธีที่ตรงกว่าในการโต้ตอบกับบอท ไม่เหมือนข้อความ คำสั่งเริ่มต้นด้วยเครื่องหมายทับ/— เช่น/hello

คุณสามารถส่งคำสั่งใน Discord ได้ด้วยวิธีเดียวกับที่คุณส่งข้อความ แต่เป็นวิธีที่นิยมใช้ในการโต้ตอบกับบอท เพราะคุณสามารถบอกได้อย่างง่ายดายว่าข้อความใดเป็นคำสั่งและข้อความใดไม่ใช่ข้อความ

ในการอนุญาตให้บอทของคุณตอบสนองต่อคำสั่ง คุณต้องมี ID ของเซิร์ฟเวอร์ที่คุณติดตั้งบอท ในการรับ ID เซิร์ฟเวอร์ คุณต้องเปิดใช้งานโหมดผู้พัฒนาในบัญชีของคุณก่อน

เปิดใช้งานโหมดผู้พัฒนาในบัญชี Discord ของคุณ

โหมดผู้พัฒนาคือการตั้งค่า Discord ที่ให้สิทธิ์ระดับสูงแก่นักพัฒนาในเซิร์ฟเวอร์ ในส่วนนี้ ฉันจะแนะนำคุณตลอดการเปิดใช้โหมดผู้พัฒนาในระบบของคุณ เพื่อให้คุณสามารถคัดลอก ID เซิร์ฟเวอร์ของคุณและเปิดใช้งานบอทของคุณเพื่อตอบสนองต่อคำสั่ง

บน Windows หรือ Mac

ที่ด้านล่างของหน้าต่าง คลิกไอคอนการตั้งค่าใกล้กับชื่อผู้ใช้ของคุณ ในบานหน้าต่างด้านซ้าย เลือก "ลักษณะที่ปรากฏ" ภายใต้ "การตั้งค่าแอป"

ในเมนูการตั้งค่ารูปลักษณ์ ให้คลิก "ขั้นสูง" เพื่อเปิดเมนูการตั้งค่าขั้นสูง ซึ่งคุณสามารถสลับตัวเลือก "โหมดนักพัฒนาซอฟต์แวร์" ได้ สุดท้าย คลิกขวาที่ชื่อเซิร์ฟเวอร์แล้วเลือก “คัดลอก ID” เพื่อคัดลอก ID เซิร์ฟเวอร์

บนลินุกซ์

ที่ด้านล่างของหน้าต่าง คลิกไอคอนการตั้งค่าใกล้กับชื่อผู้ใช้ของคุณ ในบานหน้าต่างด้านซ้าย เลือก "ขั้นสูง" ภายใต้ "การตั้งค่าแอป" เพื่อเปิดเมนูการตั้งค่าขั้นสูง ซึ่งคุณสามารถสลับตัวเลือก "โหมดนักพัฒนาซอฟต์แวร์" ได้

จากนั้น คลิกขวาที่ชื่อเซิร์ฟเวอร์แล้วเลือก “คัดลอก ID” เพื่อคัดลอก ID เซิร์ฟเวอร์:

การตั้งค่าแอปขั้นสูงที่ไม่ลงรอยกันเปิดใช้งานในโหมดนักพัฒนาโดยเปิดเมนูเซิร์ฟเวอร์และตัวเลือกในการคัดลอกรหัสเซิร์ฟเวอร์ที่ด้านล่างของรายการ

เปิดใช้งานบอทของคุณเพื่อตอบสนองต่อคำสั่ง

เมื่อ ID เซิร์ฟเวอร์พร้อม ให้ทำตามขั้นตอนเหล่านี้เพื่อให้บอทของคุณตอบสนองต่อคำสั่ง ขั้นแรก เขียนreadyวิธีการด้านล่างลงในตัวจัดการเหตุการณ์:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

ถัดไป เขียนinteraction_createตัวจัดการด้านล่างลงในตัวจัดการเหตุการณ์:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

ในreadyเมธอดของตัวจัดการเหตุการณ์ ให้แทนที่* guild_id *บรรทัดที่สามด้วย ID เซิร์ฟเวอร์ของคุณ

หากรหัสของคุณยังคงทำงานในเทอร์มินัล ให้รีสตาร์ท เมื่อคุณเห็นบอทของคุณออนไลน์บนเซิร์ฟเวอร์ ให้ส่ง/helloข้อความ คุณควรเห็นการตอบกลับจากบอตว่าhelloตอบกลับ

เช่นเดียวกับการตอบกลับข้อความ คุณสามารถตั้งโปรแกรมบอทของคุณให้ตอบสนองต่อคำสั่งที่กำหนดเองด้วยการตอบกลับที่กำหนดเองโดยทำตามขั้นตอนที่เรากล่าวถึงข้างต้น

การปรับใช้บอท Discord กับเซิร์ฟเวอร์ Shuttle

การดำเนินโครงการของคุณในระบบของคุณอาจมีข้อเสีย บอทที่ซับซ้อนมากขึ้นอาจต้องการทรัพยากรจำนวนมากเพื่อเรียกใช้และให้บริการผู้ใช้ทุกคน

การปรับใช้บอททำให้บอทได้รับประโยชน์จากการไม่ใช้ทรัพยากรของคอมพิวเตอร์ในการทำงาน นอกจากนี้ยังช่วยให้บอทของคุณออนไลน์ แม้ว่าคุณจะไม่ได้อยู่ก็ตาม

Shuttle ช่วยให้คุณสามารถปรับใช้บอทของคุณกับเซิร์ฟเวอร์ Shuttle ในการปรับใช้บอทของคุณ ให้รันคำสั่งนี้ในไดเร็กทอรีโปรเจ็กต์ของคุณ:

cargo shuttle deploy

บทสรุป

การสร้างบอทแชท Discord ใน Rust อาจเป็นงานที่ท้าทาย แต่ด้วยความรู้และเครื่องมือที่เหมาะสมก็สามารถทำได้โดยง่าย

ด้วยคำแนะนำทีละขั้นตอนในบทความนี้ ทุกคนที่มีประสบการณ์การเขียนโปรแกรมใน Rust และบัญชี Discord สามารถเรียนรู้วิธีสร้างบอทแชท Discord ของตนเองได้ หากคุณกำลังมองหาบอท Discord เพื่อสร้าง นี่คือแนวคิดบางประการ:

  • บอทต้อนรับเพื่อต้อนรับผู้ใช้ใหม่เข้าสู่เซิร์ฟเวอร์หรือแชนเนล
  • บอทเกมสำหรับเล่นเรื่องไม่สำคัญ แบบทดสอบ tic-tac-toe และเกมอื่นๆ
  • บอทสื่อที่เล่นเพลงหรืออนุญาตให้ผู้ใช้สร้างหรือเลือกวิดีโอ รูปภาพ หรือ GIF เพื่อแบ่งปัน
  • บอทสำรวจเพื่อช่วยผู้ใช้สร้างและส่งแบบสำรวจ
  • บอทยูทิลิตี้สำหรับการทำงานอัตโนมัติของเซิร์ฟเวอร์ เช่น การตอบคำถามที่พบบ่อย และอื่นๆ

หากต้องการอ่านเพิ่มเติมเกี่ยวกับบ็อต Rust Discord โปรดดู ตัวอย่างบ็ อต Serenity Discordหรือเอกสารประกอบของ Serenity

ที่มา: https://blog.logrocket.com

#rust #discord #chatbot

สร้าง Discord Chat Bot ใน Rust
Iara  Simões

Iara Simões

1677155400

Construyendo un bot de chat de Discord en Rust

Aprende a construir un bot de Discord en Rust con Shuttle y Serenity. Aprenda a crear un bot en Discord, agregue el bot a su servidor y conecte su código Rust a su bot.

Los bots de Discord pueden ahorrar mucho tiempo y esfuerzo a los propietarios de servidores y miembros del personal, al mismo tiempo que brindan una variedad de funciones útiles para los usuarios. Puede usar bots en Discord para automatizar tareas repetitivas y tareas que de otro modo requerirían mucho tiempo y esfuerzo.

En este artículo, aprenderá cómo crear un bot en Discord, agregar el bot a su servidor y conectar su código Rust a su bot.

Tabla de contenido:

  • Configurando el bot de Discord
    • Crear una aplicación en Discord
    • Creación de un bot para la aplicación.
    • Instalando el bot en tu servidor de Discord
  • Configuración del entorno de código Rust
  • Conectando el código base de Rust a tu bot de Discord
  • Creando comandos para el bot de Discord
    • Habilitando el modo de desarrollador en su cuenta de Discord
    • Permitir que su bot responda a un comando
  • Implementación del bot de Discord en el servidor de Shuttle

Para seguir este artículo, necesita al menos cierto nivel de familiaridad con Discord. También debe tener una cuenta de Discord, un servidor de Discord de su propiedad y algo de experiencia en programación con Rust.


Configurando el bot de Discord

Configurar el bot en Discord puede ser un poco complicado, especialmente si es la primera vez que lo hace. En esta sección, lo guiaré a través de la configuración del bot para su servidor.

Crear una aplicación en Discord

Una aplicación de Discord es un servicio que proporciona una interfaz entre los usuarios de Discord y su código. La interfaz que proporciona la aplicación se denomina bot. Un bot recibe mensajes de los usuarios y envía una respuesta.

Para crear una aplicación de Discord, primero inicie sesión en su cuenta de Discord en su navegador. A continuación, abra el portal para desarrolladores de Discord en su navegador y haga clic en el botón "Nueva aplicación" en la parte superior derecha de la página:

Portal para desarrolladores de Discord en modo oscuro con botón azul para crear una nueva aplicación en la parte superior derecha

Introduzca un nombre para su aplicación:

Solicite ingresar el nombre de la aplicación o verifique con el soporte de desarrollo para ver si la aplicación ya existe

Haga clic en el botón "Crear" para crear la aplicación. Si la acción se completa con éxito, será recibido con un tablero que se ve así:

Panel de aplicaciones de Discord

Creación de un bot para la aplicación.

En esta sección, creará el bot para su aplicación Discord. En el panel izquierdo de la página web, haga clic en "Bot" para abrir el menú del bot:

Elemento del menú Bot resaltado en azul en la lista de configuración

Under the “Build-A-Bot” section, click the “Add Bot” button to create the bot:

Discord Cree una sección de bot con el botón azul para agregar bot en la parte superior derecha

After clicking this button, you will have successfully created the Discord bot. To finish off, activate the “MESSAGE CONTENT INTENT” option so that the bot can receive messages from users in your Discord server:

Opción de intención de contenido del mensaje activada para permitir que Discord Bot reciba mensajes de los usuarios

Installing the bot to your Discord server

The last thing you need to do in setting your bot is to install it to your server. On the left navigation pane, click the “OAuth2” menu item to toggle a dropdown. In this dropdown, click the “URL Generator” option:

Elemento de menú Oauth2 resaltado con el esquema de opción de submenú del generador de URL con un cuadro azul más claro

In the URL Generator menu under “SCOPES,” tick the “bot” option:

Menú del generador de URL con casillas de verificación para varios elementos en los ámbitos con la opción Bot marcada

Scroll farther down the page to “BOT PERMISSIONS” and tick the “Administrator” option to give the bot admin privileges:

Submenú de permisos de bot con elementos de casilla de verificación adicionales con la opción de administrador marcada en Permisos generales

Scroll to the bottom of the page and copy the generated URL on the bottom, then open the generated URL in your browser:

Solicitud para seleccionar el destino del servidor para la instalación del bot Discord e información sobre los permisos

In the webpage that opens after you navigate to the generated URL, select the server that you want to install the bot in. Click “Continue” to proceed.

On the next screen, click “Authorize.” The webpage will then prompt you to verify that you are human:

Pantalla de confirmación para agregar una aplicación al servidor Discord

When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.

Setting up the Rust code environment

In this section, I’ll guide you through setting up the Rust code environment for your Discord bot. The code environment will have the necessary code and packages for you to get started with building the bot.

To set up the project, we’ll use a tool called Shuttle. Shuttle lets you initialize, build, and deploy a variety of projects in Rust.

Para este proyecto, usaremos Shuttle para inicializar un proyecto de Serenity. Serenity es un marco para construir bots de chat de Discord en Rust.

Para inicializar el proyecto Serenity, cree un nuevo directorio para el lugar donde desea que esté su proyecto. Luego, instale Shuttle con el siguiente comando:

cargo install cargo-shuttle

A continuación, inicialice un proyecto en el directorio:

cargo shuttle init --serenity

Finalmente, construye el proyecto:

cargo build

Si siguió estos pasos correctamente, debería ver su directorio lleno con el código necesario para comenzar.

Conectando el código base de Rust a tu bot de Discord

El src/lib.rscódigo, que generamos en la sección anterior, es un proyecto básico que puede conectar a su bot, lo cual haremos paso a paso en esta sección.

Para conectar con éxito su código a su bot, primero debe obtener su token de bot. Un token de bot es una referencia a su bot. Cada bot tiene una referencia única que puede usar para conectar una base de código a su bot.

Para recuperar su token de bot, primero abra el panel de control del desarrollador de Discord. Haga clic en "Bot" en el panel de navegación izquierdo. Luego, haga clic en el botón "Restablecer token":

Cree una pantalla de bot del panel de control del desarrollador de Discord con información de la aplicación y un botón para restablecer el token

Haga clic en "Copiar" para copiar el token:

Cree una pantalla de bot del panel de control del desarrollador de Discord con un token generado para conectar el código Rust al bot de Discord

Para conectar el código base a su bot, cree un Secrets.tomlarchivo en el directorio raíz del proyecto. Escriba lo siguiente en el Secrets.tomlarchivo y reemplácelo * bot_token *con su token de bot:

DISCORD_TOKEN="* bot_token *"

Ejecute el proyecto con este comando:

cargo shuttle run

Al final de estos pasos, debería ver su bot de Discord en línea en su servidor. Si escribe !helloen el servidor, el bot debería responder con world!.

To understand how the bot responds to !hello, take a look at the event handler from lines 12–24 of the src/lib.rs file:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

The event handler has a message method that gets called anytime someone sends a message on the server. The message function has an if block checking if the new message says !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

If the message matches !hello, the program sends the world! message back to the server with this statement:

msg.channel_id.say(&ctx.http, "world!").await

You can program the bot to respond to any custom messages with custom responses following the steps above.

Creating commands for the Discord bot

Commands are a more direct way to interact with a bot. Unlike messages, commands begin with a / slash — e.g., /hello.

You can send commands in Discord the same way you send messages, but they are the preferred way of interacting with bots because you can easily tell what messages are commands and what messages are not.

To allow your bot to respond to commands, you’ll need the ID of the server in which you installed the bot. In order to get the server ID, you need to enable developer mode on your account first.

Enabling developer mode on your Discord account

Developer mode is a Discord setting that gives developers elevated privileges in a server. In this section, I’ll guide you through enabling developer mode on your system so you can copy your server ID and enable your bot to respond to commands.

On Windows or Mac

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Appearance” under “APP SETTINGS.”

In the appearance settings menu, click “Advanced” to open the advanced settings menu, where you can then toggle the “Developer Mode” option. Finally, right-click the server name and select “Copy ID” to copy the server ID.

On Linux

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Advanced” under “APP SETTINGS” to open the advanced settings menu, where you can then toggle the “Developer Mode” option.

Then, right-click the server name and select “Copy ID” to copy the server ID:

Configuración avanzada de la aplicación Discord habilitada en el modo de desarrollador con el menú del servidor abierto y la opción de copiar la identificación del servidor en la parte inferior de la lista

Enabling your bot to respond to a command

With the server ID ready, follow these steps to enable your bot to respond to a command. First, write the ready method below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Next, write the interaction_create handler below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

En el readymétodo del controlador de eventos, reemplace * guild_id *en la tercera línea con su ID de servidor.

Si su código aún se está ejecutando en la terminal, reinícielo. Cuando vea su bot en línea en su servidor, envíe un /hellomensaje. Debería ver una respuesta del bot diciendo helloen respuesta.

Al igual que con las respuestas de mensajes, puede programar su bot para responder a cualquier comando personalizado con respuestas personalizadas siguiendo los pasos que cubrimos anteriormente.

Implementación del bot de Discord en el servidor de Shuttle

Ejecutar su proyecto en su sistema puede tener desventajas. Los bots más complejos pueden requerir grandes recursos para ejecutarse y servir a cada usuario.

La implementación de su bot le da a su bot la ventaja de no usar los recursos de su computadora para ejecutarse. También mantiene su bot en línea, incluso si no lo está.

Shuttle le permite implementar su bot en el servidor de Shuttle. Para implementar su bot, ejecute este comando en el directorio de su proyecto:

cargo shuttle deploy

Conclusión

Construir un bot de chat de Discord en Rust puede ser una tarea desafiante. Pero con el conocimiento y las herramientas adecuadas, se puede hacer fácilmente.

Con las instrucciones paso a paso proporcionadas en este artículo, cualquier persona con experiencia en programación en Rust y una cuenta de Discord puede aprender a crear su propio bot de chat de Discord. Si está buscando algunos bots de Discord para construir, aquí hay algunas ideas:

  • Bots de bienvenida para dar la bienvenida a nuevos usuarios a un servidor o canal
  • Bots de juegos para jugar trivia, cuestionarios, tic-tac-toe y otros juegos
  • Bots de medios que reproducen música o permiten a los usuarios crear o seleccionar videos, imágenes o GIF para compartir
  • Robots de encuestas para ayudar a los usuarios a crear y enviar encuestas
  • Bots de utilidad para automatizar las funciones del servidor, como responder preguntas frecuentes y más

Para obtener más información sobre los bots de Rust Discord, consulte algunos bots de ejemplo de Serenity Discord o la documentación de Serenity .

Fuente: https://blog.logrocket.com

#rust #discord #chatbot

Construyendo un bot de chat de Discord en Rust

Construire un chat bot Discord dans Rust

Apprenez à créer un bot Discord dans Rust avec Shuttle et Serenity. Apprenez à créer un bot dans Discord, ajoutez le bot à votre serveur et connectez votre code Rust à votre bot.

Les bots Discord peuvent faire gagner beaucoup de temps et d'efforts aux propriétaires de serveurs et aux membres du personnel tout en offrant une variété de fonctionnalités utiles aux utilisateurs. Vous pouvez utiliser des robots dans Discord pour automatiser les tâches répétitives et les tâches qui prendraient autrement beaucoup de temps et d'efforts.

Dans cet article, vous apprendrez à créer un bot dans Discord, à ajouter le bot à votre serveur et à connecter votre code Rust à votre bot.

Table des matières:

  • Configurer le bot Discord
    • Créer une application dans Discord
    • Créer un bot pour l'application
    • Installer le bot sur votre serveur Discord
  • Configuration de l'environnement de code Rust
  • Connecter la base de code Rust à votre bot Discord
  • Création de commandes pour le bot Discord
    • Activer le mode développeur sur votre compte Discord
    • Permettre à votre bot de répondre à une commande
  • Déployer le bot Discord sur le serveur Shuttle

Pour suivre cet article, vous avez besoin d'au moins un certain niveau de familiarité avec Discord. Vous devez également avoir un compte Discord, un serveur Discord que vous possédez et une certaine expérience de programmation avec Rust.


Configurer le bot Discord

Configurer le bot dans Discord peut être un peu délicat, surtout si c'est la première fois que vous le faites. Dans cette section, je vais vous guider dans la configuration du bot pour votre serveur.

Créer une application dans Discord

Une application Discord est un service qui fournit une interface entre les utilisateurs de Discord et votre code. L'interface fournie par l'application s'appelle un bot. Un bot reçoit des messages des utilisateurs et envoie une réponse.

Pour créer une application Discord, connectez-vous d'abord à votre compte Discord dans votre navigateur. Ensuite, ouvrez le portail des développeurs Discord dans votre navigateur et cliquez sur le bouton « Nouvelle application » en haut à droite de la page :

Portail des développeurs Discord en mode sombre avec bouton bleu pour créer une nouvelle application en haut à droite

Saisissez un nom pour votre application :

Invite à entrer le nom de l'application ou à vérifier avec le support Dev pour voir si l'application existe déjà

Cliquez sur le bouton intitulé "Créer" pour créer l'application. Si l'action se termine avec succès, vous serez accueilli par un tableau de bord qui ressemble à ceci :

Tableau de bord des applications Discord

Créer un bot pour l'application

Dans cette section, vous allez créer le bot pour votre application Discord. Dans le volet gauche de la page Web, cliquez sur "Bot" pour ouvrir le menu du bot :

Élément de menu Bot surligné en bleu dans la liste des paramètres

Sous la section "Build-A-Bot", cliquez sur le bouton "Add Bot" pour créer le bot :

Discord Build A Bot Section avec le bouton bleu pour ajouter un bot en haut à droite

Après avoir cliqué sur ce bouton, vous aurez créé avec succès le bot Discord. Pour finir, activez l'option « MESSAGE CONTENT INTENT » pour que le bot puisse recevoir des messages des utilisateurs de votre serveur Discord :

Option d'intention du contenu du message activée pour permettre au bot Discord de recevoir des messages des utilisateurs

Installer le bot sur votre serveur Discord

La dernière chose que vous devez faire pour configurer votre bot est de l'installer sur votre serveur. Dans le volet de navigation de gauche, cliquez sur l'élément de menu "OAuth2" pour basculer vers une liste déroulante. Dans ce menu déroulant, cliquez sur l'option "Générateur d'URL":

Élément de menu Oauth2 mis en surbrillance avec l'option de sous-menu du générateur d'URL Contour avec une boîte bleue plus claire

Dans le menu Générateur d'URL sous "SCOPES", cochez l'option "bot" :

Menu du générateur d'URL avec cases à cocher pour divers éléments sous les étendues avec l'option Bot cochée

Faites défiler la page jusqu'à "PERMISSIONS BOT" et cochez l'option "Administrateur" pour donner des privilèges d'administrateur au bot :

Sous-menu des autorisations de bot avec des éléments de case à cocher supplémentaires avec l'option administrateur cochée sous les autorisations générales

Faites défiler vers le bas de la page et copiez l'URL générée en bas, puis ouvrez l'URL générée dans votre navigateur :

Invite à sélectionner la destination du serveur pour l'installation de Discord Bot et les informations sur les autorisations

Dans la page Web qui s'ouvre après avoir navigué vers l'URL générée, sélectionnez le serveur sur lequel vous souhaitez installer le bot. Cliquez sur "Continuer" pour continuer.

Sur l'écran suivant, cliquez sur "Autoriser". La page Web vous demandera alors de vérifier que vous êtes un humain :

Écran de confirmation pour ajouter une application au serveur Discord

Lorsque vous avez terminé ces étapes, ouvrez la liste des membres de votre serveur. Vous devriez voir votre bot répertorié en tant que membre.

Configuration de l'environnement de code Rust

Dans cette section, je vais vous guider dans la configuration de l'environnement de code Rust pour votre bot Discord. L'environnement de code contiendra le code et les packages nécessaires pour vous permettre de commencer à créer le bot.

Pour configurer le projet, nous allons utiliser un outil appelé Shuttle. Shuttle vous permet d'initialiser, de construire et de déployer une variété de projets dans Rust.

Pour ce projet, nous utiliserons Shuttle pour initialiser un projet Serenity. Serenity est un framework pour créer des chatbots Discord dans Rust.

Pour initialiser le projet Serenity, créez un nouveau répertoire pour l'endroit où vous souhaitez placer votre projet. Ensuite, installez Shuttle avec la commande ci-dessous :

cargo install cargo-shuttle

Ensuite, initialisez un projet dans le répertoire :

cargo shuttle init --serenity

Enfin, construisez le projet :

cargo build

Si vous avez suivi ces étapes correctement, vous devriez voir votre répertoire rempli du code nécessaire pour démarrer.

Connecter la base de code Rust à votre bot Discord

Le src/lib.rscode - que nous avons généré dans la section précédente - est un projet de base que vous pouvez connecter à votre bot, ce que nous ferons étape par étape dans cette section.

Afin de connecter avec succès votre code à votre bot, vous devez d'abord obtenir votre jeton de bot. Un jeton de bot est une référence à votre bot. Chaque bot a une référence unique que vous pouvez utiliser pour connecter une base de code à votre bot.

Pour récupérer votre jeton de bot, ouvrez d'abord le tableau de bord du développeur Discord. Cliquez sur "Bot" dans le volet de navigation de gauche. Ensuite, cliquez sur le bouton "Réinitialiser le jeton":

Construire un écran de bot du tableau de bord du développeur Discord avec des informations sur l'application et un bouton pour réinitialiser le jeton

Cliquez sur "Copier" pour copier le jeton :

Construire un écran de bot du tableau de bord du développeur Discord avec un jeton généré pour connecter le code de rouille au bot Discord

Pour connecter la base de code à votre bot, créez un Secrets.tomlfichier dans le répertoire racine du projet. Écrivez ce qui suit dans le Secrets.tomlfichier et remplacez-le * bot_token *par votre jeton de bot :

DISCORD_TOKEN="* bot_token *"

Exécutez le projet avec cette commande :

cargo shuttle run

A la fin de ces étapes, vous devriez voir votre bot Discord en ligne sur votre serveur. Si vous tapez !hellosur le serveur, le bot devrait répondre avec world!.

Pour comprendre comment le bot répond à !hello, jetez un œil au gestionnaire d'événements des lignes 12 à 24 du src/lib.rsfichier :

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

Le gestionnaire d'événements a une messageméthode qui est appelée chaque fois que quelqu'un envoie un message sur le serveur. La messagefonction a un ifbloc vérifiant si le nouveau message dit !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

Si le message correspond à !hello, le programme renvoie le world!message au serveur avec cette instruction :

msg.channel_id.say(&ctx.http, "world!").await

Vous pouvez programmer le bot pour répondre à tous les messages personnalisés avec des réponses personnalisées en suivant les étapes ci-dessus.

Création de commandes pour le bot Discord

Les commandes sont un moyen plus direct d'interagir avec un bot. Contrairement aux messages, les commandes commencent par une /barre oblique — par exemple, /hello.

Vous pouvez envoyer des commandes dans Discord de la même manière que vous envoyez des messages, mais c'est le moyen préféré d'interagir avec les bots car vous pouvez facilement dire quels messages sont des commandes et quels messages ne le sont pas.

Pour permettre à votre bot de répondre aux commandes, vous aurez besoin de l'ID du serveur sur lequel vous avez installé le bot. Pour obtenir l'ID du serveur, vous devez d'abord activer le mode développeur sur votre compte.

Activer le mode développeur sur votre compte Discord

Le mode développeur est un paramètre Discord qui donne aux développeurs des privilèges élevés sur un serveur. Dans cette section, je vais vous guider dans l'activation du mode développeur sur votre système afin que vous puissiez copier votre ID de serveur et permettre à votre bot de répondre aux commandes.

Sur Windows ou Mac

En bas de votre fenêtre, cliquez sur l'icône des paramètres à côté de votre nom d'utilisateur. Dans le volet de gauche, sélectionnez "Apparence" sous "PARAMÈTRES DE L'APPLICATION".

Dans le menu des paramètres d'apparence, cliquez sur "Avancé" pour ouvrir le menu des paramètres avancés, où vous pouvez ensuite basculer l'option "Mode développeur". Enfin, cliquez avec le bouton droit sur le nom du serveur et sélectionnez "Copier l'ID" pour copier l'ID du serveur.

Sous Linux

En bas de votre fenêtre, cliquez sur l'icône des paramètres à côté de votre nom d'utilisateur. Dans le volet de gauche, sélectionnez "Avancé" sous "PARAMÈTRES DE L'APPLICATION" pour ouvrir le menu des paramètres avancés, où vous pouvez ensuite basculer l'option "Mode développeur".

Ensuite, cliquez avec le bouton droit sur le nom du serveur et sélectionnez "Copier l'ID" pour copier l'ID du serveur :

Paramètres avancés de l'application Discord activés en mode développeur avec le menu du serveur ouvert et l'option de copier l'identifiant du serveur en bas de la liste

Permettre à votre bot de répondre à une commande

Avec l'ID de serveur prêt, suivez ces étapes pour permettre à votre bot de répondre à une commande. Tout d'abord, écrivez la readyméthode ci-dessous dans le gestionnaire d'événements :

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Ensuite, écrivez le interaction_creategestionnaire ci-dessous dans le gestionnaire d'événements :

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

Dans la readyméthode du gestionnaire d'événements, remplacez * guild_id *sur la troisième ligne par votre ID de serveur.

Si votre code est toujours en cours d'exécution dans le terminal, redémarrez-le. Lorsque vous voyez votre bot en ligne sur votre serveur, envoyez un /hellomessage. Vous devriez voir une réponse du bot disant helloen réponse.

Comme pour les réponses aux messages, vous pouvez programmer votre bot pour qu'il réponde à toutes les commandes personnalisées avec des réponses personnalisées en suivant les étapes décrites ci-dessus.

Déployer le bot Discord sur le serveur Shuttle

L'exécution de votre projet sur votre système peut présenter des inconvénients. Des bots plus complexes peuvent nécessiter de grandes ressources pour fonctionner et servir chaque utilisateur.

Le déploiement de votre bot donne à votre bot l'avantage de ne pas utiliser les ressources de votre ordinateur pour s'exécuter. Il maintient également votre bot en ligne, même si vous ne l'êtes pas.

Shuttle vous permet de déployer votre bot sur le serveur Shuttle. Pour déployer votre bot, exécutez cette commande dans le répertoire de votre projet :

cargo shuttle deploy

Conclusion

Construire un chat bot Discord dans Rust peut être une tâche difficile. Mais avec les bonnes connaissances et les bons outils, cela peut être fait facilement.

Avec les instructions étape par étape fournies dans cet article, toute personne ayant une expérience de programmation dans Rust et un compte Discord peut apprendre à créer son propre chat bot Discord. Si vous cherchez des bots Discord à construire, voici quelques idées :

  • Welcome bots pour accueillir de nouveaux utilisateurs sur un serveur ou un canal
  • Robots de jeu pour jouer à des jeux-questionnaires, des quiz, des tic-tac-toe et d'autres jeux
  • Robots multimédias qui diffusent de la musique ou permettent aux utilisateurs de créer ou de sélectionner des vidéos, des images ou des GIF à partager
  • Des robots de sondage pour aider les utilisateurs à créer et envoyer des sondages
  • Bots utilitaires pour automatiser les fonctions du serveur telles que répondre aux FAQ et plus encore

Pour en savoir plus sur les bots Rust Discord, consultez quelques exemples de bots Serenity Discord ou la documentation Serenity .

Source : https://blog.logrocket.com

#rust #discord #chatbot

Construire un chat bot Discord dans Rust
曾 俊

曾 俊

1677148080

Rust で Discord チャット ボットを作成する

Shuttle と Serenity を使用して Rust で Discord ボットを作成する方法を学びます。Discord でボットを作成する方法、ボットをサーバーに追加する方法、および Rust コードをボットに接続する方法を学びます。

Discord ボットは、ユーザーにさまざまな便利な機能を提供しながら、サーバーの所有者とスタッフ メンバーの多くの時間と労力を節約できます。Discord でボットを使用して、反復的なタスクや、そうでなければ多くの時間と労力がかかるタスクを自動化できます。

この記事では、Discord でボットを作成し、ボットをサーバーに追加し、Rust コードをボットに接続する方法を学習します。

目次:

  • Discord ボットの設定
    • Discordでアプリケーションを作成する
    • アプリケーションのボットを作成する
    • ボットを Discord サーバーにインストールする
  • Rust コード環境のセットアップ
  • Rust コードベースを Discord ボットに接続する
  • Discord ボットのコマンドの作成
    • Discord アカウントで開発者モードを有効にする
    • ボットがコマンドに応答できるようにする
  • Discord ボットを Shuttle サーバーにデプロイする

この記事を読み進めるには、少なくともある程度の Discord の知識が必要です。また、Discord アカウント、所有する Discord サーバー、および Rust のプログラミング経験も必要です。


Discord ボットの設定

Discord でボットをセットアップするのは、特にこれが初めての場合は少し難しい場合があります。このセクションでは、サーバー用にボットをセットアップする方法について説明します。

Discordでアプリケーションを作成する

Discord アプリケーションは、Discord ユーザーとコードの間のインターフェースを提供するサービスです。アプリケーションが提供するインターフェースはボットと呼ばれます。ボットはユーザーからメッセージを受信し、応答を送信します。

Discord アプリケーションを作成するには、まずブラウザで Discord アカウントにログインします。次に、ブラウザでDiscord 開発者ポータルを開き、ページの右上にある [新しいアプリケーション] というラベルの付いたボタンをクリックします。

右上に新しいアプリケーションを作成するための青いボタンがあるダークモードの Discord 開発者ポータル

アプリケーションの名前を入力してください:

アプリケーションの名前を入力するか、Dev Support に確認してアプリケーションが既に存在するかどうかを確認するように求められます

「作成」というラベルの付いたボタンをクリックして、アプリケーションを作成します。アクションが正常に完了すると、次のようなダッシュボードが表示されます。

Discord アプリケーション ダッシュボード

アプリケーションのボットを作成する

このセクションでは、Discord アプリケーションのボットを作成します。Web ページの左側のペインで、[ボット] をクリックしてボット メニューを開きます。

設定リストで青色で強調表示されているボット メニュー項目

「Build-A-Bot」セクションで、「Add Bot」ボタンをクリックしてボットを作成します。

Discordは、右上にボットを追加するための青いボタンでボットセクションを構築します

このボタンをクリックすると、Discord ボットが正常に作成されます。最後に、「MESSAGE CONTENT INTENT」オプションを有効にして、ボットが Discord サーバーのユーザーからメッセージを受信できるようにします。

Discordボットがユーザーからメッセージを受信できるように、メッセージコンテンツの意図オプションをオンに切り替えました

ボットを Discord サーバーにインストールする

ボットの設定で最後に行う必要があるのは、ボットをサーバーにインストールすることです。左側のナビゲーション ペインで、[OAuth2] メニュー項目をクリックしてドロップダウンを切り替えます。このドロップダウンで、「URL ジェネレーター」オプションをクリックします。

URL ジェネレーターで強調表示された Oauth2 メニュー項目 サブメニュー オプション アウトラインと明るい青色のボックス

[スコープ] の下の URL ジェネレーター メニューで、[ボット] オプションにチェックを入れます。

ボットオプションがチェックされたスコープの下のさまざまなアイテムのチェックボックスを備えた URL ジェネレーターメニュー

ページをさらに「BOT PERMISSIONS」までスクロールし、「管理者」オプションにチェックマークを付けて、ボットに管理者権限を付与します。

ボットのアクセス許可サブメニューと追加のチェックボックス項目があり、一般アクセス許可の下で管理者オプションがチェックされている

ページの下部までスクロールし、生成された URL を下部にコピーしてから、生成された URL をブラウザーで開きます。

Discord ボットのインストール先サーバーの選択と権限に関する情報を求めるプロンプト

In the webpage that opens after you navigate to the generated URL, select the server that you want to install the bot in. Click “Continue” to proceed.

On the next screen, click “Authorize.” The webpage will then prompt you to verify that you are human:

Discordサーバーへのアプリ追加確認画面

When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.

Setting up the Rust code environment

In this section, I’ll guide you through setting up the Rust code environment for your Discord bot. The code environment will have the necessary code and packages for you to get started with building the bot.

To set up the project, we’ll use a tool called Shuttle. Shuttle lets you initialize, build, and deploy a variety of projects in Rust.

For this project, we’ll use Shuttle to initialize a Serenity project. Serenity is a framework for building Discord chat bots in Rust.

To initialize the Serenity project, create a new directory for where you want your project to be. Then, install Shuttle with the command below:

cargo install cargo-shuttle

Next, initialize a project in the directory:

cargo shuttle init --serenity

Finally, build the project:

cargo build

If you followed these steps correctly, you should see your directory filled with the necessary code for getting started.

Connecting the Rust codebase to your Discord bot

The src/lib.rs code — which we generated in the previous section — is a basic project that you can connect to your bot, which we will do step-by-step in this section.

In order to successfully connect your code to your bot, you first need to get your bot token. A bot token is a reference to your bot. Every bot has a unique reference that you can use to connect a codebase to your bot.

To retrieve your bot token, first open the Discord developer dashboard. Click “Bot” on the left navigation pane. Then, click the “Reset Token” button:

アプリケーション情報とトークンをリセットするボタンを備えた Discord 開発者ダッシュボードのボット画面を構築する

Click “Copy” to copy the token:

生成されたトークンを使用して Discord 開発者ダッシュボードのボット画面を構築し、Rust コードを Discord ボットに接続します

To connect the code base to your bot, create a Secrets.toml file in the project’s root directory. Write the following into the Secrets.toml file and replace * bot_token * with your bot token:

DISCORD_TOKEN="* bot_token *"

Run the project with this command:

cargo shuttle run

At the end of these steps, you should see your Discord bot online on your server. If you type !hello on the server, the bot should respond with world!.

To understand how the bot responds to !hello, take a look at the event handler from lines 12–24 of the src/lib.rs file:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

The event handler has a message method that gets called anytime someone sends a message on the server. The message function has an if block checking if the new message says !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

If the message matches !hello, the program sends the world! message back to the server with this statement:

msg.channel_id.say(&ctx.http, "world!").await

You can program the bot to respond to any custom messages with custom responses following the steps above.

Creating commands for the Discord bot

Commands are a more direct way to interact with a bot. Unlike messages, commands begin with a / slash — e.g., /hello.

You can send commands in Discord the same way you send messages, but they are the preferred way of interacting with bots because you can easily tell what messages are commands and what messages are not.

To allow your bot to respond to commands, you’ll need the ID of the server in which you installed the bot. In order to get the server ID, you need to enable developer mode on your account first.

Enabling developer mode on your Discord account

Developer mode is a Discord setting that gives developers elevated privileges in a server. In this section, I’ll guide you through enabling developer mode on your system so you can copy your server ID and enable your bot to respond to commands.

On Windows or Mac

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Appearance” under “APP SETTINGS.”

外観設定メニューで、「詳細」をクリックして詳細設定メニューを開き、「開発者モード」オプションを切り替えることができます。最後に、サーバー名を右クリックし、「ID のコピー」を選択してサーバー ID をコピーします。

Linux の場合

ウィンドウの下部で、ユーザー名の近くにある設定アイコンをクリックします。左側のペインで、「アプリ設定」の下の「詳細」を選択して詳細設定メニューを開き、「開発者モード」オプションを切り替えることができます。

次に、サーバー名を右クリックし、[ID のコピー] を選択してサーバー ID をコピーします。

Discordの高度なアプリ設定が開発者モードで有効になり、サーバーメニューが開き、リストの下部にあるサーバーIDをコピーするオプションが表示されます

ボットがコマンドに応答できるようにする

サーバー ID の準備ができたら、次の手順に従って、ボットがコマンドに応答できるようにします。まず、ready以下のメソッドをイベント ハンドラに記述します。

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

次に、interaction_create以下のハンドラーをイベント ハンドラーに記述します。

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

readyイベント ハンドラーのメソッドで、 * guild_id *3 行目をサーバー ID に置き換えます。

コードがまだターミナルで実行されている場合は、再起動します。サーバー上でボットがオンラインになったら、/helloメッセージを送信します。応答で言っているボットからの応答が表示されますhello

メッセージ応答と同様に、上記の手順に従って、カスタム応答でカスタム コマンドに応答するようにボットをプログラムできます。

Discord ボットを Shuttle サーバーにデプロイする

システムでプロジェクトを実行すると、欠点が生じる可能性があります。より複雑なボットを実行してすべてのユーザーにサービスを提供するには、大きなリソースが必要になる場合があります。

ボットをデプロイすると、コンピューターのリソースを使用して実行されないという利点がボットにもたらされます。また、そうでない場合でも、ボットをオンラインに保ちます。

Shuttle を使用すると、ボットを Shuttle サーバーにデプロイできます。ボットをデプロイするには、プロジェクト ディレクトリで次のコマンドを実行します。

cargo shuttle deploy

結論

Rust で Discord チャット ボットを構築するのは、困難な作業になる可能性があります。しかし、正しい知識とツールがあれば、簡単に行うことができます。

この記事に記載されている段階的な手順を使用すると、Rust でのプログラミング経験があり、Discord アカウントを持っている人なら誰でも、独自の Discord チャット ボットの作成方法を学ぶことができます。作成する Discord ボットを探している場合は、いくつかのアイデアがあります。

  • 新しいユーザーをサーバーまたはチャネルに歓迎するウェルカム ボット
  • トリビア、クイズ、三目並べ、その他のゲームをプレイするためのゲーム ボット
  • 音楽を再生したり、ユーザーがビデオ、画像、GIF を作成または選択して共有できるようにするメディア ボット
  • ボットを投票して、ユーザーが投票を作成して送信できるようにする
  • FAQ への回答などのサーバー機能を自動化するためのユーティリティ ボット

Rust Discord ボットの詳細については、Serenity Discord のサンプル ボットまたはSerenity のドキュメントを参照してください。

ソース: https://blog.logrocket.com

#rust #discord #chatbot

Rust で Discord チャット ボットを作成する

Создание чат-бота Discord в Rust

Узнайте, как создать бота Discord в Rust с помощью Shuttle и Serenity. Узнайте, как создать бота в Discord, добавить бота на свой сервер и подключить свой код Rust к вашему боту.

Боты Discord могут сэкономить владельцам серверов и сотрудникам много времени и усилий, а также предоставить пользователям множество полезных функций. Вы можете использовать ботов в Discord для автоматизации повторяющихся задач и задач, которые в противном случае отняли бы много времени и усилий.

В этой статье вы узнаете, как создать бота в Discord, добавить бота на свой сервер и подключить свой код Rust к вашему боту.

Оглавление:

  • Настройка бота в дискорде
    • Создание приложения в Discord
    • Создание бота для приложения
    • Установка бота на свой Discord сервер
  • Настройка среды кода Rust
  • Подключение кодовой базы Rust к вашему боту Discord
  • Создание команд для Discord-бота
    • Включение режима разработчика в вашей учетной записи Discord
    • Включение вашего бота для ответа на команду
  • Развертывание бота Discord на сервере Shuttle

Чтобы следовать этой статье, вам необходимо хотя бы немного познакомиться с Discord. У вас также должна быть учетная запись Discord, собственный сервер Discord и некоторый опыт программирования на Rust.


Настройка бота в дискорде

Настройка бота в Discord может быть немного сложной, особенно если вы делаете это впервые. В этом разделе я проведу вас через настройку бота для вашего сервера.

Создание приложения в Discord

Приложение Discord — это служба, которая обеспечивает интерфейс между пользователями Discord и вашим кодом. Интерфейс, который предоставляет приложение, называется ботом. Бот получает сообщения от пользователей и отправляет ответ.

Чтобы создать приложение Discord, сначала войдите в свою учетную запись Discord в браузере. Затем откройте портал разработчика Discord в своем браузере и нажмите кнопку «Новое приложение» в правом верхнем углу страницы:

Портал разработчиков Discord в темном режиме с синей кнопкой для создания нового приложения в правом верхнем углу

Введите имя для вашего приложения:

Предложите ввести имя для приложения или обратитесь в службу поддержки разработчиков, чтобы узнать, существует ли приложение

Нажмите кнопку «Создать», чтобы создать приложение. Если действие завершится успешно, вы увидите панель инструментов, которая выглядит следующим образом:

Панель управления приложения Discord

Создание бота для приложения

В этом разделе вы создадите бота для своего приложения Discord. На левой панели веб-страницы нажмите «Бот», чтобы открыть меню бота:

Пункт меню бота выделен синим цветом в списке настроек

В разделе «Build-A-Bot» нажмите кнопку «Добавить бота», чтобы создать бота:

Discord Создайте раздел бота с синей кнопкой, чтобы добавить бота вверху справа

После нажатия этой кнопки вы успешно создали бота Discord. Чтобы закончить, активируйте опцию «MESSAGE CONTENT INTENT», чтобы бот мог получать сообщения от пользователей на вашем сервере Discord:

Опция намерения содержимого сообщения включена, чтобы разрешить боту Discord получать сообщения от пользователей

Установка бота на свой Discord сервер

Последнее, что вам нужно сделать при настройке бота, это установить его на свой сервер. На левой панели навигации щелкните пункт меню «OAuth2», чтобы открыть раскрывающийся список. В этом раскрывающемся списке выберите опцию «Генератор URL»:

Пункт меню Oauth2, выделенный параметром подменю генератора URL-адресов, контур с более светлой синей рамкой

В меню «Генератор URL-адресов» в разделе «ОБЛАСТИ» отметьте опцию «бот»:

Меню генератора URL-адресов с флажками для различных элементов в областях действия с отмеченным параметром бота

Прокрутите страницу вниз до «РАЗРЕШЕНИЯ БОТА» и отметьте опцию «Администратор», чтобы предоставить боту права администратора:

Подменю «Разрешения бота» с дополнительными элементами флажка с установленным флажком «Администратор» в разделе «Общие разрешения»

Прокрутите страницу вниз и скопируйте сгенерированный URL-адрес внизу, затем откройте сгенерированный URL-адрес в браузере:

Запрос на выбор целевого сервера для установки бота Discord и информации о разрешениях

На веб-странице, которая откроется после перехода к сгенерированному URL-адресу, выберите сервер, на который вы хотите установить бота. Нажмите «Продолжить», чтобы продолжить.

На следующем экране нажмите «Авторизовать». Затем веб-страница предложит вам подтвердить, что вы человек:

Экран подтверждения добавления приложения на сервер Discord

Когда вы закончите с этими шагами, откройте список участников вашего сервера. Вы должны увидеть своего бота в списке участников.

Настройка среды кода Rust

В этом разделе я проведу вас через настройку среды кода Rust для вашего бота Discord. Среда кода будет содержать необходимый код и пакеты, чтобы вы могли приступить к созданию бота.

Для настройки проекта мы будем использовать инструмент под названием Shuttle. Shuttle позволяет вам инициализировать, создавать и развертывать различные проекты на Rust.

В этом проекте мы будем использовать Shuttle для инициализации проекта Serenity. Serenity — это фреймворк для создания чат-ботов Discord на Rust.

Чтобы инициализировать проект Serenity, создайте новый каталог, в котором вы хотите разместить свой проект. Затем установите Shuttle с помощью следующей команды:

cargo install cargo-shuttle

Затем инициализируйте проект в каталоге:

cargo shuttle init --serenity

Наконец, соберите проект:

cargo build

Если вы правильно выполнили эти шаги, вы должны увидеть, что ваш каталог заполнен необходимым кодом для начала работы.

Подключение кодовой базы Rust к вашему боту Discord

Код src/lib.rs, который мы сгенерировали в предыдущем разделе, — это базовый проект, который вы можете подключить к своему боту, что мы и сделаем шаг за шагом в этом разделе.

Чтобы успешно подключить свой код к боту, вам сначала нужно получить токен бота. Токен бота — это ссылка на вашего бота. У каждого бота есть уникальная ссылка, которую вы можете использовать для подключения базы кода к вашему боту.

Чтобы получить токен бота, сначала откройте панель разработчика Discord. Нажмите «Бот» на левой панели навигации. Затем нажмите кнопку «Сбросить токен»:

Создайте экран бота на панели инструментов разработчика Discord с информацией о приложении и кнопкой для сброса токена

Нажмите «Копировать», чтобы скопировать токен:

Создайте экран панели инструментов разработчика Discord с сгенерированным токеном для подключения кода Rust к боту Discord

Чтобы подключить кодовую базу к вашему боту, создайте Secrets.tomlфайл в корневом каталоге проекта. Напишите в файл следующее Secrets.tomlи замените * bot_token *токеном вашего бота:

DISCORD_TOKEN="* bot_token *"

Запустите проект с помощью этой команды:

cargo shuttle run

В конце этих шагов вы должны увидеть своего бота Discord онлайн на своем сервере. Если вы наберете !helloна сервере, бот должен ответить world!.

Чтобы понять, как бот реагирует на !hello, взгляните на обработчик событий из строк 12–24 файла src/lib.rs:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

У обработчика событий есть messageметод, который вызывается всякий раз, когда кто-то отправляет сообщение на сервер. Функция messageимеет ifблок, проверяющий, говорит ли новое сообщение !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

Если сообщение соответствует !hello, программа отправляет world!сообщение обратно на сервер с помощью этого оператора:

msg.channel_id.say(&ctx.http, "world!").await

Вы можете запрограммировать бота, чтобы он отвечал на любые настраиваемые сообщения с помощью настраиваемых ответов, выполнив шаги, описанные выше.

Создание команд для Discord-бота

Команды — это более прямой способ взаимодействия с ботом. В отличие от сообщений, команды начинаются с /косой черты — например, /hello.

Вы можете отправлять команды в Discord так же, как вы отправляете сообщения, но они являются предпочтительным способом взаимодействия с ботами, потому что вы можете легко определить, какие сообщения являются командами, а какие нет.

Чтобы ваш бот мог отвечать на команды, вам понадобится идентификатор сервера, на котором вы установили бота. Чтобы получить идентификатор сервера, вам необходимо сначала включить режим разработчика в своей учетной записи.

Включение режима разработчика в вашей учетной записи Discord

Режим разработчика — это параметр Discord, который дает разработчикам повышенные привилегии на сервере. В этом разделе я расскажу вам, как включить режим разработчика в вашей системе, чтобы вы могли скопировать идентификатор своего сервера и разрешить боту отвечать на команды.

В Windows или Mac

В нижней части окна щелкните значок настроек рядом с вашим именем пользователя. На левой панели выберите «Внешний вид» в разделе «НАСТРОЙКИ ПРИЛОЖЕНИЯ».

В меню настроек внешнего вида нажмите «Дополнительно», чтобы открыть меню дополнительных настроек, где вы можете переключить опцию «Режим разработчика». Наконец, щелкните правой кнопкой мыши имя сервера и выберите «Копировать идентификатор», чтобы скопировать идентификатор сервера.

В Linux

В нижней части окна щелкните значок настроек рядом с вашим именем пользователя. На левой панели выберите «Дополнительно» в разделе «НАСТРОЙКИ ПРИЛОЖЕНИЯ», чтобы открыть меню дополнительных настроек, где затем можно переключить параметр «Режим разработчика».

Затем щелкните правой кнопкой мыши имя сервера и выберите «Копировать идентификатор», чтобы скопировать идентификатор сервера:

Расширенные настройки приложения Discord включены в режиме разработчика с открытым меню сервера и возможностью копирования идентификатора сервера в нижней части списка

Включение вашего бота для ответа на команду

Подготовив идентификатор сервера, выполните следующие действия, чтобы ваш бот мог реагировать на команду. Во-первых, напишите readyметод ниже в обработчике события:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Затем interaction_createв обработчик события впишите обработчик ниже:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

В readyметоде обработчика события замените * guild_id *в третьей строке идентификатор вашего сервера.

Если ваш код все еще работает в терминале, перезапустите его. Когда вы увидите своего бота онлайн на своем сервере, отправьте сообщение /hello. Вы должны увидеть ответ от бота, говорящего helloв ответ.

Как и в случае с ответами на сообщения, вы можете запрограммировать своего бота так, чтобы он отвечал на любые настраиваемые команды с помощью настраиваемых ответов, выполнив шаги, описанные выше.

Развертывание бота Discord на сервере Shuttle

Запуск вашего проекта в вашей системе может иметь недостатки. Более сложные боты могут потребовать больших ресурсов для запуска и обслуживания каждого пользователя.

Развертывание вашего бота дает вашему боту преимущество, заключающееся в том, что он не использует ресурсы вашего компьютера для работы. Это также держит вашего бота в сети, даже если вы этого не делаете.

Shuttle позволяет развернуть вашего бота на сервере Shuttle. Чтобы развернуть бота, запустите эту команду в каталоге вашего проекта:

cargo shuttle deploy

Заключение

Создание чат-бота Discord на Rust может оказаться непростой задачей. Но при наличии необходимых знаний и инструментов это можно сделать легко.

С помощью пошаговых инструкций, представленных в этой статье, любой, у кого есть опыт программирования на Rust и учетная запись Discord, может научиться создавать собственного чат-бота Discord. Если вы ищете ботов для Discord, вот несколько идей:

  • Приветственные боты, приветствующие новых пользователей на сервере или канале.
  • Игровые боты для викторин, викторин, крестиков-ноликов и других игр
  • Медиа-боты, которые воспроизводят музыку или позволяют пользователям создавать или выбирать видео, изображения или GIF-файлы для обмена
  • Боты для опросов, помогающие пользователям создавать и отправлять опросы
  • Служебные боты для автоматизации функций сервера, таких как ответы на часто задаваемые вопросы и многое другое.

Чтобы узнать больше о ботах Rust Discord, ознакомьтесь с некоторыми примерами ботов Serenity Discord или документацией Serenity .

Источник: https://blog.logrocket.com

#rust #discord #chatbot

Создание чат-бота Discord в Rust
최  호민

최 호민

1677140723

Rust에서 Discord 채팅 봇 만들기

Shuttle 및 Serenity를 사용하여 Rust에서 Discord 봇을 구축하는 방법을 알아보세요. Discord에서 봇을 만들고, 서버에 봇을 추가하고, Rust 코드를 봇에 연결하는 방법을 알아보세요.

Discord 봇은 서버 소유자와 직원의 시간과 노력을 많이 절약하는 동시에 사용자에게 다양한 유용한 기능을 제공할 수 있습니다. Discord에서 봇을 사용하여 반복적인 작업과 많은 시간과 노력이 필요한 작업을 자동화할 수 있습니다.

이 기사에서는 Discord에서 봇을 만들고, 서버에 봇을 추가하고, Rust 코드를 봇에 연결하는 방법을 배웁니다.

목차:

  • 디스코드 봇 설정
    • Discord에서 애플리케이션 만들기
    • 애플리케이션용 봇 만들기
    • Discord 서버에 봇 설치
  • Rust 코드 환경 설정
  • Rust 코드베이스를 Discord 봇에 연결하기
  • Discord 봇용 명령 만들기
    • Discord 계정에서 개발자 모드 활성화
    • 봇이 명령에 응답하도록 활성화
  • Shuttle 서버에 Discord 봇 배포

이 기사를 따라하려면 최소한 Discord에 어느 정도 익숙해야 합니다. 또한 Discord 계정, 소유한 Discord 서버 및 Rust에 대한 약간의 프로그래밍 경험이 있어야 합니다.


디스코드 봇 설정

Discord에서 봇을 설정하는 것은 약간 까다로울 수 있습니다. 특히 처음 하는 경우에는 더욱 그렇습니다. 이 섹션에서는 서버용 봇 설정 과정을 안내합니다.

Discord에서 애플리케이션 만들기

Discord 애플리케이션은 Discord 사용자와 코드 간의 인터페이스를 제공하는 서비스입니다. 애플리케이션이 제공하는 인터페이스를 봇이라고 합니다. 봇은 사용자로부터 메시지를 받고 응답을 보냅니다.

Discord 애플리케이션을 만들려면 먼저 브라우저에서 Discord 계정에 로그인하세요. 그런 다음 브라우저에서 Discord 개발자 포털을 열고 페이지 오른쪽 상단에 있는 "새 애플리케이션" 버튼을 클릭합니다.

오른쪽 상단에 새 애플리케이션을 생성하기 위한 파란색 버튼이 있는 다크 모드의 Discord 개발자 포털

애플리케이션 이름 입력:

응용 프로그램의 이름을 입력하라는 메시지를 표시하거나 앱이 이미 존재하는지 확인하기 위해 개발자 지원에 확인

"만들기"라고 표시된 버튼을 클릭하여 애플리케이션을 만듭니다. 작업이 성공적으로 완료되면 다음과 같은 대시보드가 ​​표시됩니다.

Discord 애플리케이션 대시보드

애플리케이션용 봇 만들기

이 섹션에서는 Discord 애플리케이션용 봇을 만듭니다. 웹 페이지의 왼쪽 창에서 "봇"을 클릭하여 봇 메뉴를 엽니다.

설정 목록에서 파란색으로 강조 표시된 봇 메뉴 항목

"Build-A-Bot" 섹션에서 "Add Bot" 버튼을 클릭하여 봇을 생성합니다.

Discord는 오른쪽 상단에 봇을 추가하기 위해 파란색 버튼으로 봇 섹션을 구축합니다.

이 버튼을 클릭하면 Discord 봇이 성공적으로 생성됩니다. 마무리하려면 봇이 Discord 서버의 사용자로부터 메시지를 받을 수 있도록 "MESSAGE CONTENT INTENT" 옵션을 활성화합니다.

Discord 봇이 사용자로부터 메시지를 수신할 수 있도록 메시지 콘텐츠 의도 옵션이 켜짐

Discord 서버에 봇 설치

봇 설정에서 마지막으로 해야 할 일은 서버에 설치하는 것입니다. 왼쪽 탐색 창에서 "OAuth2" 메뉴 항목을 클릭하여 드롭다운을 전환합니다. 이 드롭다운에서 "URL 생성기" 옵션을 클릭합니다.

URL 생성기 하위 메뉴 옵션 개요로 강조 표시된 Oauth2 메뉴 항목 밝은 파란색 상자

"범위" 아래의 URL 생성기 메뉴에서 "봇" 옵션을 선택합니다.

봇 옵션이 선택된 범위 내 다양한 ​​항목에 대한 확인란이 있는 URL 생성기 메뉴

"BOT PERMISSIONS"까지 페이지를 더 아래로 스크롤하고 "Administrator" 옵션을 선택하여 봇 관리자 권한을 부여합니다.

일반 권한에서 선택된 관리자 옵션이 있는 추가 확인란 항목이 있는 봇 권한 하위 메뉴

페이지 하단으로 스크롤하여 하단에 생성된 URL을 복사한 다음 브라우저에서 생성된 URL을 엽니다.

Discord Bot 설치 및 권한에 대한 정보를 위한 서버 대상을 선택하라는 메시지 표시

In the webpage that opens after you navigate to the generated URL, select the server that you want to install the bot in. Click “Continue” to proceed.

On the next screen, click “Authorize.” The webpage will then prompt you to verify that you are human:

Discord 서버에 애플리케이션을 추가하기 위한 확인 화면

When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.

Setting up the Rust code environment

In this section, I’ll guide you through setting up the Rust code environment for your Discord bot. The code environment will have the necessary code and packages for you to get started with building the bot.

To set up the project, we’ll use a tool called Shuttle. Shuttle lets you initialize, build, and deploy a variety of projects in Rust.

For this project, we’ll use Shuttle to initialize a Serenity project. Serenity is a framework for building Discord chat bots in Rust.

To initialize the Serenity project, create a new directory for where you want your project to be. Then, install Shuttle with the command below:

cargo install cargo-shuttle

Next, initialize a project in the directory:

cargo shuttle init --serenity

Finally, build the project:

cargo build

If you followed these steps correctly, you should see your directory filled with the necessary code for getting started.

Connecting the Rust codebase to your Discord bot

The src/lib.rs code — which we generated in the previous section — is a basic project that you can connect to your bot, which we will do step-by-step in this section.

In order to successfully connect your code to your bot, you first need to get your bot token. A bot token is a reference to your bot. Every bot has a unique reference that you can use to connect a codebase to your bot.

To retrieve your bot token, first open the Discord developer dashboard. Click “Bot” on the left navigation pane. Then, click the “Reset Token” button:

애플리케이션 정보와 토큰 재설정 버튼이 있는 Discord 개발자 대시보드의 봇 화면 구축

Click “Copy” to copy the token:

Rust 코드를 Discord 봇에 연결하기 위해 생성된 토큰으로 Discord 개발자 대시보드의 봇 화면 구축

To connect the code base to your bot, create a Secrets.toml file in the project’s root directory. Write the following into the Secrets.toml file and replace * bot_token * with your bot token:

DISCORD_TOKEN="* bot_token *"

Run the project with this command:

cargo shuttle run

At the end of these steps, you should see your Discord bot online on your server. If you type !hello on the server, the bot should respond with world!.

To understand how the bot responds to !hello, take a look at the event handler from lines 12–24 of the src/lib.rs file:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

The event handler has a message method that gets called anytime someone sends a message on the server. The message function has an if block checking if the new message says !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

If the message matches !hello, the program sends the world! message back to the server with this statement:

msg.channel_id.say(&ctx.http, "world!").await

You can program the bot to respond to any custom messages with custom responses following the steps above.

Creating commands for the Discord bot

Commands are a more direct way to interact with a bot. Unlike messages, commands begin with a / slash — e.g., /hello.

메시지를 보내는 것과 같은 방식으로 Discord에서 명령을 보낼 수 있지만 어떤 메시지가 명령이고 어떤 메시지가 아닌지 쉽게 알 수 있기 때문에 봇과 상호 작용하는 데 선호되는 방법입니다.

봇이 명령에 응답하도록 하려면 봇을 설치한 서버의 ID가 필요합니다. 서버 ID를 얻으려면 먼저 계정에서 개발자 모드를 활성화해야 합니다.

Discord 계정에서 개발자 모드 활성화

개발자 모드는 개발자에게 서버에서 높은 권한을 부여하는 Discord 설정입니다. 이 섹션에서는 서버 ID를 복사하고 봇이 명령에 응답할 수 있도록 시스템에서 개발자 모드를 활성화하는 방법을 안내합니다.

Windows 또는 Mac에서

창 하단에서 사용자 이름 옆에 있는 설정 아이콘을 클릭합니다. 왼쪽 창에서 "앱 설정" 아래의 "모양"을 선택합니다.

In the appearance settings menu, click “Advanced” to open the advanced settings menu, where you can then toggle the “Developer Mode” option. Finally, right-click the server name and select “Copy ID” to copy the server ID.

On Linux

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Advanced” under “APP SETTINGS” to open the advanced settings menu, where you can then toggle the “Developer Mode” option.

Then, right-click the server name and select “Copy ID” to copy the server ID:

서버 메뉴가 열려 있고 목록 맨 아래에 서버 ID를 복사하는 옵션이 있는 개발자 모드에서 Discord 고급 앱 설정이 활성화됨

Enabling your bot to respond to a command

With the server ID ready, follow these steps to enable your bot to respond to a command. First, write the ready method below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Next, write the interaction_create handler below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

ready이벤트 처리기의 메서드 에서 * guild_id *세 번째 줄을 서버 ID로 바꿉니다.

코드가 여전히 터미널에서 실행 중이면 다시 시작하세요. 서버에서 온라인으로 봇이 보이면 메시지를 보내십시오 /hello. hello응답으로 말하는 봇의 응답이 표시되어야 합니다 .

메시지 응답과 마찬가지로 위에서 다룬 단계에 따라 사용자 지정 응답으로 모든 사용자 지정 명령에 응답하도록 봇을 프로그래밍할 수 있습니다.

Shuttle 서버에 Discord 봇 배포

시스템에서 프로젝트를 실행하면 단점이 있을 수 있습니다. 더 복잡한 봇은 모든 사용자를 실행하고 제공하기 위해 더 큰 리소스가 필요할 수 있습니다.

봇을 배포하면 컴퓨터 리소스를 사용하지 않고 실행할 수 있다는 이점이 봇에 제공됩니다. 또한 사용자가 아닌 경우에도 봇을 온라인 상태로 유지합니다.

Shuttle을 사용하면 Shuttle 서버에 봇을 배포할 수 있습니다. 봇을 배포하려면 프로젝트 디렉터리에서 다음 명령을 실행합니다.

cargo shuttle deploy

결론

Rust에서 Discord 채팅 봇을 구축하는 것은 어려운 작업이 될 수 있습니다. 그러나 올바른 지식과 도구를 사용하면 쉽게 수행할 수 있습니다.

이 기사에 제공된 단계별 지침을 통해 Rust 프로그래밍 경험과 Discord 계정이 있는 사람은 누구나 자신만의 Discord 채팅 봇을 구축하는 방법을 배울 수 있습니다. 빌드할 Discord 봇을 찾고 있다면 다음과 같은 몇 가지 아이디어가 있습니다.

  • 서버 또는 채널에 새로운 사용자를 환영하는 환영 봇
  • 퀴즈, 퀴즈, 틱택토 및 기타 게임을 플레이하기 위한 게임 봇
  • 음악을 재생하거나 사용자가 공유할 비디오, 이미지 또는 GIF를 만들거나 선택할 수 있도록 하는 미디어 봇
  • 사용자가 설문 조사를 만들고 보내는 데 도움이 되는 설문 조사 봇
  • FAQ 응답 등과 같은 서버 기능 자동화를 위한 유틸리티 봇

Rust Discord 봇에 대한 자세한 내용은 Serenity Discord 예제 봇 또는 Serenity 문서를 확인하세요 .

출처: https://blog.logrocket.com

#rust #discord #chatbot

Rust에서 Discord 채팅 봇 만들기
Mélanie  Faria

Mélanie Faria

1677136860

Construindo um Discord Chat Bot em Rust

Aprenda a construir um bot Discord em Rust com Shuttle e Serenity. Aprenda a criar um bot no Discord, adicione o bot ao seu servidor e conecte seu código Rust ao seu bot.

Os bots do Discord podem economizar muito tempo e esforço dos proprietários de servidores e membros da equipe, além de fornecer uma variedade de recursos úteis aos usuários. Você pode usar bots no Discord para automatizar tarefas repetitivas e tarefas que, de outra forma, levariam muito tempo e esforço.

Neste artigo, você aprenderá como criar um bot no Discord, adicionar o bot ao seu servidor e conectar seu código Rust ao seu bot.

Índice:

  • Configurando o bot do Discord
    • Criando um aplicativo no Discord
    • Criando um bot para o aplicativo
    • Instalando o bot no seu servidor Discord
  • Configurando o ambiente de código Rust
  • Conectando a base de código Rust ao seu bot do Discord
  • Criando comandos para o bot do Discord
    • Ativando o modo de desenvolvedor na sua conta do Discord
    • Habilitando seu bot para responder a um comando
  • Implantando o bot do Discord no servidor Shuttle

Para acompanhar este artigo, você precisa de pelo menos algum nível de familiaridade com o Discord. Você também deve ter uma conta Discord, um servidor Discord de sua propriedade e alguma experiência em programação com Rust.


Configurando o bot do Discord

Configurar o bot no Discord pode ser um pouco complicado, especialmente se for a primeira vez que o faz. Nesta seção, orientarei você na configuração do bot para seu servidor.

Criando um aplicativo no Discord

Um aplicativo Discord é um serviço que fornece uma interface entre os usuários do Discord e seu código. A interface que o aplicativo fornece é chamada de bot. Um bot recebe mensagens de usuários e envia uma resposta.

Para criar um aplicativo Discord, primeiro faça login em sua conta Discord em seu navegador. Em seguida, abra o portal do desenvolvedor do Discord em seu navegador e clique no botão "Novo aplicativo" no canto superior direito da página:

Portal do desenvolvedor do Discord no modo escuro com botão azul para criar um novo aplicativo no canto superior direito

Digite um nome para seu aplicativo:

Solicitar para inserir o nome do aplicativo ou verificar com o suporte do desenvolvedor para ver se o aplicativo já existe

Clique no botão “Criar” para criar o aplicativo. Se a ação for concluída com sucesso, você verá um painel semelhante a este:

Painel de aplicativos do Discord

Criando um bot para o aplicativo

Nesta seção, você criará o bot para seu aplicativo Discord. No painel esquerdo da página da Web, clique em “Bot” para abrir o menu do bot:

Item de menu do bot destacado em azul na lista de configurações

Na seção “Build-A-Bot”, clique no botão “Add Bot” para criar o bot:

Discord Crie uma seção de bot com botão azul para adicionar bot no canto superior direito

Depois de clicar neste botão, você terá criado com sucesso o bot do Discord. Para finalizar, ative a opção “MESSAGE CONTENT INTENT” para que o bot possa receber mensagens dos usuários do seu servidor Discord:

Opção de intenção de conteúdo de mensagem ativada para permitir que o Discord Bot receba mensagens de usuários

Instalando o bot no seu servidor Discord

A última coisa que você precisa fazer ao configurar seu bot é instalá-lo em seu servidor. No painel de navegação esquerdo, clique no item de menu “OAuth2” para alternar para um menu suspenso. Neste menu suspenso, clique na opção “Gerador de URL”:

Item de menu Oauth2 destacado com opção de submenu do gerador de URL com caixa azul mais clara

No menu Gerador de URL em “ESCOPOS”, marque a opção “bot”:

Menu do gerador de URL com caixas de seleção para vários itens em escopos com opção de bot marcada

Role a página até “BOT PERMISSIONS” e marque a opção “Administrator” para dar privilégios de administrador ao bot:

Submenu de permissões de bot com itens de caixa de seleção adicionais com opção de administrador marcada em permissões gerais

Role até a parte inferior da página e copie a URL gerada na parte inferior e abra a URL gerada em seu navegador:

Solicitar para selecionar o destino do servidor para instalação do Discord Bot e informações sobre permissões

Na página da Web que se abre depois de navegar para o URL gerado, selecione o servidor no qual deseja instalar o bot. Clique em “Continuar” para continuar.

Na tela seguinte, clique em “Autorizar”. A página da Web solicitará que você verifique se você é humano:

Tela de confirmação para adicionar aplicativo ao servidor Discord

Quando terminar essas etapas, abra a lista de membros do seu servidor. Você deve ver seu bot listado como membro.

Configurando o ambiente de código Rust

Nesta seção, orientarei você na configuração do ambiente de código Rust para seu bot do Discord. O ambiente de código terá o código e os pacotes necessários para você começar a criar o bot.

Para configurar o projeto, usaremos uma ferramenta chamada Shuttle. Shuttle permite inicializar, construir e implantar uma variedade de projetos em Rust.

Para este projeto, usaremos Shuttle para inicializar um projeto Serenity. Serenity é uma estrutura para criar bots de bate-papo do Discord em Rust.

Para inicializar o projeto Serenity, crie um novo diretório onde você deseja que seu projeto esteja. Em seguida, instale o Shuttle com o comando abaixo:

cargo install cargo-shuttle

Em seguida, inicialize um projeto no diretório:

cargo shuttle init --serenity

Por fim, construa o projeto:

cargo build

Se você seguiu essas etapas corretamente, verá seu diretório preenchido com o código necessário para começar.

Conectando a base de código Rust ao seu bot do Discord

O src/lib.rscódigo — que geramos na seção anterior — é um projeto básico que você pode conectar ao seu bot, o que faremos passo a passo nesta seção.

Para conectar com sucesso seu código ao bot, primeiro você precisa obter o token do bot. Um token de bot é uma referência ao seu bot. Cada bot tem uma referência exclusiva que você pode usar para conectar uma base de código ao seu bot.

Para recuperar seu token de bot, primeiro abra o painel do desenvolvedor do Discord. Clique em “Bot” no painel de navegação esquerdo. Em seguida, clique no botão “Redefinir Token”:

Crie uma tela de bot do painel do desenvolvedor do Discord com informações do aplicativo e botão para redefinir o token

Clique em “Copiar” para copiar o token:

Crie uma tela de bot do painel do desenvolvedor do Discord com token gerado para conectar o código Rust ao bot do Discord

Para conectar a base de código ao seu bot, crie um Secrets.tomlarquivo no diretório raiz do projeto. Escreva o seguinte no Secrets.tomlarquivo e substitua * bot_token *pelo token do bot:

DISCORD_TOKEN="* bot_token *"

Execute o projeto com este comando:

cargo shuttle run

Ao final dessas etapas, você deverá ver seu bot do Discord online em seu servidor. Se você digitar !hellono servidor, o bot deve responder com world!.

Para entender como o bot responde a !hello, dê uma olhada no manipulador de eventos nas linhas 12–24 do src/lib.rsarquivo:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

O manipulador de eventos tem um messagemétodo que é chamado sempre que alguém envia uma mensagem no servidor. A messagefunção possui um ifbloco verificando se a nova mensagem diz !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

Se a mensagem corresponder a !hello, o programa enviará a world!mensagem de volta ao servidor com esta instrução:

msg.channel_id.say(&ctx.http, "world!").await

Você pode programar o bot para responder a quaisquer mensagens personalizadas com respostas personalizadas seguindo as etapas acima.

Criando comandos para o bot do Discord

Os comandos são uma forma mais direta de interagir com um bot. Ao contrário das mensagens, os comandos começam com uma /barra — por exemplo, /hello.

Você pode enviar comandos no Discord da mesma forma que envia mensagens, mas eles são a forma preferida de interagir com bots porque você pode facilmente dizer quais mensagens são comandos e quais não são.

Para permitir que seu bot responda a comandos, você precisará do ID do servidor no qual instalou o bot. Para obter o ID do servidor, primeiro você precisa habilitar o modo de desenvolvedor em sua conta.

Ativando o modo de desenvolvedor na sua conta do Discord

O modo de desenvolvedor é uma configuração do Discord que dá aos desenvolvedores privilégios elevados em um servidor. Nesta seção, orientarei você na ativação do modo de desenvolvedor em seu sistema para que você possa copiar o ID do servidor e permitir que o bot responda aos comandos.

No Windows ou Mac

Na parte inferior da janela, clique no ícone de configurações próximo ao seu nome de usuário. No painel esquerdo, selecione "Aparência" em "CONFIGURAÇÕES DO APLICATIVO".

No menu de configurações de aparência, clique em “Avançado” para abrir o menu de configurações avançadas, onde você pode alternar a opção “Modo de desenvolvedor”. Por fim, clique com o botão direito do mouse no nome do servidor e selecione “Copiar ID” para copiar o ID do servidor.

No Linux

Na parte inferior da janela, clique no ícone de configurações próximo ao seu nome de usuário. No painel esquerdo, selecione “Avançado” em “CONFIGURAÇÕES DO APLICATIVO” para abrir o menu de configurações avançadas, onde você pode alternar a opção “Modo de desenvolvedor”.

Em seguida, clique com o botão direito do mouse no nome do servidor e selecione “Copiar ID” para copiar o ID do servidor:

Configurações avançadas do aplicativo Discord ativadas no modo de desenvolvedor com o menu do servidor aberto e a opção de copiar o ID do servidor na parte inferior da lista

Habilitando seu bot para responder a um comando

Com o ID do servidor pronto, siga estas etapas para permitir que seu bot responda a um comando. Primeiro, escreva o readymétodo abaixo no manipulador de eventos:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Em seguida, escreva o interaction_createmanipulador abaixo no manipulador de eventos:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

No readymétodo do manipulador de eventos, substitua * guild_id *na terceira linha pelo ID do seu servidor.

Se o seu código ainda estiver em execução no terminal, reinicie-o. Quando você vir seu bot online em seu servidor, envie uma /hellomensagem. Você deve ver uma resposta do bot dizendo helloem resposta.

Assim como nas respostas de mensagens, você pode programar seu bot para responder a qualquer comando personalizado com respostas personalizadas seguindo as etapas abordadas acima.

Implantando o bot do Discord no servidor Shuttle

Executar seu projeto em seu sistema pode ter desvantagens. Bots mais complexos podem exigir grandes recursos para executar e atender a todos os usuários.

A implantação do bot oferece a ele a vantagem de não usar os recursos do computador para execução. Ele também mantém seu bot online, mesmo que você não esteja.

O Shuttle permite que você implante seu bot no servidor Shuttle. Para implantar seu bot, execute este comando no diretório do projeto:

cargo shuttle deploy

Conclusão

Construir um bot de bate-papo Discord em Rust pode ser uma tarefa desafiadora. Mas com o conhecimento e as ferramentas certas, isso pode ser feito facilmente.

Com as instruções passo a passo fornecidas neste artigo, qualquer pessoa com experiência em programação em Rust e uma conta Discord pode aprender a criar seu próprio bot de bate-papo Discord. Se você está procurando alguns bots do Discord para construir, aqui estão algumas ideias:

  • Bots de boas-vindas para receber novos usuários em um servidor ou canal
  • Bots de jogos para jogos de perguntas e respostas, quiz, jogo da velha e outros jogos
  • Bots de mídia que tocam música ou permitem que os usuários criem ou selecionem vídeos, imagens ou GIFs para compartilhar
  • Poll bots para ajudar os usuários a criar e enviar enquetes
  • Bots utilitários para automatizar funções do servidor, como responder a perguntas frequentes e muito mais

Para ler mais sobre os bots do Rust Discord, confira alguns exemplos de bots do Serenity Discord ou a documentação do Serenity .

Fonte: https://blog.logrocket.com

#rust #chatbot #discord

Construindo um Discord Chat Bot em Rust

بناء روبوت محادثة على الفتنة في Rust

تعرف على كيفية بناء روبوت Discord في Rust باستخدام Shuttle and Serenity. تعرف على كيفية إنشاء روبوت في Discord ، وإضافة الروبوت إلى الخادم الخاص بك ، وتوصيل كود Rust الخاص بك إلى الروبوت الخاص بك.

يمكن لروبوتات Discord أن توفر لمالكي الخوادم والموظفين الكثير من الوقت والجهد مع توفير مجموعة متنوعة من الميزات المفيدة للمستخدمين. يمكنك استخدام الروبوتات في Discord لأتمتة المهام والمهام المتكررة التي كانت ستستغرق الكثير من الوقت والجهد.

في هذه المقالة ، ستتعلم كيفية إنشاء روبوت في Discord ، وإضافة الروبوت إلى الخادم الخاص بك ، وتوصيل كود Rust الخاص بك إلى الروبوت الخاص بك.

جدول المحتويات:

  • إعداد بوت ديسكورد
    • إنشاء تطبيق في Discord
    • إنشاء بوت للتطبيق
    • تثبيت الروبوت على خادم Discord الخاص بك
  • إعداد بيئة كود الصدأ
  • توصيل قاعدة كود Rust بروبوت Discord الخاص بك
  • إنشاء أوامر لروبوت الديسكورد
    • تمكين وضع المطور على حساب Discord الخاص بك
    • تمكين الروبوت الخاص بك من الاستجابة لأمر
  • نشر بوت Discord على خادم Shuttle

لمتابعة هذا المقال ، تحتاج على الأقل إلى مستوى معين من الإلمام بـ Discord. يجب أن يكون لديك أيضًا حساب Discord وخادم Discord تملكه وبعض الخبرة في البرمجة مع Rust.


إعداد بوت ديسكورد

قد يكون إعداد الروبوت في Discord أمرًا صعبًا بعض الشيء ، خاصة إذا كانت هذه هي المرة الأولى التي تقوم فيها بذلك. في هذا القسم ، سأوجهك خلال إعداد الروبوت لخادمك.

إنشاء تطبيق في Discord

تطبيق Discord هو خدمة توفر واجهة بين مستخدمي Discord وكودك. الواجهة التي يوفرها التطبيق تسمى bot. يتلقى الروبوت رسائل من المستخدمين ويرسل ردًا.

لإنشاء تطبيق Discord ، قم أولاً بتسجيل الدخول إلى حساب Discord الخاص بك في متصفحك. بعد ذلك ، افتح بوابة مطور Discord في متصفحك وانقر على الزر المسمى "تطبيق جديد" في أعلى يمين الصفحة:

بوابة مطور Discord في الوضع المظلم مع الزر الأزرق لإنشاء تطبيق جديد في أعلى اليمين

أدخل اسمًا للتطبيق الخاص بك:

اطلب إدخال اسم للتطبيق أو تحقق من دعم Dev لمعرفة ما إذا كان التطبيق موجودًا بالفعل

انقر فوق الزر المسمى "إنشاء" لإنشاء التطبيق. إذا اكتمل الإجراء بنجاح ، فسيتم استقبالك بلوحة تحكم تبدو كالتالي:

لوحة معلومات تطبيق الخلاف

إنشاء بوت للتطبيق

في هذا القسم ، ستقوم بإنشاء الروبوت لتطبيق Discord الخاص بك. في الجزء الأيمن من صفحة الويب ، انقر فوق "Bot" لفتح قائمة bot:

تم تمييز عنصر قائمة البوت باللون الأزرق في قائمة الإعدادات

Under the “Build-A-Bot” section, click the “Add Bot” button to create the bot:

قم ببناء قسم بوت باستخدام زر أزرق لإضافة بوت في أعلى اليمين

After clicking this button, you will have successfully created the Discord bot. To finish off, activate the “MESSAGE CONTENT INTENT” option so that the bot can receive messages from users in your Discord server:

تم تبديل خيار هدف محتوى الرسالة للسماح لروبوتات الديسكورد بتلقي رسائل من المستخدمين

Installing the bot to your Discord server

The last thing you need to do in setting your bot is to install it to your server. On the left navigation pane, click the “OAuth2” menu item to toggle a dropdown. In this dropdown, click the “URL Generator” option:

تم تمييز عنصر قائمة Oauth2 مع مخطط خيار القائمة الفرعية لمولد عنوان URL مع مربع أزرق فاتح

In the URL Generator menu under “SCOPES,” tick the “bot” option:

قائمة مولِّد عنوان URL مع مربعات اختيار للعناصر المختلفة ضمن النطاقات مع تحديد خيار Bot

Scroll farther down the page to “BOT PERMISSIONS” and tick the “Administrator” option to give the bot admin privileges:

قائمة فرعية لأذونات Bot مع عناصر مربع اختيار إضافية مع تحديد خيار المسؤول ضمن أذونات عامة

Scroll to the bottom of the page and copy the generated URL on the bottom, then open the generated URL in your browser:

اطلب تحديد وجهة الخادم لتثبيت Discord Bot ومعلومات حول الأذونات

In the webpage that opens after you navigate to the generated URL, select the server that you want to install the bot in. Click “Continue” to proceed.

On the next screen, click “Authorize.” The webpage will then prompt you to verify that you are human:

شاشة التأكيد لإضافة التطبيق إلى خادم Discord

When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.

Setting up the Rust code environment

In this section, I’ll guide you through setting up the Rust code environment for your Discord bot. The code environment will have the necessary code and packages for you to get started with building the bot.

To set up the project, we’ll use a tool called Shuttle. Shuttle lets you initialize, build, and deploy a variety of projects in Rust.

For this project, we’ll use Shuttle to initialize a Serenity project. Serenity is a framework for building Discord chat bots in Rust.

To initialize the Serenity project, create a new directory for where you want your project to be. Then, install Shuttle with the command below:

cargo install cargo-shuttle

Next, initialize a project in the directory:

cargo shuttle init --serenity

Finally, build the project:

cargo build

If you followed these steps correctly, you should see your directory filled with the necessary code for getting started.

Connecting the Rust codebase to your Discord bot

The src/lib.rs code — which we generated in the previous section — is a basic project that you can connect to your bot, which we will do step-by-step in this section.

In order to successfully connect your code to your bot, you first need to get your bot token. A bot token is a reference to your bot. Every bot has a unique reference that you can use to connect a codebase to your bot.

To retrieve your bot token, first open the Discord developer dashboard. Click “Bot” on the left navigation pane. Then, click the “Reset Token” button:

قم بإنشاء شاشة بوت للوحة تحكم مطور Discord مع معلومات التطبيق وزر لإعادة تعيين الرمز

Click “Copy” to copy the token:

قم بإنشاء شاشة بوت للوحة تحكم مطور Discord مع رمز تم إنشاؤه لتوصيل كود الصدأ ببرنامج Discord Bot

To connect the code base to your bot, create a Secrets.toml file in the project’s root directory. Write the following into the Secrets.toml file and replace * bot_token * with your bot token:

DISCORD_TOKEN="* bot_token *"

Run the project with this command:

cargo shuttle run

At the end of these steps, you should see your Discord bot online on your server. If you type !hello on the server, the bot should respond with world!.

لفهم كيفية استجابة الروبوت !hello، ألق نظرة على معالج الأحداث من السطور 12-24 من الملف src/lib.rs:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

يحتوي معالج الأحداث على messageطريقة يتم استدعاؤها في أي وقت يرسل فيه شخص ما رسالة على الخادم. messageتحتوي الوظيفة على فحص ifكتلة إذا كانت الرسالة الجديدة تقول !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

إذا تطابقت الرسالة !hello، يرسل البرنامج الرسالة world!مرة أخرى إلى الخادم بهذه العبارة:

msg.channel_id.say(&ctx.http, "world!").await

يمكنك برمجة الروبوت للرد على أي رسائل مخصصة بردود مخصصة باتباع الخطوات المذكورة أعلاه.

إنشاء أوامر لروبوت الديسكورد

الأوامر هي طريقة مباشرة أكثر للتفاعل مع الروبوت. على عكس الرسائل ، تبدأ الأوامر بشرطة /مائلة - على سبيل المثال ، /hello.

يمكنك إرسال الأوامر في Discord بالطريقة نفسها التي ترسل بها الرسائل ، لكنها الطريقة المفضلة للتفاعل مع برامج الروبوت لأنه يمكنك بسهولة معرفة الرسائل التي هي أوامر وما هي الرسائل غير الموجودة.

للسماح لبرنامج الروبوت الخاص بك بالاستجابة للأوامر ، ستحتاج إلى معرف الخادم الذي قمت بتثبيت الروبوت فيه. من أجل الحصول على معرف الخادم ، تحتاج إلى تمكين وضع المطور على حسابك أولاً.

تمكين وضع المطور على حساب Discord الخاص بك

وضع المطور هو أحد إعدادات Discord التي تمنح المطورين امتيازات عالية في الخادم. في هذا القسم ، سأوجهك خلال تمكين وضع المطور على نظامك حتى تتمكن من نسخ معرف الخادم الخاص بك وتمكين الروبوت الخاص بك من الاستجابة للأوامر.

على نظام التشغيل Windows أو Mac

في الجزء السفلي من النافذة ، انقر فوق رمز الإعدادات بالقرب من اسم المستخدم الخاص بك. في الجزء الأيمن ، حدد "المظهر" ضمن "إعدادات التطبيق".

في قائمة إعدادات المظهر ، انقر على "خيارات متقدمة" لفتح قائمة الإعدادات المتقدمة ، حيث يمكنك بعد ذلك تبديل خيار "وضع المطور". أخيرًا ، انقر بزر الماوس الأيمن فوق اسم الخادم وحدد "نسخ المعرف" لنسخ معرف الخادم.

على لينكس

في الجزء السفلي من النافذة ، انقر فوق رمز الإعدادات بالقرب من اسم المستخدم الخاص بك. في الجزء الأيمن ، حدد "متقدم" ضمن "إعدادات التطبيق" لفتح قائمة الإعدادات المتقدمة ، حيث يمكنك بعد ذلك تبديل خيار "وضع المطور".

ثم ، انقر بزر الماوس الأيمن فوق اسم الخادم وحدد "نسخ المعرف" لنسخ معرف الخادم:

تم تمكين إعدادات تطبيق Discord المتقدمة في وضع المطور مع فتح قائمة الخادم وخيار لنسخ معرف الخادم في أسفل القائمة

تمكين الروبوت الخاص بك من الاستجابة لأمر

مع استعداد معرف الخادم ، اتبع هذه الخطوات لتمكين الروبوت الخاص بك من الاستجابة لأمر ما. أولاً ، اكتب readyالطريقة أدناه في معالج الأحداث:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

بعد ذلك ، اكتب interaction_createالمعالج أدناه في معالج الأحداث:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

في readyطريقة معالج الحدث ، استبدل * guild_id *معرف الخادم الخاص بك في السطر الثالث.

إذا كان الرمز الخاص بك لا يزال يعمل في الجهاز ، فأعد تشغيله. عندما ترى الروبوت الخاص بك على الإنترنت على خادمك ، أرسل رسالة /hello. يجب أن ترى ردًا من الروبوت يقول helloردًا.

كما هو الحال مع الردود على الرسائل ، يمكنك برمجة الروبوت الخاص بك للرد على أي أوامر مخصصة مع ردود مخصصة باتباع الخطوات التي تناولناها أعلاه.

نشر بوت Discord على خادم Shuttle

يمكن أن يؤدي تشغيل مشروعك على نظامك إلى عيوب. قد تتطلب برامج الروبوت الأكثر تعقيدًا موارد كبيرة لتشغيل وخدمة كل مستخدم.

يمنح نشر برنامج الروبوت الخاص بك ميزة عدم استخدام موارد جهاز الكمبيوتر الخاص بك للتشغيل. كما أنه يبقي الروبوت الخاص بك متصلاً بالإنترنت ، حتى لو لم تكن كذلك.

يتيح لك Shuttle نشر الروبوت الخاص بك على خادم Shuttle. لنشر الروبوت الخاص بك ، قم بتشغيل هذا الأمر في دليل المشروع الخاص بك:

cargo shuttle deploy

خاتمة

يمكن أن يكون بناء روبوت محادثة على Discord في Rust مهمة صعبة. ولكن مع المعرفة والأدوات الصحيحة ، يمكن القيام بذلك بسهولة.

من خلال الإرشادات خطوة بخطوة الواردة في هذه المقالة ، يمكن لأي شخص لديه خبرة في البرمجة في Rust وحساب Discord تعلم كيفية إنشاء روبوت دردشة Discord الخاص به. إذا كنت تبحث عن بعض روبوتات Discord المراد إنشاؤها ، فإليك بعض الأفكار:

  • نرحب بالروبوتات للترحيب بالمستخدمين الجدد على خادم أو قناة
  • روبوتات الألعاب للعب التوافه والاختبار و tic-tac-toe وغيرها من الألعاب
  • روبوتات الوسائط التي تشغل الموسيقى أو تسمح للمستخدمين بإنشاء أو تحديد مقاطع فيديو أو صور أو ملفات GIF لمشاركتها
  • روبوتات الاقتراع لمساعدة المستخدمين على إنشاء وإرسال استطلاعات الرأي
  • الروبوتات المساعدة لأتمتة وظائف الخادم مثل الإجابة على الأسئلة الشائعة والمزيد

لمزيد من القراءة عن روبوتات Rust Discord ، تحقق من بعض أمثلة برامج Serenity Discord أو وثائق Serenity .

المصدر: https://blog.logrocket.com

#rust #discord #chatbot

بناء روبوت محادثة على الفتنة في Rust
Duong Tran

Duong Tran

1677129494

Cách tạo Discord chatbot trong Rust

Tìm hiểu cách xây dựng bot Discord trong Rust với Shuttle và Serenity. Tìm hiểu cách tạo bot trong Discord, thêm bot vào máy chủ của bạn và kết nối mã Rust với bot của bạn.

Bot Discord có thể tiết kiệm cho chủ sở hữu máy chủ và nhân viên rất nhiều thời gian và công sức đồng thời cung cấp nhiều tính năng hữu ích cho người dùng. Bạn có thể sử dụng bot trong Discord để tự động hóa các nhiệm vụ lặp đi lặp lại và các nhiệm vụ sẽ chiếm nhiều thời gian và công sức.

Trong bài viết này, bạn sẽ tìm hiểu cách tạo bot trong Discord, thêm bot vào máy chủ của bạn và kết nối mã Rust với bot của bạn.

Mục lục:

  • Thiết lập bot Discord
    • Tạo một ứng dụng trong Discord
    • Tạo bot cho ứng dụng
    • Cài đặt bot vào máy chủ Discord của bạn
  • Thiết lập môi trường mã Rust
  • Kết nối cơ sở mã Rust với bot Discord của bạn
  • Tạo lệnh cho bot Discord
    • Kích hoạt chế độ nhà phát triển trên tài khoản Discord của bạn
    • Cho phép bot của bạn phản hồi lệnh
  • Triển khai bot Discord đến máy chủ Shuttle

Để theo dõi bài viết này, bạn cần ít nhất một mức độ quen thuộc với Discord. Bạn cũng nên có tài khoản Discord, máy chủ Discord mà bạn sở hữu và một số kinh nghiệm lập trình với Rust.


Thiết lập bot Discord

Việc thiết lập bot trong Discord có thể hơi phức tạp, đặc biệt nếu đây là lần đầu tiên bạn thực hiện việc này. Trong phần này, tôi sẽ hướng dẫn bạn thiết lập bot cho máy chủ của bạn.

Tạo một ứng dụng trong Discord

Ứng dụng Discord là dịch vụ cung cấp giao diện giữa người dùng Discord và mã của bạn. Giao diện mà ứng dụng cung cấp được gọi là bot. Bot nhận tin nhắn từ người dùng và gửi phản hồi.

Để tạo ứng dụng Discord, trước tiên hãy đăng nhập vào tài khoản Discord của bạn trong trình duyệt. Tiếp theo, hãy mở cổng thông tin dành cho nhà phát triển Discord trong trình duyệt của bạn và nhấp vào nút có nhãn “Ứng dụng mới” ở trên cùng bên phải của trang:

Cổng thông tin dành cho nhà phát triển Discord ở chế độ tối với nút màu xanh lam để tạo ứng dụng mới ở trên cùng bên phải

Nhập tên cho ứng dụng của bạn:

Nhắc nhập tên cho ứng dụng hoặc kiểm tra với bộ phận hỗ trợ của nhà phát triển để xem ứng dụng đã tồn tại chưa

Nhấp vào nút có nhãn “Tạo” để tạo ứng dụng. Nếu hành động hoàn tất thành công, bạn sẽ được chào đón bằng một bảng điều khiển giống như sau:

Bảng điều khiển ứng dụng Discord

Tạo bot cho ứng dụng

Trong phần này, bạn sẽ tạo bot cho ứng dụng Discord của mình. Trên ngăn bên trái của trang web, nhấp vào “Bot” để mở menu bot:

Mục Menu Bot được đánh dấu bằng màu xanh lam trong danh sách cài đặt

Trong phần “Build-A-Bot”, nhấp vào nút “Add Bot” để tạo bot:

Discord Xây dựng phần Bot bằng nút màu xanh lam để thêm bot ở trên cùng bên phải

Sau khi nhấp vào nút này, bạn sẽ tạo thành công bot Discord. Để kết thúc, hãy kích hoạt tùy chọn “MESSAGE CONTENT INTENT” để bot có thể nhận tin nhắn từ người dùng trong máy chủ Discord của bạn:

Tùy chọn ý định nội dung tin nhắn được bật để cho phép Discord Bot nhận tin nhắn từ người dùng

Cài đặt bot vào máy chủ Discord của bạn

Điều cuối cùng bạn cần làm trong việc thiết lập bot của mình là cài đặt nó vào máy chủ của bạn. Trên ngăn điều hướng bên trái, hãy nhấp vào mục menu “OAuth2” để chuyển đổi danh sách thả xuống. Trong danh sách thả xuống này, hãy nhấp vào tùy chọn “Trình tạo URL”:

Mục menu Oauth2 được làm nổi bật với tùy chọn menu phụ Trình tạo url Phác thảo với hộp màu xanh nhạt hơn

Trong menu Trình tạo URL bên dưới “PHẠM VI”, đánh dấu vào tùy chọn “bot”:

Trình đơn trình tạo url có hộp kiểm cho các mục khác nhau trong phạm vi với tùy chọn bot được chọn

Cuộn xa hơn xuống dưới trang đến “PHÉP BOT” và đánh dấu vào tùy chọn “Quản trị viên” để cấp đặc quyền quản trị viên bot:

Menu con quyền của bot với các mục hộp kiểm bổ sung với tùy chọn quản trị viên được đánh dấu trong quyền chung

Cuộn xuống cuối trang và sao chép URL được tạo ở dưới cùng, sau đó mở URL được tạo trong trình duyệt của bạn:

Nhắc chọn đích máy chủ để cài đặt Discord Bot và thông tin về quyền

Trong trang web mở ra sau khi bạn điều hướng đến URL đã tạo, hãy chọn máy chủ mà bạn muốn cài đặt bot. Nhấp vào “Tiếp tục” để tiếp tục.

Trên màn hình tiếp theo, nhấp vào “Ủy quyền”. Sau đó, trang web sẽ nhắc bạn xác minh rằng bạn là con người:

Màn hình xác nhận để thêm ứng dụng vào máy chủ Discord

Khi bạn hoàn thành các bước này, hãy mở danh sách thành viên máy chủ của bạn. Bạn sẽ thấy bot của mình được liệt kê là thành viên.

Thiết lập môi trường mã Rust

Trong phần này, tôi sẽ hướng dẫn bạn cách thiết lập môi trường mã Rust cho bot Discord của bạn. Môi trường mã sẽ có các gói và mã cần thiết để bạn bắt đầu xây dựng bot.

Để thiết lập dự án, chúng tôi sẽ sử dụng một công cụ có tên là Shuttle. Shuttle cho phép bạn khởi tạo, xây dựng và triển khai nhiều dự án khác nhau trong Rust.

Đối với dự án này, chúng tôi sẽ sử dụng Shuttle để khởi tạo dự án Serenity. Serenity là một khuôn khổ để xây dựng các bot trò chuyện Discord trong Rust.

Để khởi tạo dự án Serenity, hãy tạo một thư mục mới cho nơi bạn muốn đặt dự án của mình. Sau đó, cài đặt Shuttle bằng lệnh bên dưới:

cargo install cargo-shuttle

Tiếp theo, khởi tạo một dự án trong thư mục:

cargo shuttle init --serenity

Cuối cùng, xây dựng dự án:

cargo build

Nếu thực hiện đúng các bước này, bạn sẽ thấy thư mục chứa đầy mã cần thiết để bắt đầu.

Kết nối cơ sở mã Rust với bot Discord của bạn

src/lib.rs— mà chúng tôi đã tạo trong phần trước — là một dự án cơ bản mà bạn có thể kết nối với bot của mình, chúng tôi sẽ thực hiện từng bước trong phần này.

Để kết nối thành công mã của bạn với bot, trước tiên bạn cần nhận mã thông báo bot của mình. Mã thông báo bot là tham chiếu đến bot của bạn. Mỗi bot có một tham chiếu duy nhất mà bạn có thể sử dụng để kết nối cơ sở mã với bot của mình.

Để truy xuất mã thông báo bot của bạn, trước tiên hãy mở bảng điều khiển dành cho nhà phát triển Discord. Nhấp vào “Bot” trên ngăn điều hướng bên trái. Sau đó, nhấp vào nút “Đặt lại mã thông báo”:

Xây dựng màn hình bot của bảng điều khiển dành cho nhà phát triển Discord với thông tin ứng dụng và nút để đặt lại mã thông báo

Nhấp vào “Sao chép” để sao chép mã thông báo:

Xây dựng màn hình bot của Bảng điều khiển dành cho nhà phát triển Discord với mã thông báo được tạo để kết nối mã Rust với Discord Bot

Để kết nối cơ sở mã với bot của bạn, hãy tạo một Secrets.tomltệp trong thư mục gốc của dự án. Viết phần sau vào Secrets.tomltệp và thay thế * bot_token *bằng mã thông báo bot của bạn:

DISCORD_TOKEN="* bot_token *"

Chạy dự án bằng lệnh này:

cargo shuttle run

Khi kết thúc các bước này, bạn sẽ thấy bot Discord trực tuyến trên máy chủ của mình. Nếu bạn nhập !hellotrên máy chủ, bot sẽ phản hồi bằng world!.

Để hiểu cách bot phản hồi !hello, hãy xem trình xử lý sự kiện từ dòng 12–24 của tệp src/lib.rs:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

Trình xử lý sự kiện có một messagephương thức được gọi bất cứ khi nào ai đó gửi tin nhắn trên máy chủ. Chức năng này messagecó một ifkhối kiểm tra nếu thông báo mới cho biết !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

Nếu thông báo khớp !hello, chương trình sẽ gửi world!thông báo trở lại máy chủ với câu lệnh sau:

msg.channel_id.say(&ctx.http, "world!").await

Bạn có thể lập trình bot để trả lời bất kỳ tin nhắn tùy chỉnh nào bằng phản hồi tùy chỉnh theo các bước ở trên.

Tạo lệnh cho bot Discord

Lệnh là một cách trực tiếp hơn để tương tác với bot. Không giống như tin nhắn, lệnh bắt đầu bằng /dấu gạch chéo — ví dụ: /hello.

Bạn có thể gửi lệnh trong Discord giống như cách bạn gửi tin nhắn, nhưng chúng là cách tương tác ưa thích với bot vì bạn có thể dễ dàng biết tin nhắn nào là lệnh và tin nhắn nào không.

Để cho phép bot của bạn phản hồi các lệnh, bạn sẽ cần ID của máy chủ mà bạn đã cài đặt bot. Để có được ID máy chủ, trước tiên bạn cần bật chế độ nhà phát triển trên tài khoản của mình.

Kích hoạt chế độ nhà phát triển trên tài khoản Discord của bạn

Chế độ nhà phát triển là cài đặt Discord cung cấp cho nhà phát triển các đặc quyền nâng cao trong máy chủ. Trong phần này, tôi sẽ hướng dẫn bạn cách bật chế độ nhà phát triển trên hệ thống của bạn để bạn có thể sao chép ID máy chủ của mình và cho phép bot của bạn phản hồi các lệnh.

Trên Windows hoặc Mac

Ở dưới cùng của cửa sổ, nhấp vào biểu tượng cài đặt gần với tên người dùng của bạn. Trên ngăn bên trái, chọn “Giao diện” trong “CÀI ĐẶT ỨNG DỤNG”.

Trong menu cài đặt giao diện, hãy nhấp vào “Nâng cao” để mở menu cài đặt nâng cao, sau đó bạn có thể chuyển đổi tùy chọn “Chế độ nhà phát triển”. Cuối cùng, nhấp chuột phải vào tên máy chủ và chọn “Copy ID” để sao chép ID máy chủ.

Trên Linux

Ở dưới cùng của cửa sổ, nhấp vào biểu tượng cài đặt gần với tên người dùng của bạn. Trên ngăn bên trái, chọn “Nâng cao” trong “CÀI ĐẶT ỨNG DỤNG” để mở menu cài đặt nâng cao, sau đó bạn có thể chuyển đổi tùy chọn “Chế độ nhà phát triển”.

Sau đó, nhấp chuột phải vào tên máy chủ và chọn “Copy ID” để sao chép ID máy chủ:

Cài đặt ứng dụng nâng cao của Discord được bật ở Chế độ nhà phát triển với menu máy chủ mở và tùy chọn sao chép Id máy chủ ở cuối danh sách

Cho phép bot của bạn phản hồi lệnh

Với ID máy chủ đã sẵn sàng, hãy làm theo các bước sau để cho phép bot của bạn phản hồi lệnh. Đầu tiên, hãy viết readyphương thức bên dưới vào trình xử lý sự kiện:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Tiếp theo, viết interaction_createtrình xử lý bên dưới vào trình xử lý sự kiện:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

Trong readyphương thức của trình xử lý sự kiện, hãy thay thế * guild_id *trên dòng thứ ba bằng ID máy chủ của bạn.

Nếu mã của bạn vẫn đang chạy trong thiết bị đầu cuối, hãy khởi động lại nó. Khi bạn thấy bot trực tuyến trên máy chủ của mình, hãy gửi /hellotin nhắn. Bạn sẽ thấy phản hồi từ bot nói hellođể đáp lại.

Đối với phản hồi tin nhắn, bạn có thể lập trình bot của mình để phản hồi bất kỳ lệnh tùy chỉnh nào bằng phản hồi tùy chỉnh bằng cách thực hiện theo các bước chúng tôi đã trình bày ở trên.

Triển khai bot Discord đến máy chủ Shuttle

Chạy dự án của bạn trên hệ thống của bạn có thể có những bất lợi. Các bot phức tạp hơn có thể yêu cầu tài nguyên lớn để chạy và phục vụ mọi người dùng.

Triển khai bot của bạn mang lại cho bot của bạn lợi thế là không sử dụng tài nguyên máy tính của bạn để chạy. Nó cũng giữ cho bot của bạn trực tuyến, ngay cả khi bạn không.

Shuttle cho phép bạn triển khai bot của mình đến máy chủ Shuttle. Để triển khai bot của bạn, hãy chạy lệnh này trong thư mục dự án của bạn:

cargo shuttle deploy

Phần kết luận

Xây dựng bot trò chuyện Discord trong Rust có thể là một nhiệm vụ đầy thách thức. Nhưng với kiến ​​thức và công cụ phù hợp, nó có thể được thực hiện dễ dàng.

Với hướng dẫn từng bước được cung cấp trong bài viết này, bất kỳ ai có kinh nghiệm lập trình trong Rust và có tài khoản Discord đều có thể học cách xây dựng bot trò chuyện Discord của riêng mình. Nếu bạn đang tìm kiếm một số bot Discord để xây dựng, đây là một số ý tưởng:

  • Các bot chào mừng chào đón người dùng mới đến với máy chủ hoặc kênh
  • Bot trò chơi để chơi đố vui, đố vui, tic-tac-toe và các trò chơi khác
  • Các bot phương tiện phát nhạc hoặc cho phép người dùng tạo hoặc chọn video, hình ảnh hoặc GIF để chia sẻ
  • Các bot thăm dò ý kiến ​​để giúp người dùng tạo và gửi các cuộc thăm dò ý kiến
  • Các bot tiện ích để tự động hóa các chức năng của máy chủ như trả lời các câu hỏi thường gặp và hơn thế nữa

Để đọc thêm về bot Rust Discord, hãy xem một số bot ví dụ về Serenity Discord hoặc tài liệu về Serenity .

Nguồn: https://blog.logrocket.com

#rust #chatbot #discord

Cách tạo Discord chatbot trong Rust
Rust  Language

Rust Language

1677125250

Building a Discord Chat Bot in Rust

Learn how to build a Discord bot in Rust with Shuttle and Serenity. Learn how to create a bot in Discord, add the bot to your server, and connect your Rust code to your bot.

Discord bots can save server owners and staff members a lot of time and effort while also providing a variety of useful features to users. You can use bots in Discord to automate repetitive tasks and tasks that would otherwise take up a lot of time and effort.

In this article, you will learn how to create a bot in Discord, add the bot to your server, and connect your Rust code to your bot.

Table of contents:

  • Setting up the Discord bot
    • Creating an application in Discord
    • Creating a bot for the application
    • Installing the bot to your Discord server
  • Setting up the Rust code environment
  • Connecting the Rust codebase to your Discord bot
  • Creating commands for the Discord bot
    • Enabling developer mode on your Discord account
    • Enabling your bot to respond to a command
  • Deploying the Discord bot to the Shuttle server

To follow along with this article, you need at least some level of familiarity with Discord. You should also have a Discord account, a Discord server that you own, and some programming experience with Rust.


Setting up the Discord bot

Setting up the bot in Discord can be a little tricky, especially if this is your first time doing it. In this section, I’ll guide you through setting up the bot for your server.

Creating an application in Discord

A Discord application is a service that provides an interface between Discord users and your code. The interface that the application provides is called a bot. A bot receives messages from users and sends a response.

To create a Discord application, first log in to your Discord account in your browser. Next, open the Discord developer portal in your browser and click the button labeled “New Application” at the top right of the page:

Discord Developer Portal In Dark Mode With Blue Button To Create New Application At Top Right

Enter a name for your application:

Prompt To Enter Name For Application Or Check With Dev Support To See If App Already Exists

Click the button labeled “Create” to create the application. If the action completes successfully, you’ll be greeted with a dashboard that looks like this:

Discord Application Dashboard

Creating a bot for the application

In this section, you’ll create the bot for your Discord application. On the left pane of the webpage, click “Bot” to open the bot menu:

Bot Menu Item Highlighted In Blue In Settings List

Under the “Build-A-Bot” section, click the “Add Bot” button to create the bot:

Discord Build A Bot Section With Blue Button To Add Bot At Top Right

After clicking this button, you will have successfully created the Discord bot. To finish off, activate the “MESSAGE CONTENT INTENT” option so that the bot can receive messages from users in your Discord server:

Message Content Intent Option Toggled On To Allow Discord Bot To Receive Messages From Users

Installing the bot to your Discord server

The last thing you need to do in setting your bot is to install it to your server. On the left navigation pane, click the “OAuth2” menu item to toggle a dropdown. In this dropdown, click the “URL Generator” option:

Oauth2 Menu Item Highlighted With Url Generator Submenu Option Outline With Lighter Blue Box

In the URL Generator menu under “SCOPES,” tick the “bot” option:

Url Generator Menu With Checkboxes For Various Items Under Scopes With Bot Option Checked

Scroll farther down the page to “BOT PERMISSIONS” and tick the “Administrator” option to give the bot admin privileges:

Bot Permissions Submenu With Additional Checkbox Items With Administrator Option Ticked Under General Permissions

Scroll to the bottom of the page and copy the generated URL on the bottom, then open the generated URL in your browser:

Prompt To Select Server Destination For Discord Bot Installation And Information About Permissions

In the webpage that opens after you navigate to the generated URL, select the server that you want to install the bot in. Click “Continue” to proceed.

On the next screen, click “Authorize.” The webpage will then prompt you to verify that you are human:

Confirmation Screen For Adding Application To Discord Server

When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.

Setting up the Rust code environment

In this section, I’ll guide you through setting up the Rust code environment for your Discord bot. The code environment will have the necessary code and packages for you to get started with building the bot.

To set up the project, we’ll use a tool called Shuttle. Shuttle lets you initialize, build, and deploy a variety of projects in Rust.

For this project, we’ll use Shuttle to initialize a Serenity project. Serenity is a framework for building Discord chat bots in Rust.

To initialize the Serenity project, create a new directory for where you want your project to be. Then, install Shuttle with the command below:

cargo install cargo-shuttle

Next, initialize a project in the directory:

cargo shuttle init --serenity

Finally, build the project:

cargo build

If you followed these steps correctly, you should see your directory filled with the necessary code for getting started.

Connecting the Rust codebase to your Discord bot

The src/lib.rs code — which we generated in the previous section — is a basic project that you can connect to your bot, which we will do step-by-step in this section.

In order to successfully connect your code to your bot, you first need to get your bot token. A bot token is a reference to your bot. Every bot has a unique reference that you can use to connect a codebase to your bot.

To retrieve your bot token, first open the Discord developer dashboard. Click “Bot” on the left navigation pane. Then, click the “Reset Token” button:

Build A Bot Screen Of Discord Developer Dashboard With Application Information And Button To Reset Token

Click “Copy” to copy the token:

Build A Bot Screen Of Discord Developer Dashboard With Generated Token To Connect Rust Code To Discord Bot

To connect the code base to your bot, create a Secrets.toml file in the project’s root directory. Write the following into the Secrets.toml file and replace * bot_token * with your bot token:

DISCORD_TOKEN="* bot_token *"

Run the project with this command:

cargo shuttle run

At the end of these steps, you should see your Discord bot online on your server. If you type !hello on the server, the bot should respond with world!.

To understand how the bot responds to !hello, take a look at the event handler from lines 12–24 of the src/lib.rs file:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       if msg.content == "!hello" {
           if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
               error!("Error sending message: {:?}", e);
           }
       }

   }

   async fn ready(&self, _: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
   }
}

The event handler has a message method that gets called anytime someone sends a message on the server. The message function has an if block checking if the new message says !hello:

if msg.content == "!hello" {
    if let Err(e) = msg.channel_id.say(&ctx.http, "world!").await {
        error!("Error sending message: {:?}", e);
    }
}

If the message matches !hello, the program sends the world! message back to the server with this statement:

msg.channel_id.say(&ctx.http, "world!").await

You can program the bot to respond to any custom messages with custom responses following the steps above.

Creating commands for the Discord bot

Commands are a more direct way to interact with a bot. Unlike messages, commands begin with a / slash — e.g., /hello.

You can send commands in Discord the same way you send messages, but they are the preferred way of interacting with bots because you can easily tell what messages are commands and what messages are not.

To allow your bot to respond to commands, you’ll need the ID of the server in which you installed the bot. In order to get the server ID, you need to enable developer mode on your account first.

Enabling developer mode on your Discord account

Developer mode is a Discord setting that gives developers elevated privileges in a server. In this section, I’ll guide you through enabling developer mode on your system so you can copy your server ID and enable your bot to respond to commands.

On Windows or Mac

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Appearance” under “APP SETTINGS.”

In the appearance settings menu, click “Advanced” to open the advanced settings menu, where you can then toggle the “Developer Mode” option. Finally, right-click the server name and select “Copy ID” to copy the server ID.

On Linux

At the bottom of your window, click the settings icon close to your username. On the left pane, select “Advanced” under “APP SETTINGS” to open the advanced settings menu, where you can then toggle the “Developer Mode” option.

Then, right-click the server name and select “Copy ID” to copy the server ID:

Discord Advanced App Settings Enabled In Developer Mode With Server Menu Open And Option To Copy Server Id At Bottom Of List

Enabling your bot to respond to a command

With the server ID ready, follow these steps to enable your bot to respond to a command. First, write the ready method below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   
   // "EventHandler" calls the "ready" method below when the project starts running 
   async fn ready(&self, ctx: Context, ready: Ready) {
       info!("{} is connected!", ready.user.name);
       
       let guild_id = GuildId(* guild_id *);
       
       // add "/hello" command to the bot
       GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
           commands.create_application_command(|command| { command.name("hello").description("Say hello") })
       }).await.unwrap();

   }
}

Next, write the interaction_create handler below into the event handler:

struct Bot;

#[async_trait]
impl EventHandler for Bot {
   async fn message(&self, ctx: Context, msg: Message) {
       // ...
   }
   // `ready` method runs when the bot starts
   async fn ready(&self, _: Context, ready: Ready) {
       // ...
   }
   // `interaction_create` runs when the user interacts with the bot
   async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
       // check if the interaction is a command
       if let Interaction::ApplicationCommand(command) = interaction {

           let response_content =
               match command.data.name.as_str() {
                   "hello" => "hello".to_owned(),
                   command => unreachable!("Unknown command: {}", command),
               };
           // send `response_content` to the discord server
           command.create_interaction_response(&ctx.http, |response| {
               response
                   .kind(InteractionResponseType::ChannelMessageWithSource)
                   .interaction_response_data(|message| message.content(response_content))
           })
               .await.expect("Cannot respond to slash command");
       }
   }
}

In the ready method of the event handler, replace * guild_id * on the third line with your server ID.

If your code is still running in the terminal, restart it. When you see your bot online on your server, send a /hello message. You should see a response from the bot saying hello in response.

As with message responses, you can program your bot to respond to any custom commands with custom responses by following the steps we covered above.

Deploying the Discord bot to the Shuttle server

Running your project on your system can have disadvantages. More complex bots may require large resources to run and serve every user.

Deploying your bot gives your bot the advantage of not using your computer’s resources to run. It also keeps your bot online, even if you’re not.

Shuttle allows you to deploy your bot to the Shuttle server. To deploy your bot, run this command in your project directory:

cargo shuttle deploy

Conclusion

Building a Discord chat bot in Rust can be a challenging task. But with the right knowledge and tools, it can be done easily.

With the step-by-step instructions provided in this article, anyone with programming experience in Rust and a Discord account can learn to build their own Discord chat bot. If you’re looking for some Discord bots to build, here are some ideas:

  • Welcome bots to welcome new users to a server or channel
  • Game bots for playing trivia, quiz, tic-tac-toe, and other games
  • Media bots that play music or allow users to create or select videos, images, or GIFs to share
  • Poll bots to help users create and send polls
  • Utility bots for automating server functions such as answering FAQs and more

For further reading on Rust Discord bots, check out some Serenity Discord example bots or the Serenity documentation.

Source: https://blog.logrocket.com

#rust #chatbot #discord

Building a Discord Chat Bot in Rust

Dashboard for Managing Rally Discord Bot Built using Vuejs

Rally Discord Bot Dashboard

Dashboard for managing rally discord bot built using vuejs, a tour of the UI is available in the getting started guide. This app is ready to be deployed on netlify. On deploy it is required to set the CLIENT_ID and BOT_API enviroment variables.

  • CLIENT_ID – app client ID obtained from discord
  • BOT_API – base url for the bot API, more info here on setting up the bot and API

Also add the following redirect URIs to your app on discord BASE_URL/ and BASE_URL/dashboard/home.

DEMO

Netlify Deploy

If self hosting is not your thing you can start using the dashboard right away on the official site by visiting https://rallybot.app

Screenshot

screehot

TODO

Setup

  • Project
  • Components
  • Router
  • Store
  • I18n
  • Fetch API utils

Implement

  • Discord API intergration
  • Rally API intergration
  • Rally role bot API intergration(bot setup, commands, set role mapping, get role mappings etc)
  • Feature request form
  • Notification system
  • SSO
  • Tests

Development

Clone the repo

git clone https://github.com/Ju99ernaut/rally-discordbot-dashboard

Navigate into the repo

cd rally-discordbot-dashboard

Install dependencies

npm install

Start dev server

npm run serve

Production Build

npm run build

Lint files

npm run lint

Configuration

Add BASE_URL/ and BASE_URL/dashboard/home to your discord app’s redirect URIs

Fill in the config.js file

SettingDescription
homeBase URL of the dashboard site
clientIddiscord client ID
botApiBase URL for the discord bot API
githubHomerepo homepage

config.js example

export default {
    home: "http://localhost:8080/",
    clientId: "786246670530773023",
    botApi: "http://localhost:8000",
    githubHome: "https://github.com/Ju99ernaut/rally-discordbot-dashboard",
    //...
}

feature request form

You will have to set it up in src/pages/FeatureRequest.vue

example google forms setup

create a google form with title and description field then click get prefilled link, you will get something like: https://docs.google.com/forms/d/e/formID/formResponse?inputid1=""&inputid2="" Fill in the submitRequest as shown below

submitRequest() {
    const obj = {
        "inputid1": this.title,
        "inputid2": this.description,
    };
    fetch(
        "https://docs.google.com/forms/d/e/" +
          "formID/formResponse" +
          queryString(obj),
        {
          mode: "no-cors",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
    });
    //...
},

Download details:

Author: FAKEFREESEXS
Source code: https://github.com/FAKEFREESEXS/dark?ref=vuejsexamples.com

License: MIT license

#vue #vuejs #discord 

Dashboard for Managing Rally Discord Bot Built using Vuejs
Edwina  Namiiro

Edwina Namiiro

1676425260

How to Build a Discord Bot for Blockchain Events

In this Blockchain tutorial, we learn about What is a Discord Bot? | How to Build a Discord Bot for Blockchain Events. When it comes to crypto communities, Discord is an extremely popular platform. Hence, we want to show you how to build a Discord bot for on-chain events, and thanks to the Moralis Streams API, you can build a crypto monitor Discord bot effortlessly. All it takes is a free Moralis account, a Discord server, and some simple JavaScript programming. Moreover, building a Discord bot is a lot simpler than you might think, and in this article, we’re going to accomplish this in five simple steps:

  1. Setting Up a Simple NodeJS Express Backend   
  2. Adding a New Moralis Stream 
  3. Verifying the Webhook Sender
  4. Setting Up a Discord Bot 
  5. Implementing an Example Blockchain Discord Bot  

Furthermore, it shouldn’t take more than twenty minutes to set things up. Also, thanks to Moralis’ cross-chain interoperability, the best thing about our Discord bot is that you can listen to any on-chain event on Ethereum and other EVM-compatible chains. But, for the sake of this tutorial, we’ll focus on the Polygon testnet (Mumbai).

Moving forward, we’ll first ensure that you all know what a Discord bot is. Then, we’ll dive into today’s tutorial. However, before we show you how to build a Discord bot, we’ll take a look at a demo, which will help you better understand what a crypto monitor Discord bot is. In addition, by seeing our demonstration, you’ll also be able to decide whether or not you want to focus on building a Discord bot for your own purposes. With that said, if you already know what a Discord bot is, feel free to dive right into our blockchain Discord bot tutorial.   

What is a Discord Bot?

If you’ve done any online shopping, you’ve probably encountered chatbots. These bots are programs that help automate certain processes. Moreover, when these sorts of AI-driven tools are used to automate tasks on Discord servers, they are called Discord bots. As you may know, Discord servers offer many features, many of which can be automated. 

Showing a crypto Discord bot on a user's smartphone.

So, what exactly is a blockchain Discord bot? It is a Discord bot that triggers a specific action on a specific Discord server when a particular on-chain event (the one that the bot listens to) occurs. Hence, a crypto monitor Discord bot is a very practical tool for all sorts of crypto Discord communities. After all, it can add a lot of value to private and public Discord channels. 

Discord logo next to a virtual bot.

It’s also worth mentioning that the Discord bot feature is available on Discord’s developer portal. As such, you don’t have to do any serious coding to create Discord bots. Instead, you can simply select among the given options and use Discord’s pre-built solutions. You’ll get to see this, as we show you how to build a Discord bot in the section below. 

How to Build a Discord Bot for Blockchain Events

Building a Discord bot for crypto is effortless, thanks to Moralis’ Streams API. This powerful tool enables you to stream blockchain data into your backend (in this case, Discord’s backend) via webhooks. To access this powerful tool, you only need a free Moralis account. Of course, you also need to decide what on-chain events interest you. This will determine whether you can listen to an existing smart contract or if you’ll need to create and deploy your smart contract first. However, for the sake of this tutorial, we’ll use an existing smart contract. In fact, to avoid any confusion, start by focusing on our example Web3 contract. 

Also, to build your own crypto monitor Discord bot following our lead, you will need the following tools:

  • A Moralis account, which you can create for free!
  • Some type of code editor or IDE. We’ll be using Visual Studio Code (VSC). 
  • A Discord server and access to Discord’s developer portal.
  • A blockchain explorer. Our example Web3 contract is on the Mumbai network, so we’ll be using PolygonScan.
  • The Postman platform (optional). This is a tool to help you make API calls to different posts, get endpoints, etc.

Discord.js Basics with Discord title.

Moreover, we’ll take you through the following steps:

  1. Setting Up a Simple NodeJS Express Backend   
  2. Adding a New Moralis Stream 
  3. Verifying the Webhook Sender
    1. You need to ensure that only Moralis can make a webhook post.
  4. Setting Up a Discord Bot   
  5. Implementing an Example Blockchain Discord Bot
    1. Sending messages with Discord.js

Now, as mentioned above, before we show you how to build a Discord bot, let’s take a look at a demonstration. 

Our Crypto Monitor Discord Bot – Demo

So, this is our example Discord server, which we created for the sake of this tutorial:

Showing a Discord channel that displays a message that says Build a Blockchain Discord Bot!

Looking at the above screenshot, you can see our crypto monitor Discord bot (“DonationBot”) in the right sidebar. Next, we use PolygonScan to interact with our example “donationExample” smart contract. Obviously, this is the smart contract that our example blockchain Discord bot listens to.

Showing a Web3 wallet modal with a confirmed transaction.

The above image shows you that by clicking on the “Write” button on PolygonScan’s page for our example Web3 contract, we actually execute an on-chain transaction using MetaMask. Also, as you can see above, we donated six MATIC tokens. Finally, as soon as our transaction goes through, our Discord bot posts a message informing our Discord members about this donation:

As you can see, the message includes the donor’s address and the donated amount. However, the key point is that the on-chain event (a donation transaction) triggered our Discord bot. 

If you find this feature useful, make sure to follow our lead in the upcoming sections, where we’ll cover building a Discord bot that listens to on-chain events (like the one presented in this demo). 

Setting Up a Simple NodeJS Express Backend   

If you want to learn how to build a Discord bot for on-chain events the easy way, start with a simple NodeJS Express dapp. You can find the starter code in our GitHub repo for this tutorial. Also, make sure you have “ngrok” installed to create a “ngrok” tunnel to your Express dapp. To do this, open a new terminal and enter the following command:

ngrok http 3000

Note: In case you are using a different port, make sure to replace “3000” accordingly.

As a result of running the above command, you will get an address where your Express dapp will be running:

Next, you want to install all the dependencies with this command:

npm i express moralis discord.js dotenv

Moreover, we recommend that you also install “nodemon” so that you’ll be able to view changes without needing to stop and restart your server. Hence, also use the command below:

npm i nodemon

With the dependencies in place, open your “package.json” file and add the “start” script for “nodemon“:

Finally, you are ready to run your dapp using the command below:

npm run start

Adding a New Moralis Stream

With your dapp running, it’s time to create a new Moralis Stream. To do this, you need your Moralis account. So, in case you haven’t created your account yet, do so now. Using your credentials, you’ll access your admin area. From there, you’ll be able to go to the “Streams” page, where you need to click on the “New Stream” button:

Showing Moralis' Streams landing page with an API key credential.

Then, select the “Create From Scratch” option:

User clicking on the Create From Scratch button on the Streams page.

Next, you need to enter several details related to the smart contract you want to listen to. This is an essential step of the “how to build a Discord bot” process. Moreover, in the future, you’ll want to use your own smart contract or other already deployed contracts. However, for the sake of this tutorial, we recommend you use our example smart contract (the “exampleDonation” contract).

Obtaining and Entering Smart Contract Details

By focusing on the “exampleDonation” contract, go to PolygonScan and copy this smart contract’s address:

Showing a contract's address on PolygonScan.

Then, return to your “Add new Stream” window and paste the above-copied address into the designated spot:

Moving on, scroll down to add your new Moralis Stream’s description. This can be whatever you want; however, to avoid any unnecessary confusion, you can use “New Donation”:

Description of the user's blockchain Discord bot project - New Donation.

Next, paste your “ngrok“ address in the “Webhook URL” entry field and add “/webhook” at the end: 

Entering webhook as the URL.

As far as the tag goes, you can go with “NewDonation”:

Tag for the project is NewDonation.

When it comes to selecting networks, you need to make sure you select the network on which the smart contract you want to listen to is. If you remember, the “exampleDonation” contract is on Polygon’s testnet. Thus, make sure to select the “Polygon Mumbai” option:

Showing the user to click on the Polygon Mumbai network.

Then, you want to select the “Native Transactions” option (donations are made in MATIC):

Checmarking the Native Transaction option.

Furthermore, make sure to turn on “Event Emittance”:

Enabling Event Emittance.

Next, return to PolygonScan to copy the smart contract’s ABI:

User copying the contract's ABI address.

By pasting the copied ABI in the designated area, you’ll get to select the event of this smart contract:

Pasting the ABI into the designated area.

Finally, create your new Moralis Stream by clicking on the “Create Stream” button in the bottom-right corner. As a result, you should get the “New Stream Created” success message. You should also be able to see your Moralis Stream at the bottom of the “Stream” page:

Seeing the New Stream Created message.

You can now test your Moralis Stream. To see exactly how to do that, use the video at the bottom of the article, starting at 5:36.

Verifying Webhook Sender 

With the current “index.js” code (as provided in the “starter.js” file”), anyone with your webhook address can make a post request. As such, you must implement the necessary tweaks to verify the webhook sender. First, import Moralis at the top of your “index.js” file:

const Moralis = require("moralis").default;

Then, initialize an instance of Moralis by adding the following lines of code:

Moralis.start({
  apiKey: process.env.APIKEY,
})

Looking at the lines of code above, you see that you need your Moralis Web3 API key. You need to copy it from your Moralis admin area:

Copying the Web3 API key on the Web3 API page on Moralis' Admin Panel.

Next, return to VSC, create a new file (“.env”), and paste your Web3 key next to “APIKEY”:

The .env file inside VSC.

With your Web3 API key in place, return to the “index.js” file and require “dotenv” at the top:

require("dotenv").config();

Now, you want to make sure that your dapp starts only after starting Moralis by putting “app.listen” inside “then”:

Moralis.start({
  apiKey: process.env.APIKEY,
}).then(() => {
  app.listen(port, () => {
    console.log(`Listening to streams`);
  });
});

Then, you also want to look at “headers” and add Moralis’ “verifySignature”:

Seeing the verifySignature code snippet.

Note: We encourage you to test your current progress by following our in-house expert’s lead (video below at 10:20). This is where you’ll use Postman.

Setting Up a Discord Bot   

Demonstrating how to build a Discord bot wouldn’t be complete without us showing you how to set up a Discord bot. So, start by going to your Discord account. There, create a new server (“Blockchain Notify”). If you’ve never created a Discord server before, make sure to use the video below (11:30). 

Once you have your server ready, it’s time to add a new Discord bot to that server. To do that, visit Discord’s developer portal and sign in. Then go to the “Applications” page and click on the “New Application” button:

Adding a Discord blockchain bot on the applications page on discord.com.

Next, name your application, check the box, and hit the “Create” button: 

The box where a user can name their application and click on create.

You can also add an icon to your application:

General Information page.

Then, you want to select the “Bot” option, click on the “Add Bot” button, and confirm with a click on “Yes, do it!”:

The module showing a message that says Add a Bot to this App.

Moving forward, you want to expand “OAuth2” and click on the “URL Generator” option:

User checkmarking the "bot" option.

Next, as indicated in the image above, check the “bot” scope. Then, scroll down and check the “Send Message” permission:

User checking the Send Message permission.

As shown in the above screenshot, copy the generated URL. By pasting that URL into your browser, you’ll be able to select a server to which you want to add that bot:

Discord.com page showing the prompt box asking if user wants to add a blockchain Discord bot.

To finalize this step of building a Discord bot for crypto, you’ll also need to click on the “Authorize” button and confirm that you are human:

Checkmarking the I Am Human message.

Now, you can close that tab and visit your Discord. If you’ve followed our instructions, you should now have the “DonationBot” bot in your “Blockchain Notify” Discord server:

Showing the DonationBot on the Discord server.

Implementing an Example Blockchain Discord Bot – Sending Messages with Discord.js

In this final step of our “how to build a Discord bot” quest, you need to add the necessary lines of code to ensure that the above-created bot becomes a crypto monitor Discord bot. Hence, return to your “index.js” script and import “discord.js” at the top:

const discord = require("discord.js");   

Next, create a Discord client just below the imports:

const client = new discord.Client({
    intents: [],
  });

client.login(process.env.PASS);

Looking at the bottom line of the code above, you can see that you need to add the “PASS” variable to your “.env” file. To get this variable, return to your “DonationBot” application (the “Bot” option) and click on the “Reset Token” button. Then copy the token:

User copying. the token.

Moving on, go to your “.env” file, create the “PASS” variable, and paste in the above-copied token:

Inside the .env file in VSC.

Next, go to your Discord server, and copy your channel ID (right-click on the channel in which you want your bot to post messages):

User copying the ID.

Return to the “.env” file and create a new variable that will store the above-copied ID:

User pasting the ID into the channel variable inside VSC.

With your variables in place, you can add the necessary lines of code inside “try”:

    let from = body.txs[0].fromAddress;
    let amount = Number(body.txs[0].value / 1E18);

    const channel = await client.channels.fetch(process.env.CHANNEL);
    channel.send(`New Donation submitted by ${from}, for ${amount.toFixed(2)} MATIC!!!!`);

Note: You can access the final code on GitHub.

With the above lines of code in place, you have successfully completed all five steps involved in the “how to build a Discord bot” implementation. Now, make sure to take your bot for a spin. For guidance, use the video below (17:34).

Last but not least, here’s the video version of our “how to build a Discord bot” tutorial we’ve been referencing throughout the article:

Blockchain Discord Bot – Build a Discord Bot for On-Chain Events – Summary

We covered quite a distance in today’s article. First, you had a chance to learn what a Discord bot is. We also made sure you know what a crypto monitor Discord bot is. With the basics under your belt, you had an opportunity to follow our lead. Moreover, by taking you through the five primary steps, we provided you with all the details related to building a Discord bot. These five steps included:

  1. Setting Up a Simple NodeJS Express Backend   
  2. Adding a New Moralis Stream 
  3. Verifying the Webhook Sender
  4. Setting Up a Discord Bot 
  5. Implementing an Example Blockchain Discord Bot  

Nonetheless, we also shared a video tutorial containing additional details about building a Discord bot for on-chain events. 

Original article sourced at:  https://moralis.io

#blockchain #discord

How to Build a Discord Bot for Blockchain Events