# Discord Bot ## 建置 - Review:replit帳號 {%youtube n1kJI_wuq2g %}<br/> - 機器人架設,[先前往discord developers](https://discord.com/developers/applications) {%youtube UugDhrtwrQc %}<br/> - 在shell內打入`pip install py-cord`然後按enter鍵  附註—shell可能會有報錯: 1. 若他說: `AttributeError: module 'discord' has no attribute 'Bot'` 那問題很可能是沒載到py-cord, 因此要再輸一次`pip install py-cord` [參考來源](https://stackoverflow.com/questions/69719970/how-to-fix-error-module-discord-has-no-attribute-bot) 2. 而報錯若是: `ModuleNotFoundError: No module named 'discord'` 那代表模組之間有衝突,輸入`pip uninstall discord.py` [參考來源](https://stackoverflow.com/questions/49886183/modulenotfounderror-no-module-named-discord) ## 基礎功能 ### 開頭 1. import ```python= import discord ``` 翻譯: </br> >就像桌遊有擴充一樣,python 的 import 就是拿來擴充用的 > 現在要擴充 discord 方面的功能 <b></b> --- 2. 一些設定 ```python= intents = discord.Intents.all() bot = discord.Bot(intents=intents) ``` 如果爛掉就用J個,但不能用斜線指令 ```python= intents = discord.Intents.all() bot = discord.Client(intents = intents) ``` 翻譯: </br> > 要求所有「意圖」,讓機器人可以收訊息 > 並定義 bot 變數 為 你的機器人 ### 結尾 ```python= bot.run(token) ``` 翻譯: </br> > 執行機器人,其中 token 為你的機器人的密鑰 ### 對話 1. 偵測發言 ```python= @bot.event async def on_message(message): if message.author == bot.user: return if message.content == '嗨': await message.channel.send('你好呀') ``` 翻譯: </br> > 第一行:說明現在是一個discord的事件,而非自己定義函式 > 第二行:現在的事件是,當有人發送訊息,就會觸發 > 第三四行:不偵測機器人自己講話(避免無限循環) > `(直翻:訊息的作者 為 這隻機器人 時,結束函式執行)`</br> > 第五六行:當訊息為"嗨",就會回"你好啊" > `(直翻:訊息的內容 為 "嗨" 時,在 接收到訊息的頻道傳送"你好啊")` :star: 應用:敷衍機器人 ```python= @bot.event async def on_message(message): if message.author == bot.user: return await message.channel.send('確實') ``` 翻譯: > 因為不像上面有 if 偵測哪些訊息才會回嘴 > 所以不論收到甚麼訊息都會回嘴「確實」 <b></b> --- 2. 斜線指令 ```python= @bot.slash_command(name = "hello", description = "打招呼") async def hello(ctx): await ctx.respond("hihi") ``` 翻譯: </br> > 第一行:創造一個斜線指令,其中 > - `name` 為指令名稱 > - `description` 為選到指令時可檢視的簡單敘述</br> > 第二行:定義一個觸發指令時會執行的程式區塊 > 第三行:對你發出的指令回復"hihi" ### 上線時提示 ```python= @bot.event async def on_ready(): print(f'目前登入身份:{bot.user}') ``` 翻譯: </br> > 第一行:說明現在是一個discord的事件,而非自己定義函式 > 第二行:現在的事件是,當機器人上線,就會觸發 ### 完整程式碼 ```python= import discord intents = discord.Intents.all() bot = discord.Bot(intents=intents) @bot.event async def on_ready(): print(f"{bot.user} is ready and online!") @bot.event async def on_message(message): if message.author == bot.user: return if message.content == '嗨': await message.channel.send('你好呀') @bot.slash_command(name = "hello", description = "打招呼") async def hello(ctx): await ctx.respond("HiHi") # 這邊要記得改成自己的 token bot.run("MTAzzM0NjQz4fMD0OTUyY0saNw.GDNp.tSWHsITj4wYQi51RDxCWeOQBjcR0u1") ``` <b></b> --- ###### ---作者<<font color="#ffc500">海星</font>> ###### tags: `Python` `DiscordBot`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up