函數內容

取得歷史訊息可以使用channel.history(),其中channel的來源不限
如何取得channel請參考頻道物件

channel.history()這個函數會返回頻道的所有歷史訊息,可以有以下參數

  • limit=100: 最大數量,填入None則會返回所有
  • before=None/after=None: 限定時間範圍,需要是datetime.datetime類別的物件
  • around=None: 返回這個日期左右的訊息,需要是datetime.datetime類別的物件
  • oldest_first=None: 是否從最舊的開始抓,如果有指定after的話就會自動設為True

這個函數返回的結果是一個可以被迭代的物件
可以想像成特殊的陣列,用for迴圈來取用

範例

範例,印出50則訊息的內容

1
2
3
#用async for迴圈來取得內容,取出來的會是一個訊息物件
async for msg in channel.history(limit=50):
print(msg.content)

結合機器人即可印出該頻道的內容

1
2
3
4
5
6
@bot.tree.command()
async def chat(interaction:discord.Interaction):
async for msg in interaction.channel.history(limit=100): #用async for迴圈來取得內容,取出來的會是一個訊息物件
print(msg.content)

await interaction.response.send_message('完成')
聊天室 終端機
聊天室 終端機

練習

印出使用者

請依照範例方式,但改印出訊息使用者的名字

1
2
3
4
5
6
@bot.tree.command()
async def chat(interaction:discord.Interaction):
async for msg in interaction.channel.history(limit=100):
print(msg.author.display_name)

await interaction.response.send_message('完成')

訊息計數

請試著讓使用者指定一個人,並統計他說了多少次話
如果忘記如何讓指令接收一個使用者,可以參考使用者物件

1
2
3
4
5
6
7
8
9
@bot.tree.command()
async def count(interaction:discord.Interaction, user:discord.User):
await interaction.response.defer()
count = 0
async for msg in interaction.channel.history():
if msg.author == user:
count += 1

await interaction.followup.send(f"{user.display_name}一共有{count}則訊息")