---
# System prepended metadata

title: Discord Bot講義-4
tags: [Discord Bot講義]

---

# Discord Bot講義-4

**注意!這個篇是Replit的版本，如果使用Thonny IDE點選[這裡](https://hackmd.io/@AndrewCho365/rJo8Vq08C)**

## 學習內容
1. 架設Discord Bot
2. Discord Bot 訊息偵測、斜線指令

## 架設Discord Bot
### 機器人設置
首先到[Discord 開發網站](https://discord.com/developers/applications)點下右上角的**New Application**
![https://ithelp.ithome.com.tw/upload/images/20230927/20161576ODdmvASILS.jpg](https://ithelp.ithome.com.tw/upload/images/20230927/20161576ODdmvASILS.jpg)
輸入你想要的機器人名稱(名稱不要包含**Discord**)，記得勾選同意條款後再按下創建
![https://ithelp.ithome.com.tw/upload/images/20230929/20161576GK4Mjc5onK.jpg](https://ithelp.ithome.com.tw/upload/images/20230929/20161576GK4Mjc5onK.jpg)
點選左邊的bot，到底下將Privileged Gateway Intents 的三個選項打開
然後按下紫色的Reset Token按鈕並複製Token（Token很重要不能告訴別人，也不行上傳到GitHub，會被官方掃描到並重置Token，可以找個自己的地方記錄下來）
![https://ithelp.ithome.com.tw/upload/images/20230927/20161576e1q1IKTJkl.jpg](https://ithelp.ithome.com.tw/upload/images/20230927/20161576e1q1IKTJkl.jpg)
接著找到OAuth2的URL Generator
上下兩區選項分別勾選bot和Administrator，最後複製底下的網址到瀏覽器貼上
![https://ithelp.ithome.com.tw/upload/images/20230927/20161576Y9dyXrgLLf.jpg](https://ithelp.ithome.com.tw/upload/images/20230927/20161576Y9dyXrgLLf.jpg)
進到貼上的網址，選好想要的伺服器後點選繼續並授權將機器人加入伺服器
![https://ithelp.ithome.com.tw/upload/images/20230927/20161576ECHSOPqdhF.png](https://ithelp.ithome.com.tw/upload/images/20230927/20161576ECHSOPqdhF.png)
接著進入伺服器檢查機器人是否成功進入
![https://ithelp.ithome.com.tw/upload/images/20230927/20161576Sgsvi4whlk.png](https://ithelp.ithome.com.tw/upload/images/20230927/20161576Sgsvi4whlk.png)
下一步就是要讓機器人上線了！
### 前置作業
如果不想後面麻含的設定可以按下右邊綠色的按鈕直接用我的[模板](https://replit.com/@andrewcho365/Discord-Bot?v=1#README.md)製作
※如果使用我的模板，基本程式碼編寫和環境安裝可以跳過，但還是要設定Secrets儲存token
![https://ithelp.ithome.com.tw/upload/images/20240328/20161576XOHfdUmkrr.png](https://ithelp.ithome.com.tw/upload/images/20240328/20161576XOHfdUmkrr.png)
### 建立檔案

1.到[Replit](https://replit.com/)註冊並登入帳號
2.點下左上角的Create Repl，選擇**Python**並在**Title**輸入自訂名稱，最後按下藍色的**Create Repl**按鈕
![https://ithelp.ithome.com.tw/upload/images/20230926/201615762r1flF7AwB.jpg](https://ithelp.ithome.com.tw/upload/images/20230926/201615762r1flF7AwB.jpg)
![https://ithelp.ithome.com.tw/upload/images/20230926/20161576AXvE7pvBEI.jpg](https://ithelp.ithome.com.tw/upload/images/20230926/20161576AXvE7pvBEI.jpg)

### 基本程式碼編寫
在**main.py**輸入以下程式碼⬇️

```py=
import discord #導入discord
import os

bot = discord.Bot(intents = discord.Intents.all()) 
#定義物件 intents是前面勾選的三個勾勾

@bot.event
async def on_ready():
    print(f"「{bot.user}」已登入")

bot.run(os.environ['bot_token']) #運行機器人
```
然後按下第一次執行
### 使用Secrets儲存token
因為擁有token的人就可以操控機器人
而Repl.it的程式碼是網路上所有人都能查看的
所以需要使用**Secrets**把token藏起來
來到左下角點選**Secrets**
按下**New Secret**
創建一個名為**bot_token**的**Key**
**Value**為前面複製的token
![image](https://hackmd.io/_uploads/r1chu_9_0.png)


### 環境安裝（此部分順序很重要）
接下來到左下角點選**Dependencies**
![image](https://hackmd.io/_uploads/S16t8O9_R.png)

點選**Add new package**

![image](https://hackmd.io/_uploads/HkCcLu5_0.png)


在右邊的搜尋欄打入**py-cord**並按下Install
![image](https://hackmd.io/_uploads/r177L_quA.png)

在右邊的搜尋欄打入**discord2**並按下Install（**discord2**一定要最後安裝）
![image](https://hackmd.io/_uploads/HJRgIu9OC.png)
按下第二次執行後你就可以看到機器人已經上線了
如果產生錯誤只需將**discord2**刪除後再重新安裝即可
![image](https://ithelp.ithome.com.tw/upload/images/20230928/2016157657vkhpLsfr.png)


## Discord Bot 訊息偵測、斜線指令
### 訊息偵測
|             |   輸入  |           輸出         |
|   :-----:   | :----:  |         :----:        |
|    Python   |  input  |         print()       |
| Discord Bot | message | await.XXX.send("XXX") |

### 偵測特定訊息並回復
```py=
@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    if message.content == "hi": #如果有訊息為"hi"
        await message.channel.send("hello!") #在此頻道發送"hello!"
```
### 偵測訊息開頭並回復
```py=
@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    if message.content.startswith("你好"): #當開頭為"你好"
        await message.channel.send("你好啊!") #在此頻道發送"你好啊!"
```
### 發送歡迎使用者加入訊息
```py=
@bot.event
async def on_member_join(member): #定義為使用者加入 調用member
    wel_channel_id = 1234567891234567890 #發送頻道ID
    wel_channel = bot.get_channel(wel_channel_id) #取得頻道
    await wel_channel.send(f"歡迎 {member.mention} 加入!") #在該頻道發送訊息 mention能@到該使用者
```
#### 獲取頻道ID
點擊左下角的設定
![https://ithelp.ithome.com.tw/upload/images/20230929/20161576kHRKgUTRNm.jpg](https://ithelp.ithome.com.tw/upload/images/20230929/20161576kHRKgUTRNm.jpg)
在左邊找到進階，把開發者模式打開
![https://ithelp.ithome.com.tw/upload/images/20230929/20161576GTktg3Kwk4.jpg](https://ithelp.ithome.com.tw/upload/images/20230929/20161576GTktg3Kwk4.jpg)
對頻道右鍵，點擊複製頻道ID
![https://ithelp.ithome.com.tw/upload/images/20230929/201615767U4Jq4Yikl.jpg](https://ithelp.ithome.com.tw/upload/images/20230929/201615767U4Jq4Yikl.jpg)
### 斜線指令
```py=
@bot.command(description="回復world") #description為備註(也可不放)
async def hello(ctx): #指令名稱為"hello" 並調用ctx
    await ctx.respond("world") #回復"world"
```
如果有文字或數值需要使用者輸入
可以在ctx的後方加入輸入框設定
```py=
@bot.command(description="傳送訊息給伺服器")
async def text(ctx, message:str, 頻道id=None,pin=int):
    if pin = 123456:
        if 頻道id is not None:
            channel = bot.get_channel(int(頻道id))
            await channel.send(message)
        else:
            await ctx.send(message)
    else:
        await ctx.respond("驗證錯誤")
```
有時候指令被執行後會需要大量運算或是時間延遲的，
可以在加入```await ctx.defer```傳送機器人受到指令的訊息
```py=
@bot.command(description="回復world")
async def hello(ctx):
	await ctx.defer
    await ctx.respond("world") 
```
![image](https://hackmd.io/_uploads/rJTcBahyJe.png)

不過執行上方程式碼應該是看不到的效果的
因為電腦處理這條指令不需要很多時間
在後面的教學就會派上用場了