1677170040
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:
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.
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.
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:
Enter a name for your application:
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:
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:
Nella sezione "Build-A-Bot", fai clic sul pulsante "Aggiungi bot" per creare il bot:
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:
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":
Nel menu del generatore di URL sotto "AMBITI", seleziona l'opzione "bot":
Scorri più in basso nella pagina fino a "PERMESSI BOT" e seleziona l'opzione "Amministratore" per concedere i privilegi di amministratore del bot:
Scorri fino alla fine della pagina e copia l'URL generato in basso, quindi apri l'URL generato nel tuo browser:
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:
When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.
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.
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":
Fare clic su "Copia" per copiare il token:
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.
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.
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.
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.
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:
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.
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
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:
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
1677166392
了解如何使用 Shuttle 和 Serenity 在 Rust 中構建 Discord 機器人。了解如何在 Discord 中創建機器人,將機器人添加到您的服務器,並將您的 Rust 代碼連接到您的機器人。
Discord 機器人可以為服務器所有者和員工節省大量時間和精力,同時還可以為用戶提供各種有用的功能。您可以在 Discord 中使用機器人來自動執行重複性任務和任務,否則這些任務會佔用大量時間和精力。
在本文中,您將學習如何在 Discord 中創建機器人,將機器人添加到您的服務器,以及將您的 Rust 代碼連接到您的機器人。
目錄:
要閱讀本文,您至少需要對 Discord 有一定程度的熟悉。您還應該擁有一個 Discord 帳戶、您擁有的 Discord 服務器以及一些 Rust 編程經驗。
在 Discord 中設置機器人可能有點棘手,尤其是如果這是您第一次這樣做的話。在本節中,我將指導您為您的服務器設置機器人。
Discord 應用程序是一種在 Discord 用戶和您的代碼之間提供接口的服務。應用程序提供的界面稱為機器人。機器人接收來自用戶的消息並發送響應。
要創建 Discord 應用程序,請首先在瀏覽器中登錄您的 Discord 帳戶。接下來,在瀏覽器中打開Discord 開發人員門戶,然後單擊頁面右上角標有“新建應用程序”的按鈕:
為您的應用程序輸入一個名稱:
單擊標有“創建”的按鈕創建應用程序。如果操作成功完成,您將看到如下所示的儀表板:
在本節中,您將為 Discord 應用程序創建機器人。在網頁的左側窗格中,單擊“Bot”以打開 bot 菜單:
在“Build-A-Bot”部分下,單擊“Add Bot”按鈕創建機器人:
單擊此按鈕後,您將成功創建 Discord 機器人。最後,激活“MESSAGE CONTENT INTENT”選項,以便機器人可以接收來自您 Discord 服務器中用戶的消息:
在設置你的機器人時你需要做的最後一件事是將它安裝到你的服務器上。在左側導航窗格中,單擊“OAuth2”菜單項以切換下拉菜單。在此下拉列表中,單擊“URL 生成器”選項:
在“SCOPES”下的 URL Generator 菜單中,勾選“bot”選項:
向下滾動頁面至“BOT PERMISSIONS”並勾選“管理員”選項以授予機器人管理員權限:
滾動到頁面底部並複制底部生成的 URL,然後在瀏覽器中打開生成的 URL:
在導航到生成的 URL 後打開的網頁中,選擇要安裝機器人的服務器。單擊“繼續”繼續。
在下一個屏幕上,單擊“授權”。然後該網頁將提示您驗證您是人類:
完成這些步驟後,打開服務器的成員列表。您應該會看到您的機器人被列為成員。
在本節中,我將指導您為 Discord 機器人設置 Rust 代碼環境。代碼環境將包含開始構建機器人所需的代碼和包。
要設置項目,我們將使用一個名為 Shuttle 的工具。Shuttle 允許您在 Rust 中初始化、構建和部署各種項目。
對於這個項目,我們將使用 Shuttle 來初始化一個 Serenity 項目。Serenity 是一個用 Rust 構建 Discord 聊天機器人的框架。
要初始化 Serenity 項目,請為您希望項目所在的位置創建一個新目錄。然後,使用以下命令安裝 Shuttle:
cargo install cargo-shuttle
接下來在目錄下初始化一個項目:
cargo shuttle init --serenity
最後,構建項目:
cargo build
如果您正確地執行了這些步驟,您應該會看到您的目錄中充滿了入門所需的代碼。
我們在上一節中生成的代碼src/lib.rs是一個基本項目,您可以連接到您的機器人,我們將在本節中逐步執行此操作。
為了成功地將您的代碼連接到您的機器人,您首先需要獲取您的機器人令牌。機器人令牌是對您的機器人的引用。每個機器人都有一個唯一的參考,您可以使用它來將代碼庫連接到您的機器人。
要檢索您的機器人令牌,請先打開 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
您可以按照上述步驟對機器人進行編程,以使用自定義響應來響應任何自定義消息。
命令是與機器人交互的更直接的方式。與消息不同,命令以/斜杠開頭——例如,/hello。
您可以像發送消息一樣在 Discord 中發送命令,但它們是與機器人交互的首選方式,因為您可以輕鬆分辨哪些消息是命令,哪些消息不是。
要讓您的機器人響應命令,您需要安裝機器人的服務器的 ID。為了獲取服務器ID,您需要先在您的帳戶上啟用開發者模式。
開發人員模式是一種 Discord 設置,可讓開發人員在服務器中提升權限。在本節中,我將指導您在您的系統上啟用開發者模式,以便您可以復制您的服務器 ID 並使您的機器人能夠響應命令。
在窗口底部,單擊用戶名旁邊的設置圖標。在左窗格中,選擇“應用程序設置”下的“外觀”。
在外觀設置菜單中,單擊“高級”以打開高級設置菜單,然後您可以在其中切換“開發人員模式”選項。最後,右鍵單擊服務器名稱並選擇“複製ID”以復制服務器ID。
在窗口底部,單擊用戶名旁邊的設置圖標。在左側窗格中,選擇“APP SETTINGS”下的“Advanced”以打開高級設置菜單,然後您可以在其中切換“Developer Mode”選項。
然後,右鍵單擊服務器名稱並選擇“複製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作為回應。
與消息響應一樣,您可以按照我們上面介紹的步驟對您的機器人進行編程,以使用自定義響應來響應任何自定義命令。
在您的系統上運行您的項目可能有缺點。更複雜的機器人可能需要大量資源才能運行並為每個用戶提供服務。
部署您的機器人可以讓您的機器人獲得不使用計算機資源運行的優勢。它還可以使您的機器人保持在線,即使您不在線也是如此。
Shuttle 允許您將機器人部署到 Shuttle 服務器。要部署您的機器人,請在您的項目目錄中運行此命令:
cargo shuttle deploy
在 Rust 中構建 Discord 聊天機器人可能是一項具有挑戰性的任務。但是有了正確的知識和工具,它可以很容易地完成。
通過本文中提供的分步說明,任何具有 Rust 編程經驗和 Discord 帳戶的人都可以學習構建自己的 Discord 聊天機器人。如果你正在尋找一些要構建的 Discord 機器人,這裡有一些想法:
如需進一步閱讀 Rust Discord 機器人,請查看一些Serenity Discord 示例機器人或Serenity 文檔。
資料來源: https: //blog.logrocket.com
#rust #chatbot #discord
1677162720
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:
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 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.
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:
Enter a name for your application:
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:
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:
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:
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:
In the URL Generator menu under “SCOPES,” tick the “bot” option:
Scroll farther down the page to “BOT PERMISSIONS” and tick the “Administrator” option to give the bot admin privileges:
Scroll to the bottom of the page and copy the generated URL on the bottom, then open the generated URL in your browser:
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:
When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.
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.
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:
Click “Copy” to copy the token:
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.
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.
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.
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.
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:
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.
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
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:
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
1677159060
เรียนรู้วิธีสร้างบอท Discord ใน Rust ด้วย Shuttle และ Serenity เรียนรู้วิธีสร้างบอทใน Discord เพิ่มบอทไปยังเซิร์ฟเวอร์ของคุณ และเชื่อมต่อรหัส Rust กับบอทของคุณ
บอท Discord สามารถช่วยเจ้าของเซิร์ฟเวอร์และพนักงานลงแรงและเวลาได้มาก ในขณะเดียวกันก็มอบคุณสมบัติที่มีประโยชน์มากมายให้กับผู้ใช้ คุณสามารถใช้บอทใน Discord เพื่อทำงานซ้ำๆ โดยอัตโนมัติและงานที่ต้องใช้เวลาและความพยายามมาก
ในบทความนี้ คุณจะได้เรียนรู้วิธีสร้างบอทใน Discord เพิ่มบอทไปยังเซิร์ฟเวอร์ของคุณ และเชื่อมต่อรหัส Rust กับบอทของคุณ
สารบัญ:
หากต้องการติดตามบทความนี้ คุณต้องมีความคุ้นเคยกับ Discord ในระดับหนึ่งเป็นอย่างน้อย คุณควรมีบัญชี Discord เซิร์ฟเวอร์ Discord ที่คุณเป็นเจ้าของ และประสบการณ์ในการเขียนโปรแกรมด้วย Rust
การตั้งค่าบอทใน Discord อาจเป็นเรื่องยุ่งยากเล็กน้อย โดยเฉพาะอย่างยิ่งหากนี่เป็นครั้งแรกที่คุณทำ ในส่วนนี้ ฉันจะแนะนำคุณตลอดการตั้งค่าบอทสำหรับเซิร์ฟเวอร์ของคุณ
แอปพลิเคชัน Discord เป็นบริการที่ให้อินเทอร์เฟซระหว่างผู้ใช้ Discord และรหัสของคุณ อินเทอร์เฟซที่แอปพลิเคชันจัดเตรียมให้เรียกว่าบอท บอทได้รับข้อความจากผู้ใช้และส่งการตอบกลับ
หากต้องการสร้างแอปพลิเคชัน Discord ให้ลงชื่อเข้าใช้บัญชี Discord ในเบราว์เซอร์ของคุณก่อน ถัดไป เปิดพอร์ทัลผู้พัฒนา Discordในเบราว์เซอร์ของคุณ แล้วคลิกปุ่ม "แอปพลิเคชันใหม่" ที่ด้านบนขวาของหน้า:
ป้อนชื่อสำหรับแอปพลิเคชันของคุณ:
คลิกปุ่ม "สร้าง" เพื่อสร้างแอปพลิเคชัน หากการดำเนินการเสร็จสมบูรณ์ คุณจะได้รับการต้อนรับด้วยแดชบอร์ดที่มีลักษณะดังนี้:
ในส่วนนี้ คุณจะสร้างบอทสำหรับแอปพลิเคชัน Discord ของคุณ ที่บานหน้าต่างด้านซ้ายของหน้าเว็บ คลิก “บอท” เพื่อเปิดเมนูบอท:
ภายใต้ส่วน “สร้างบอท” ให้คลิกปุ่ม “เพิ่มบอท” เพื่อสร้างบอท:
หลังจากคลิกปุ่มนี้ คุณจะสร้างบอท Discord ได้สำเร็จ หากต้องการสิ้นสุด ให้เปิดใช้งานตัวเลือก “ข้อความแสดงเจตนา” เพื่อให้บอทสามารถรับข้อความจากผู้ใช้ในเซิร์ฟเวอร์ Discord ของคุณ:
สิ่งสุดท้ายที่คุณต้องทำในการตั้งค่าบอทคือติดตั้งลงในเซิร์ฟเวอร์ของคุณ ในบานหน้าต่างนำทางด้านซ้าย คลิกรายการเมนู “OAuth2” เพื่อสลับรายการแบบเลื่อนลง ในดร็อปดาวน์นี้ ให้คลิกตัวเลือก “ตัวสร้าง URL”:
ในเมนูตัวสร้าง URL ใต้ “ขอบเขต” ให้ทำเครื่องหมายที่ตัวเลือก “บอท”:
เลื่อนลงไปด้านล่างของหน้าไปที่ “BOT PERMISSIONS” และทำเครื่องหมายที่ตัวเลือก “Administrator” เพื่อให้สิทธิ์ของผู้ดูแลระบบ bot:
เลื่อนไปที่ด้านล่างของหน้าและคัดลอก URL ที่สร้างขึ้นที่ด้านล่าง จากนั้นเปิด URL ที่สร้างขึ้นในเบราว์เซอร์ของคุณ:
ในหน้าเว็บที่เปิดขึ้นหลังจากที่คุณนำทางไปยัง URL ที่สร้างขึ้น ให้เลือกเซิร์ฟเวอร์ที่คุณต้องการติดตั้งบอท คลิก “ดำเนินการต่อ” เพื่อดำเนินการต่อ
ในหน้าจอถัดไป ให้คลิก "อนุญาต" หน้าเว็บจะแจ้งให้คุณยืนยันว่าคุณเป็นมนุษย์:
เมื่อทำตามขั้นตอนเหล่านี้เสร็จแล้ว ให้เปิดรายชื่อสมาชิกของเซิร์ฟเวอร์ คุณควรเห็นบอตของคุณแสดงรายการเป็นสมาชิก
ในส่วนนี้ ฉันจะแนะนำคุณตลอดการตั้งค่าสภาพแวดล้อมรหัสสนิมสำหรับบอท Discord ของคุณ สภาพแวดล้อมรหัสจะมีรหัสและแพ็คเกจที่จำเป็นสำหรับคุณในการเริ่มต้นสร้างบอท
ในการตั้งค่าโครงการ เราจะใช้เครื่องมือที่เรียกว่า Shuttle Shuttle ช่วยให้คุณเริ่มต้น สร้าง และปรับใช้โครงการต่างๆ ใน Rust
สำหรับโครงการนี้ เราจะใช้ Shuttle เพื่อเริ่มต้นโครงการ Serenity Serenity เป็นเฟรมเวิร์กสำหรับสร้างบอทแชท Discord ใน Rust
ในการเริ่มต้นโครงการ Serenity ให้สร้างไดเร็กทอรีใหม่สำหรับตำแหน่งที่คุณต้องการให้โครงการของคุณอยู่ จากนั้นติดตั้ง Shuttle ด้วยคำสั่งด้านล่าง:
cargo install cargo-shuttle
ถัดไป เริ่มต้นโครงการในไดเร็กทอรี:
cargo shuttle init --serenity
สุดท้าย สร้างโครงการ:
cargo build
หากคุณทำตามขั้นตอนเหล่านี้อย่างถูกต้อง คุณควรเห็นไดเร็กทอรีของคุณเต็มไปด้วยโค้ดที่จำเป็นสำหรับการเริ่มต้นใช้งาน
โค้ดsrc/lib.rs— ที่เราสร้างขึ้นในส่วนที่แล้ว — เป็นโปรเจ็กต์พื้นฐานที่คุณสามารถเชื่อมต่อกับบอทของคุณ ซึ่งเราจะทำทีละขั้นตอนในส่วนนี้
ในการเชื่อมต่อรหัสของคุณกับบอทให้สำเร็จ คุณต้องได้รับโทเค็นบอทของคุณก่อน โทเค็นบอทคือการอ้างอิงถึงบอทของคุณ บอททุกตัวมีการอ้างอิงที่ไม่ซ้ำกันซึ่งคุณสามารถใช้เชื่อมต่อฐานรหัสกับบอทของคุณได้
ในการดึงโทเค็นบอทของคุณ ก่อนอื่นให้เปิดแดชบอร์ดสำหรับนักพัฒนา 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
คุณสามารถตั้งโปรแกรมบอทให้ตอบกลับข้อความที่กำหนดเองด้วยการตอบกลับที่กำหนดเองตามขั้นตอนด้านบน
คำสั่งเป็นวิธีที่ตรงกว่าในการโต้ตอบกับบอท ไม่เหมือนข้อความ คำสั่งเริ่มต้นด้วยเครื่องหมายทับ/— เช่น/hello
คุณสามารถส่งคำสั่งใน Discord ได้ด้วยวิธีเดียวกับที่คุณส่งข้อความ แต่เป็นวิธีที่นิยมใช้ในการโต้ตอบกับบอท เพราะคุณสามารถบอกได้อย่างง่ายดายว่าข้อความใดเป็นคำสั่งและข้อความใดไม่ใช่ข้อความ
ในการอนุญาตให้บอทของคุณตอบสนองต่อคำสั่ง คุณต้องมี ID ของเซิร์ฟเวอร์ที่คุณติดตั้งบอท ในการรับ ID เซิร์ฟเวอร์ คุณต้องเปิดใช้งานโหมดผู้พัฒนาในบัญชีของคุณก่อน
โหมดผู้พัฒนาคือการตั้งค่า Discord ที่ให้สิทธิ์ระดับสูงแก่นักพัฒนาในเซิร์ฟเวอร์ ในส่วนนี้ ฉันจะแนะนำคุณตลอดการเปิดใช้โหมดผู้พัฒนาในระบบของคุณ เพื่อให้คุณสามารถคัดลอก ID เซิร์ฟเวอร์ของคุณและเปิดใช้งานบอทของคุณเพื่อตอบสนองต่อคำสั่ง
ที่ด้านล่างของหน้าต่าง คลิกไอคอนการตั้งค่าใกล้กับชื่อผู้ใช้ของคุณ ในบานหน้าต่างด้านซ้าย เลือก "ลักษณะที่ปรากฏ" ภายใต้ "การตั้งค่าแอป"
ในเมนูการตั้งค่ารูปลักษณ์ ให้คลิก "ขั้นสูง" เพื่อเปิดเมนูการตั้งค่าขั้นสูง ซึ่งคุณสามารถสลับตัวเลือก "โหมดนักพัฒนาซอฟต์แวร์" ได้ สุดท้าย คลิกขวาที่ชื่อเซิร์ฟเวอร์แล้วเลือก “คัดลอก 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ตอบกลับ
เช่นเดียวกับการตอบกลับข้อความ คุณสามารถตั้งโปรแกรมบอทของคุณให้ตอบสนองต่อคำสั่งที่กำหนดเองด้วยการตอบกลับที่กำหนดเองโดยทำตามขั้นตอนที่เรากล่าวถึงข้างต้น
การดำเนินโครงการของคุณในระบบของคุณอาจมีข้อเสีย บอทที่ซับซ้อนมากขึ้นอาจต้องการทรัพยากรจำนวนมากเพื่อเรียกใช้และให้บริการผู้ใช้ทุกคน
การปรับใช้บอททำให้บอทได้รับประโยชน์จากการไม่ใช้ทรัพยากรของคอมพิวเตอร์ในการทำงาน นอกจากนี้ยังช่วยให้บอทของคุณออนไลน์ แม้ว่าคุณจะไม่ได้อยู่ก็ตาม
Shuttle ช่วยให้คุณสามารถปรับใช้บอทของคุณกับเซิร์ฟเวอร์ Shuttle ในการปรับใช้บอทของคุณ ให้รันคำสั่งนี้ในไดเร็กทอรีโปรเจ็กต์ของคุณ:
cargo shuttle deploy
การสร้างบอทแชท Discord ใน Rust อาจเป็นงานที่ท้าทาย แต่ด้วยความรู้และเครื่องมือที่เหมาะสมก็สามารถทำได้โดยง่าย
ด้วยคำแนะนำทีละขั้นตอนในบทความนี้ ทุกคนที่มีประสบการณ์การเขียนโปรแกรมใน Rust และบัญชี Discord สามารถเรียนรู้วิธีสร้างบอทแชท Discord ของตนเองได้ หากคุณกำลังมองหาบอท Discord เพื่อสร้าง นี่คือแนวคิดบางประการ:
หากต้องการอ่านเพิ่มเติมเกี่ยวกับบ็อต Rust Discord โปรดดู ตัวอย่างบ็ อต Serenity Discordหรือเอกสารประกอบของ Serenity
ที่มา: https://blog.logrocket.com
#rust #discord #chatbot
1677155400
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:
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.
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.
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:
Introduzca un nombre para su aplicación:
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í:
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:
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:
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:
In the URL Generator menu under “SCOPES,” tick the “bot” option:
Scroll farther down the page to “BOT PERMISSIONS” and tick the “Administrator” option to give the bot admin privileges:
Scroll to the bottom of the page and copy the generated URL on the bottom, then open the generated URL in your browser:
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:
When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.
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.
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":
Haga clic en "Copiar" para copiar el token:
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.
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.
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.
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.
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:
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.
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
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:
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
1677151740
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:
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 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.
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 :
Saisissez un nom pour votre application :
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 :
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 :
Sous la section "Build-A-Bot", cliquez sur le bouton "Add Bot" pour créer le bot :
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 :
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":
Dans le menu Générateur d'URL sous "SCOPES", cochez l'option "bot" :
Faites défiler la page jusqu'à "PERMISSIONS BOT" et cochez l'option "Administrateur" pour donner des privilèges d'administrateur au bot :
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 :
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 :
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.
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.
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":
Cliquez sur "Copier" pour copier le jeton :
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.
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.
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.
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.
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 :
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.
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
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 :
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
1677148080
Shuttle と Serenity を使用して Rust で Discord ボットを作成する方法を学びます。Discord でボットを作成する方法、ボットをサーバーに追加する方法、および Rust コードをボットに接続する方法を学びます。
Discord ボットは、ユーザーにさまざまな便利な機能を提供しながら、サーバーの所有者とスタッフ メンバーの多くの時間と労力を節約できます。Discord でボットを使用して、反復的なタスクや、そうでなければ多くの時間と労力がかかるタスクを自動化できます。
この記事では、Discord でボットを作成し、ボットをサーバーに追加し、Rust コードをボットに接続する方法を学習します。
目次:
この記事を読み進めるには、少なくともある程度の Discord の知識が必要です。また、Discord アカウント、所有する Discord サーバー、および Rust のプログラミング経験も必要です。
Discord でボットをセットアップするのは、特にこれが初めての場合は少し難しい場合があります。このセクションでは、サーバー用にボットをセットアップする方法について説明します。
Discord アプリケーションは、Discord ユーザーとコードの間のインターフェースを提供するサービスです。アプリケーションが提供するインターフェースはボットと呼ばれます。ボットはユーザーからメッセージを受信し、応答を送信します。
Discord アプリケーションを作成するには、まずブラウザで Discord アカウントにログインします。次に、ブラウザでDiscord 開発者ポータルを開き、ページの右上にある [新しいアプリケーション] というラベルの付いたボタンをクリックします。
アプリケーションの名前を入力してください:
「作成」というラベルの付いたボタンをクリックして、アプリケーションを作成します。アクションが正常に完了すると、次のようなダッシュボードが表示されます。
このセクションでは、Discord アプリケーションのボットを作成します。Web ページの左側のペインで、[ボット] をクリックしてボット メニューを開きます。
「Build-A-Bot」セクションで、「Add Bot」ボタンをクリックしてボットを作成します。
このボタンをクリックすると、Discord ボットが正常に作成されます。最後に、「MESSAGE CONTENT INTENT」オプションを有効にして、ボットが Discord サーバーのユーザーからメッセージを受信できるようにします。
ボットの設定で最後に行う必要があるのは、ボットをサーバーにインストールすることです。左側のナビゲーション ペインで、[OAuth2] メニュー項目をクリックしてドロップダウンを切り替えます。このドロップダウンで、「URL ジェネレーター」オプションをクリックします。
[スコープ] の下の URL ジェネレーター メニューで、[ボット] オプションにチェックを入れます。
ページをさらに「BOT PERMISSIONS」までスクロールし、「管理者」オプションにチェックマークを付けて、ボットに管理者権限を付与します。
ページの下部までスクロールし、生成された URL を下部にコピーしてから、生成された URL をブラウザーで開きます。
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:
When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.
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.
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:
Click “Copy” to copy the token:
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.
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.
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.
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 をコピーします。
ウィンドウの下部で、ユーザー名の近くにある設定アイコンをクリックします。左側のペインで、「アプリ設定」の下の「詳細」を選択して詳細設定メニューを開き、「開発者モード」オプションを切り替えることができます。
次に、サーバー名を右クリックし、[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 *3 行目をサーバー ID に置き換えます。
コードがまだターミナルで実行されている場合は、再起動します。サーバー上でボットがオンラインになったら、/helloメッセージを送信します。応答で言っているボットからの応答が表示されますhello。
メッセージ応答と同様に、上記の手順に従って、カスタム応答でカスタム コマンドに応答するようにボットをプログラムできます。
システムでプロジェクトを実行すると、欠点が生じる可能性があります。より複雑なボットを実行してすべてのユーザーにサービスを提供するには、大きなリソースが必要になる場合があります。
ボットをデプロイすると、コンピューターのリソースを使用して実行されないという利点がボットにもたらされます。また、そうでない場合でも、ボットをオンラインに保ちます。
Shuttle を使用すると、ボットを Shuttle サーバーにデプロイできます。ボットをデプロイするには、プロジェクト ディレクトリで次のコマンドを実行します。
cargo shuttle deploy
Rust で Discord チャット ボットを構築するのは、困難な作業になる可能性があります。しかし、正しい知識とツールがあれば、簡単に行うことができます。
この記事に記載されている段階的な手順を使用すると、Rust でのプログラミング経験があり、Discord アカウントを持っている人なら誰でも、独自の Discord チャット ボットの作成方法を学ぶことができます。作成する Discord ボットを探している場合は、いくつかのアイデアがあります。
Rust Discord ボットの詳細については、Serenity Discord のサンプル ボットまたはSerenity のドキュメントを参照してください。
#rust #discord #chatbot
1677144420
Узнайте, как создать бота Discord в Rust с помощью Shuttle и Serenity. Узнайте, как создать бота в Discord, добавить бота на свой сервер и подключить свой код Rust к вашему боту.
Боты Discord могут сэкономить владельцам серверов и сотрудникам много времени и усилий, а также предоставить пользователям множество полезных функций. Вы можете использовать ботов в Discord для автоматизации повторяющихся задач и задач, которые в противном случае отняли бы много времени и усилий.
В этой статье вы узнаете, как создать бота в Discord, добавить бота на свой сервер и подключить свой код Rust к вашему боту.
Оглавление:
Чтобы следовать этой статье, вам необходимо хотя бы немного познакомиться с Discord. У вас также должна быть учетная запись Discord, собственный сервер Discord и некоторый опыт программирования на Rust.
Настройка бота в Discord может быть немного сложной, особенно если вы делаете это впервые. В этом разделе я проведу вас через настройку бота для вашего сервера.
Приложение Discord — это служба, которая обеспечивает интерфейс между пользователями Discord и вашим кодом. Интерфейс, который предоставляет приложение, называется ботом. Бот получает сообщения от пользователей и отправляет ответ.
Чтобы создать приложение Discord, сначала войдите в свою учетную запись Discord в браузере. Затем откройте портал разработчика Discord в своем браузере и нажмите кнопку «Новое приложение» в правом верхнем углу страницы:
Введите имя для вашего приложения:
Нажмите кнопку «Создать», чтобы создать приложение. Если действие завершится успешно, вы увидите панель инструментов, которая выглядит следующим образом:
В этом разделе вы создадите бота для своего приложения Discord. На левой панели веб-страницы нажмите «Бот», чтобы открыть меню бота:
В разделе «Build-A-Bot» нажмите кнопку «Добавить бота», чтобы создать бота:
После нажатия этой кнопки вы успешно создали бота Discord. Чтобы закончить, активируйте опцию «MESSAGE CONTENT INTENT», чтобы бот мог получать сообщения от пользователей на вашем сервере Discord:
Последнее, что вам нужно сделать при настройке бота, это установить его на свой сервер. На левой панели навигации щелкните пункт меню «OAuth2», чтобы открыть раскрывающийся список. В этом раскрывающемся списке выберите опцию «Генератор URL»:
В меню «Генератор URL-адресов» в разделе «ОБЛАСТИ» отметьте опцию «бот»:
Прокрутите страницу вниз до «РАЗРЕШЕНИЯ БОТА» и отметьте опцию «Администратор», чтобы предоставить боту права администратора:
Прокрутите страницу вниз и скопируйте сгенерированный URL-адрес внизу, затем откройте сгенерированный URL-адрес в браузере:
На веб-странице, которая откроется после перехода к сгенерированному URL-адресу, выберите сервер, на который вы хотите установить бота. Нажмите «Продолжить», чтобы продолжить.
На следующем экране нажмите «Авторизовать». Затем веб-страница предложит вам подтвердить, что вы человек:
Когда вы закончите с этими шагами, откройте список участников вашего сервера. Вы должны увидеть своего бота в списке участников.
В этом разделе я проведу вас через настройку среды кода Rust для вашего бота Discord. Среда кода будет содержать необходимый код и пакеты, чтобы вы могли приступить к созданию бота.
Для настройки проекта мы будем использовать инструмент под названием Shuttle. Shuttle позволяет вам инициализировать, создавать и развертывать различные проекты на Rust.
В этом проекте мы будем использовать Shuttle для инициализации проекта Serenity. Serenity — это фреймворк для создания чат-ботов Discord на Rust.
Чтобы инициализировать проект Serenity, создайте новый каталог, в котором вы хотите разместить свой проект. Затем установите Shuttle с помощью следующей команды:
cargo install cargo-shuttle
Затем инициализируйте проект в каталоге:
cargo shuttle init --serenity
Наконец, соберите проект:
cargo build
Если вы правильно выполнили эти шаги, вы должны увидеть, что ваш каталог заполнен необходимым кодом для начала работы.
Код src/lib.rs, который мы сгенерировали в предыдущем разделе, — это базовый проект, который вы можете подключить к своему боту, что мы и сделаем шаг за шагом в этом разделе.
Чтобы успешно подключить свой код к боту, вам сначала нужно получить токен бота. Токен бота — это ссылка на вашего бота. У каждого бота есть уникальная ссылка, которую вы можете использовать для подключения базы кода к вашему боту.
Чтобы получить токен бота, сначала откройте панель разработчика 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
Вы можете запрограммировать бота, чтобы он отвечал на любые настраиваемые сообщения с помощью настраиваемых ответов, выполнив шаги, описанные выше.
Команды — это более прямой способ взаимодействия с ботом. В отличие от сообщений, команды начинаются с /косой черты — например, /hello.
Вы можете отправлять команды в Discord так же, как вы отправляете сообщения, но они являются предпочтительным способом взаимодействия с ботами, потому что вы можете легко определить, какие сообщения являются командами, а какие нет.
Чтобы ваш бот мог отвечать на команды, вам понадобится идентификатор сервера, на котором вы установили бота. Чтобы получить идентификатор сервера, вам необходимо сначала включить режим разработчика в своей учетной записи.
Режим разработчика — это параметр 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в ответ.
Как и в случае с ответами на сообщения, вы можете запрограммировать своего бота так, чтобы он отвечал на любые настраиваемые команды с помощью настраиваемых ответов, выполнив шаги, описанные выше.
Запуск вашего проекта в вашей системе может иметь недостатки. Более сложные боты могут потребовать больших ресурсов для запуска и обслуживания каждого пользователя.
Развертывание вашего бота дает вашему боту преимущество, заключающееся в том, что он не использует ресурсы вашего компьютера для работы. Это также держит вашего бота в сети, даже если вы этого не делаете.
Shuttle позволяет развернуть вашего бота на сервере Shuttle. Чтобы развернуть бота, запустите эту команду в каталоге вашего проекта:
cargo shuttle deploy
Создание чат-бота Discord на Rust может оказаться непростой задачей. Но при наличии необходимых знаний и инструментов это можно сделать легко.
С помощью пошаговых инструкций, представленных в этой статье, любой, у кого есть опыт программирования на Rust и учетная запись Discord, может научиться создавать собственного чат-бота Discord. Если вы ищете ботов для Discord, вот несколько идей:
Чтобы узнать больше о ботах Rust Discord, ознакомьтесь с некоторыми примерами ботов Serenity Discord или документацией Serenity .
Источник: https://blog.logrocket.com
#rust #discord #chatbot
1677140723
Shuttle 및 Serenity를 사용하여 Rust에서 Discord 봇을 구축하는 방법을 알아보세요. Discord에서 봇을 만들고, 서버에 봇을 추가하고, Rust 코드를 봇에 연결하는 방법을 알아보세요.
Discord 봇은 서버 소유자와 직원의 시간과 노력을 많이 절약하는 동시에 사용자에게 다양한 유용한 기능을 제공할 수 있습니다. Discord에서 봇을 사용하여 반복적인 작업과 많은 시간과 노력이 필요한 작업을 자동화할 수 있습니다.
이 기사에서는 Discord에서 봇을 만들고, 서버에 봇을 추가하고, Rust 코드를 봇에 연결하는 방법을 배웁니다.
목차:
이 기사를 따라하려면 최소한 Discord에 어느 정도 익숙해야 합니다. 또한 Discord 계정, 소유한 Discord 서버 및 Rust에 대한 약간의 프로그래밍 경험이 있어야 합니다.
Discord에서 봇을 설정하는 것은 약간 까다로울 수 있습니다. 특히 처음 하는 경우에는 더욱 그렇습니다. 이 섹션에서는 서버용 봇 설정 과정을 안내합니다.
Discord 애플리케이션은 Discord 사용자와 코드 간의 인터페이스를 제공하는 서비스입니다. 애플리케이션이 제공하는 인터페이스를 봇이라고 합니다. 봇은 사용자로부터 메시지를 받고 응답을 보냅니다.
Discord 애플리케이션을 만들려면 먼저 브라우저에서 Discord 계정에 로그인하세요. 그런 다음 브라우저에서 Discord 개발자 포털을 열고 페이지 오른쪽 상단에 있는 "새 애플리케이션" 버튼을 클릭합니다.
애플리케이션 이름 입력:
"만들기"라고 표시된 버튼을 클릭하여 애플리케이션을 만듭니다. 작업이 성공적으로 완료되면 다음과 같은 대시보드가 표시됩니다.
이 섹션에서는 Discord 애플리케이션용 봇을 만듭니다. 웹 페이지의 왼쪽 창에서 "봇"을 클릭하여 봇 메뉴를 엽니다.
"Build-A-Bot" 섹션에서 "Add Bot" 버튼을 클릭하여 봇을 생성합니다.
이 버튼을 클릭하면 Discord 봇이 성공적으로 생성됩니다. 마무리하려면 봇이 Discord 서버의 사용자로부터 메시지를 받을 수 있도록 "MESSAGE CONTENT INTENT" 옵션을 활성화합니다.
봇 설정에서 마지막으로 해야 할 일은 서버에 설치하는 것입니다. 왼쪽 탐색 창에서 "OAuth2" 메뉴 항목을 클릭하여 드롭다운을 전환합니다. 이 드롭다운에서 "URL 생성기" 옵션을 클릭합니다.
"범위" 아래의 URL 생성기 메뉴에서 "봇" 옵션을 선택합니다.
"BOT PERMISSIONS"까지 페이지를 더 아래로 스크롤하고 "Administrator" 옵션을 선택하여 봇 관리자 권한을 부여합니다.
페이지 하단으로 스크롤하여 하단에 생성된 URL을 복사한 다음 브라우저에서 생성된 URL을 엽니다.
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:
When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.
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.
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:
Click “Copy” to copy the token:
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.
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 설정입니다. 이 섹션에서는 서버 ID를 복사하고 봇이 명령에 응답할 수 있도록 시스템에서 개발자 모드를 활성화하는 방법을 안내합니다.
창 하단에서 사용자 이름 옆에 있는 설정 아이콘을 클릭합니다. 왼쪽 창에서 "앱 설정" 아래의 "모양"을 선택합니다.
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.
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:
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을 사용하면 Shuttle 서버에 봇을 배포할 수 있습니다. 봇을 배포하려면 프로젝트 디렉터리에서 다음 명령을 실행합니다.
cargo shuttle deploy
Rust에서 Discord 채팅 봇을 구축하는 것은 어려운 작업이 될 수 있습니다. 그러나 올바른 지식과 도구를 사용하면 쉽게 수행할 수 있습니다.
이 기사에 제공된 단계별 지침을 통해 Rust 프로그래밍 경험과 Discord 계정이 있는 사람은 누구나 자신만의 Discord 채팅 봇을 구축하는 방법을 배울 수 있습니다. 빌드할 Discord 봇을 찾고 있다면 다음과 같은 몇 가지 아이디어가 있습니다.
Rust Discord 봇에 대한 자세한 내용은 Serenity Discord 예제 봇 또는 Serenity 문서를 확인하세요 .
#rust #discord #chatbot
1677136860
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:
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.
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.
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:
Digite um nome para seu aplicativo:
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:
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:
Na seção “Build-A-Bot”, clique no botão “Add Bot” para criar o bot:
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:
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”:
No menu Gerador de URL em “ESCOPOS”, marque a opção “bot”:
Role a página até “BOT PERMISSIONS” e marque a opção “Administrator” para dar privilégios de administrador ao bot:
Role até a parte inferior da página e copie a URL gerada na parte inferior e abra a URL gerada em seu navegador:
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:
Quando terminar essas etapas, abra a lista de membros do seu servidor. Você deve ver seu bot listado como membro.
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.
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”:
Clique em “Copiar” para copiar o token:
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.
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.
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.
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.
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:
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.
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
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:
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
1677133200
تعرف على كيفية بناء روبوت Discord في Rust باستخدام Shuttle and Serenity. تعرف على كيفية إنشاء روبوت في Discord ، وإضافة الروبوت إلى الخادم الخاص بك ، وتوصيل كود Rust الخاص بك إلى الروبوت الخاص بك.
يمكن لروبوتات Discord أن توفر لمالكي الخوادم والموظفين الكثير من الوقت والجهد مع توفير مجموعة متنوعة من الميزات المفيدة للمستخدمين. يمكنك استخدام الروبوتات في Discord لأتمتة المهام والمهام المتكررة التي كانت ستستغرق الكثير من الوقت والجهد.
في هذه المقالة ، ستتعلم كيفية إنشاء روبوت في Discord ، وإضافة الروبوت إلى الخادم الخاص بك ، وتوصيل كود Rust الخاص بك إلى الروبوت الخاص بك.
جدول المحتويات:
لمتابعة هذا المقال ، تحتاج على الأقل إلى مستوى معين من الإلمام بـ Discord. يجب أن يكون لديك أيضًا حساب Discord وخادم Discord تملكه وبعض الخبرة في البرمجة مع Rust.
قد يكون إعداد الروبوت في Discord أمرًا صعبًا بعض الشيء ، خاصة إذا كانت هذه هي المرة الأولى التي تقوم فيها بذلك. في هذا القسم ، سأوجهك خلال إعداد الروبوت لخادمك.
تطبيق Discord هو خدمة توفر واجهة بين مستخدمي Discord وكودك. الواجهة التي يوفرها التطبيق تسمى bot. يتلقى الروبوت رسائل من المستخدمين ويرسل ردًا.
لإنشاء تطبيق Discord ، قم أولاً بتسجيل الدخول إلى حساب Discord الخاص بك في متصفحك. بعد ذلك ، افتح بوابة مطور Discord في متصفحك وانقر على الزر المسمى "تطبيق جديد" في أعلى يمين الصفحة:
أدخل اسمًا للتطبيق الخاص بك:
انقر فوق الزر المسمى "إنشاء" لإنشاء التطبيق. إذا اكتمل الإجراء بنجاح ، فسيتم استقبالك بلوحة تحكم تبدو كالتالي:
في هذا القسم ، ستقوم بإنشاء الروبوت لتطبيق 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:
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:
In the URL Generator menu under “SCOPES,” tick the “bot” option:
Scroll farther down the page to “BOT PERMISSIONS” and tick the “Administrator” option to give the bot admin privileges:
Scroll to the bottom of the page and copy the generated URL on the bottom, then open the generated URL in your browser:
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:
When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.
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.
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:
Click “Copy” to copy the token:
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 التي تمنح المطورين امتيازات عالية في الخادم. في هذا القسم ، سأوجهك خلال تمكين وضع المطور على نظامك حتى تتمكن من نسخ معرف الخادم الخاص بك وتمكين الروبوت الخاص بك من الاستجابة للأوامر.
في الجزء السفلي من النافذة ، انقر فوق رمز الإعدادات بالقرب من اسم المستخدم الخاص بك. في الجزء الأيمن ، حدد "المظهر" ضمن "إعدادات التطبيق".
في قائمة إعدادات المظهر ، انقر على "خيارات متقدمة" لفتح قائمة الإعدادات المتقدمة ، حيث يمكنك بعد ذلك تبديل خيار "وضع المطور". أخيرًا ، انقر بزر الماوس الأيمن فوق اسم الخادم وحدد "نسخ المعرف" لنسخ معرف الخادم.
في الجزء السفلي من النافذة ، انقر فوق رمز الإعدادات بالقرب من اسم المستخدم الخاص بك. في الجزء الأيمن ، حدد "متقدم" ضمن "إعدادات التطبيق" لفتح قائمة الإعدادات المتقدمة ، حيث يمكنك بعد ذلك تبديل خيار "وضع المطور".
ثم ، انقر بزر الماوس الأيمن فوق اسم الخادم وحدد "نسخ المعرف" لنسخ معرف الخادم:
مع استعداد معرف الخادم ، اتبع هذه الخطوات لتمكين الروبوت الخاص بك من الاستجابة لأمر ما. أولاً ، اكتب 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ردًا.
كما هو الحال مع الردود على الرسائل ، يمكنك برمجة الروبوت الخاص بك للرد على أي أوامر مخصصة مع ردود مخصصة باتباع الخطوات التي تناولناها أعلاه.
يمكن أن يؤدي تشغيل مشروعك على نظامك إلى عيوب. قد تتطلب برامج الروبوت الأكثر تعقيدًا موارد كبيرة لتشغيل وخدمة كل مستخدم.
يمنح نشر برنامج الروبوت الخاص بك ميزة عدم استخدام موارد جهاز الكمبيوتر الخاص بك للتشغيل. كما أنه يبقي الروبوت الخاص بك متصلاً بالإنترنت ، حتى لو لم تكن كذلك.
يتيح لك Shuttle نشر الروبوت الخاص بك على خادم Shuttle. لنشر الروبوت الخاص بك ، قم بتشغيل هذا الأمر في دليل المشروع الخاص بك:
cargo shuttle deploy
يمكن أن يكون بناء روبوت محادثة على Discord في Rust مهمة صعبة. ولكن مع المعرفة والأدوات الصحيحة ، يمكن القيام بذلك بسهولة.
من خلال الإرشادات خطوة بخطوة الواردة في هذه المقالة ، يمكن لأي شخص لديه خبرة في البرمجة في Rust وحساب Discord تعلم كيفية إنشاء روبوت دردشة Discord الخاص به. إذا كنت تبحث عن بعض روبوتات Discord المراد إنشاؤها ، فإليك بعض الأفكار:
لمزيد من القراءة عن روبوتات Rust Discord ، تحقق من بعض أمثلة برامج Serenity Discord أو وثائق Serenity .
المصدر: https://blog.logrocket.com
#rust #discord #chatbot
1677129494
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:
Để 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.
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.
Ứ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:
Nhập tên cho ứng dụng của bạn:
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:
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:
Trong phần “Build-A-Bot”, nhấp vào nút “Add Bot” để tạo bot:
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:
Đ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”:
Trong menu Trình tạo URL bên dưới “PHẠM VI”, đánh dấu vào tùy chọn “bot”:
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:
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:
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:
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.
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.
Mã 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”:
Nhấp vào “Sao chép” để sao chép mã thông báo:
Để 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.
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.
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.
Ở 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ủ.
Ở 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ủ:
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.
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
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 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
1677125250
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:
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 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.
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:
Enter a name for your application:
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:
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:
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:
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:
In the URL Generator menu under “SCOPES,” tick the “bot” option:
Scroll farther down the page to “BOT PERMISSIONS” and tick the “Administrator” option to give the bot admin privileges:
Scroll to the bottom of the page and copy the generated URL on the bottom, then open the generated URL in your browser:
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:
When you’re done with these steps, open your server’s member list. You should see your bot listed as a member.
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.
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:
Click “Copy” to copy the token:
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.
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.
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.
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.
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:
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.
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
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:
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
1676589720
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 discordBOT_API
– base url for the bot API, more info here on setting up the bot and APIAlso add the following redirect URIs to your app on discord BASE_URL/
and BASE_URL/dashboard/home
.
If self hosting is not your thing you can start using the dashboard right away on the official site by visiting https://rallybot.app
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
Add BASE_URL/
and BASE_URL/dashboard/home
to your discord app’s redirect URIs
Fill in the config.js
file
Setting | Description |
---|---|
home | Base URL of the dashboard site |
clientId | discord client ID |
botApi | Base URL for the discord bot API |
githubHome | repo homepage |
config.js
exampleexport default {
home: "http://localhost:8080/",
clientId: "786246670530773023",
botApi: "http://localhost:8000",
githubHome: "https://github.com/Ju99ernaut/rally-discordbot-dashboard",
//...
}
You will have to set it up in src/pages/FeatureRequest.vue
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",
},
});
//...
},
Author: FAKEFREESEXS
Source code: https://github.com/FAKEFREESEXS/dark?ref=vuejsexamples.com
License: MIT license
1676425260
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:
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.
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.
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.
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.
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:
Moreover, we’ll take you through the following steps:
Now, as mentioned above, before we show you how to build a Discord bot, let’s take a look at a demonstration.
So, this is our example Discord server, which we created for the sake of this tutorial:
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.
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).
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
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:
Then, select the “Create From Scratch” option:
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).
By focusing on the “exampleDonation” contract, go to PolygonScan and copy this smart contract’s address:
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”:
Next, paste your “ngrok“ address in the “Webhook URL” entry field and add “/webhook” at the end:
As far as the tag goes, you can go with “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:
Then, you want to select the “Native Transactions” option (donations are made in MATIC):
Furthermore, make sure to turn on “Event Emittance”:
Next, return to PolygonScan to copy the smart contract’s ABI:
By pasting the copied ABI in the designated area, you’ll get to select the event of this smart contract:
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:
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.
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:
Next, return to VSC, create a new file (“.env”), and paste your Web3 key next to “APIKEY”:
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”:
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.
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:
Next, name your application, check the box, and hit the “Create” button:
You can also add an icon to your application:
Then, you want to select the “Bot” option, click on the “Add Bot” button, and confirm with a click on “Yes, do it!”:
Moving forward, you want to expand “OAuth2” and click on the “URL Generator” option:
Next, as indicated in the image above, check the “bot” scope. Then, scroll down and check 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:
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:
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:
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:
Moving on, go to your “.env” file, create the “PASS” variable, and paste in the above-copied token:
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):
Return to the “.env” file and create a new variable that will store the above-copied ID:
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:
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:
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