xia的小窩

一起來coding和碼字吧

0%

python-Discord-bot,從0開始到做出一個機器人系列-12

行前作業

註冊帳號
需要有自己的伺服器或是相應的權限

開始後續作業

搜尋discord developer portal

點擊New Application

輸入名字,點擊create

點擊Bot(Add Bot)

勾選Administrator

點擊OAuth2,點選Bot,下方將出現一個網址,那是邀請碼,按下Copy後,複製到網址列

最後授權即可

取得token

回到剛才的Bot畫面

裡面有一個token,copy點下去

開始撰寫

建立資料夾,並將資料夾拖曳進vscode,在裡面建立一個bot的python檔案,以及items的json檔案

先點擊json檔,並輸入

1
2
3
{
"token":"Your token"
}

接著,使用在下方的終端機,輸入……以使用discord延伸模組

1
pip install discord.py

點開bot檔案,並輸入

1
2
3
# 引用包
from discord.ext import commands
import discord

添加前綴字符

1
bot = commands.Bot(command_prefix="!")

添加事件

1
2
3
@bot.event
async def on_ready():
print("Bot in ready")

這樣就可以給他跑了嗎??還沒喔,因為我們剛剛把token寫入了json檔,所以我們需要把它拿出來~~

1
2
3
4
import json

with open('items.json', "r", encoding = "utf8") as file:
data = json.load(file)

最後添加上keyword

1
bot.run(data['token']) 

確認機器人是否能啟動

在終端機輸入

1
python bot.py

確認是否能啟動

本次的程式碼如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from discord.ext import commands 
import discord
import json

bot = commands.Bot(command_prefix="!")

with open('items.json', "r", encoding = "utf8") as file:
data = json.load(file)


@bot.event
async def on_ready():
print("Bot in ready")

bot.run(data['token'])

2.0部分更改

自從discord.py 2.0 發布後,這些文章有些地方不能用,更改後的程式碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from discord.ext import commands 
import discord
import json
import asyncio

bot = commands.Bot(command_prefix="!")

with open('items.json', "r", encoding = "utf8") as file:
data = json.load(file)

token = data["token"] # python3.12強制更動為雙引

@bot.event
async def on_ready():
print("Bot in ready")

# bot 開機開啟.py檔案
async def load_extensions():
# 先建立cogs資料夾
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}")
# 先建立cmds資料夾
for filename in os.listdir("./cmds"):
if filename.endswith(".py"):
await bot.load_extension(f"cmds.{filename[:-3]}")


async def main():
async with bot:
await load_extensions()
await bot.start(token)

if __name__ == "__main__":
asyncio.run(main())