- 到Discord Developers創建機器人(參考文章:Discord.py 機器人從0到1超詳細教學)
- 安裝Python相關檔案
因為我個人有使用import requests
所以我會在額外輸入python -m pip install requests來安裝
- 建立檔案(編寫環境可使用 Notepad++ 或 Visual Studio Code )
建立一個副檔名為.py的文字檔案
#導入Discord.pyimport discord#client是我們與Discord連結的橋樑intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents)#調用event函式庫@client.event#當機器人完成啟動時async def on_ready():print('目前登入身份:',client.user)#discord.Status.<狀態>,可以是online(上線),offline(下線),idle(閒置),dnd(請勿打擾),invisible(隱身)dc_status = discord.Status.online#type可以是playing(遊玩中)、streaming(直撥中)、listening(聆聽中)、watching(觀看中)dc_activity = discord.Activity(type=discord.ActivityType.playing,name="待機中")await client.change_presence(status=dc_status , activity=dc_activity)@client.event#當有訊息時async def on_message(message):#排除自己的訊息,避免陷入無限循環if message.author == client.user:returnclient.run('你的機器人TOKEN') #TOKEN在剛剛Discord Developer那邊「BOT」頁面裡面
- 語法介紹(參考來源:API Reference)
def on_message(message): 當使用者發送訊息時觸發,message變數會存取使用者輸入的內容,功能通常都會寫在這個函數之中。if message.content == "": 判斷訊息是否完全符合條件
if message.content.startswith(""): 判斷訊息開頭是否符合條件
await message.channel.send() 在訊息發送的該頻道傳送指定訊息
await message.reply() 在訊息發送的該頻道以回覆形式傳送指定訊息
await message.author.send() 向傳送訊息的使用者發送私訊
Discord Models.Member屬性介紹
message.author.id 訊息發送者的使用者ID
message.author.name 訊息發送者的使用者名稱
message.author.nick 訊息發送者的使用者在該伺服器使用的暱稱
以上皆是屬於條件判定使用,若要顯示的話須加上f"{}"。範例:f"{message.author.nick}"
若要@訊息發送者須加上f"<@{}>"。範例:f"<@{message.author.id}>"
讓機器人傳送貼圖
傳送圖片
傳送圖片網址便可以將圖片傳至訊息欄;例如說先把圖片上傳至Imgur再複製圖片網址。
但外部連結有時候會失效(只有顯示網址但無法顯示圖片),再加上嵌入式訊息尚無支援Imgur網站,所以筆者方法如下:
嵌入式訊息embed功能介紹(參考來源:Day13 - 嵌入式訊息embed與 bot 的指令表(額外))
程式碼參考:變數 = discord.Embed()變數.set_image()await message.channel.send(embed=變數)




沒有留言:
張貼留言