今天來介紹一些常用的訊息屬性設定。
進度

前幾天介紹了兩大類的訊息,包含:文字訊息與包含可以互動的圖形化元件的訊息。接下來,來繼續認識,除了內容與樣式,訊息本身還有什麼可以設定的。
在開始之前,根據函數的參數型別,要分成兩大類來討論:
- 訊息類
Message
:通常是 Client
的寫法會用到
Context
:通常是 Bot
的寫法會用到
- 互動類
先從訊息類開始介紹~
訊息類
之前都是簡單這樣寫:
1 2 3 4
| @client.event async def on_message(message: discord.Message): if message.content == "ping": await message.channel.send("Pong!")
|
或是
1 2 3
| @bot.command() async def ping(ctx: commands.Context): await ctx.send('Pong!')
|
但其實還有一些變化,例如可以用 reply
,就變成回復訊息的格式。
1 2 3
| @bot.command() async def ping(ctx: commands.Context): await ctx.reply('Pong!')
|

如果不想要那麼突兀,也可以把提示用的黃色背景去掉,只要再加上 mention_author=False
就可以了。
1 2 3
| @bot.command() async def ping(ctx: commands.Context): await ctx.reply('Pong!', mention_author=False)
|

互動類
之前都是簡單這樣寫:
1 2 3
| @bot.tree.command() async def ping(interaction: discord.Interaction): await interaction.response.send_message(f'Pong!')
|

可以設定 ephemeral=True
,讓這則 Discord BOT 傳送的
訊息只有你自己才看得到。
如果是「檢舉成功」這類的訊息就很需要這個設定 XD
1 2 3
| @bot.tree.command() async def ping(interaction: discord.Interaction): await interaction.response.send_message(f'Pong!', ephemeral=True)
|

由於這牽涉到「是誰可以看到」,所以如果只是單純地在頻道傳送訊息 (e.g. ctx.send('Pong!')
),並沒有這類的功能。
共通的屬性
有些屬性不論哪類都有,例如:
delete_after
:幾秒後自動刪除 (有點難 Demo,就不放圖了)
silent
:是否要靜音 (不發送通知)
那文字訊息以外的呢?
當然也有上述這些設定,這邊來看一下同時傳送文字、嵌入式訊息 (Embed) 和按鈕的範例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| async def on_click(interaction: discord.Interaction): await interaction.response.send_message("QQ", ephemeral=True)
@bot.tree.command() async def ping(interaction: discord.Interaction): view = discord.ui.View() btn = discord.ui.Button(label="可惜了") btn.callback = on_click view.add_item(btn)
embed = discord.Embed(title="我家的貓", description="不會後空翻") cat = discord.File("cat.jpg", filename="cat.jpg") embed.set_image(url="attachment://cat.jpg")
await interaction.response.send_message( f"Pong!", ephemeral=True, view=view, file=cat, embed=embed )
|
效果如下:

可以看到還是可以設定為只有自己看得到~
正在輸入…
最後介紹一個與這篇主題有點相關,但又沒那麼相關的設定:正在輸入。
在使用 Discord 跟別人聊天時,不知道大家有沒有注意過,輸入框下方有時候會出現「OOO 正在輸入…」的提示。大概長這樣:

在 Discord 手機版則是出現在輸入框上方

而這個「正在輸入…」的提示,Discord BOT 是可以設定的。通常會用於那些需要較長時間處理的任務,確保讓其他人知道 Discord BOT 還活著,而不是毫無反應。
先看一下簡單的範例:
1 2 3 4 5
| @bot.command() async def ping(ctx: commands.Context): await ctx.typing() await asyncio.sleep(5) await ctx.send('pong')
|
1 2 3 4 5
| @bot.command() async def ping(ctx: commands.Context): async with ctx.typing(): await asyncio.sleep(5) await ctx.send('pong', ephemeral=True)
|
這兩種寫法效果一樣
執行效果就會跟上面的範例相同,就不重複貼了XD
這邊用 asyncio.sleep
來表示需要較長時間處理的功能,實際使用時把它替換掉就好了。
小結
今天介紹的內容不多,但比較雜,包含了:
mention_author
:黃底的提示
ephemeral
:只有自己看的到
delete_after
:數秒後自動刪除
silent
:靜音
typing()
:正在輸入
以上這些都是我覺得在訊息的設定中,比較常會用到的。