# Discord Bot#1 ## How to basic --- ## 註冊你的Discord bot https://discord.com/developers/docs/intro ---- 1. 點選Application並登入Discord帳戶 ![](https://i.imgur.com/LSNdqVI.png) ---- 2. 點選 New application ![](https://i.imgur.com/FcMPDfS.png) ---- 3. 輸入應用程式名稱 >note: 這個還不是機器人的名字 ![](https://i.imgur.com/2LF3EtI.png =600x) ---- 4. 點選Bot ![](https://i.imgur.com/gJajatL.png) ---- 5. 點選Add Bot ![](https://i.imgur.com/2vVogIe.png) ---- 6. 野生的Bot出現了! >note: 這裡的USERNAME就是機器人在伺服器的名字 ![](https://i.imgur.com/n75sG2G.png =600x) ---- 7. 滑到下面,啟用三個Intent ![](https://i.imgur.com/yn1Bpnd.png) --- # Start coding! ## 打開vscode並新增一個.py檔案 ---- - 在檔案前面新增這兩行,告訴python你會使用這些套件 ```python= import discord from discord.ext import commands ``` ---- - 新增一個bot物件 ```python= bot = commands.Bot(command_prefix = '!' ,intents = discord.Intents.all()) ``` ---- - 讓機器人啟動時在終端輸出文字 ```python= @bot.event async def on_ready(): print('Hello world!') ``` ---- - 執行你的機器人 ```python= bot.run('你的token') ``` ---- - 在剛剛註冊機器人的網頁可以找到你的token ![](https://i.imgur.com/pnLfkXC.png) ---- - 回到vscode,按左上角的三角形執行你的機器人 ![](https://i.imgur.com/QQhd7XZ.png) ---- - 看到終端有輸出hello world就代表你成功了! ![](https://i.imgur.com/ly3EiJ1.png) --- # 基本指令與事件 https://discordpy.readthedocs.io/en/stable/api.html ---- ## 成員加入/退出伺服器事件 - on_member_join(member) - on_member_remove(member) ---- ## Example ```python= @bot.event async def on_member_join(member): channel = bot.get_channel(頻道ID) await channel.send(f'{member} Ya hello') @bot.event async def on_member_remove(member): channel = bot.get_channel(頻道ID) await channel.send(f'{member} Bye bye') ``` ---- ## ctx引數 - 指令中最重要的部分 - 可以讓你的機器人讀取訊息的資訊(伺服器id,訊息的主人) ---- ## Example: ping ```python= @bot.command() async def ping(ctx): await ctx.send(bot.latency) ``` --- # 加入伺服器 ---- - 回到Developer portal,點選OAUTH2 ![](https://i.imgur.com/7fNumr7.png) ---- - 勾選bot ![](https://i.imgur.com/3NhWsp3.png) ---- - 複製最下面的網址,貼到瀏覽器的網址列上 ![](https://i.imgur.com/xNECF9l.png) ---- - 選取你的機器人要加入的伺服器 >note: 要有伺服器權限才可以使用 ![](https://i.imgur.com/vfhWmHm.png =350x)
{"metaMigratedAt":"2023-06-16T15:09:24.464Z","metaMigratedFrom":"YAML","title":"Discord Bot#1","breaks":true,"contributors":"[{\"id\":\"e66eff6e-ecb8-470a-a384-ea2a02e04747\",\"add\":2235,\"del\":82}]"}
    792 views
   owned this note