簡體   English   中英

(Discord.py)如何讓機器人在一段時間后刪除自己的消息?

[英](Discord.py) How to make bot delete his own message after some time?

我在 Python 中有這個代碼:

import discord
client = commands.Bot(command_prefix='!')

@client.event
async def on_voice_state_update(member):
    channel = client.get_channel(channels_id_where_i_want_to_send_message))
    response = f'Hello {member}!'
    await channel.send(response)

client.run('bots_token')

我希望機器人刪除自己的消息。 例如,一分鍾后,我該怎么做?

有比Dean AmbrosDom建議的更好的方法,您可以簡單地在.send中添加 kwarg delete_after

await ctx.send('whatever', delete_after=60.0)

參考

在我們做任何事情之前,我們要導入 asyncio。 這可以讓我們在代碼中等待設定的時間。

import asyncio

首先定義您發送的消息。 這樣我們可以稍后再回來。

msg = await channel.send(response)

然后,我們可以使用 asyncio 等待一段時間。 括號中的時間以秒為單位,因此一分鍾為 60,兩分鍾為 120,依此類推。

await asyncio.sleep(60)

接下來,我們實際上刪除了我們最初發送的消息。

await msg.delete()

所以,你的代碼最終看起來像這樣:

import discord
import asyncio

client = commands.Bot(command_prefix='!')

@client.event
async def on_voice_state_update(member, before, after):
    channel = client.get_channel(123...))
    response = f'Hello {member}!'
    msg = await channel.send(response) # defining msg
    await asyncio.sleep(60) # waiting 60 seconds
    await msg.delete() # Deleting msg

您還可以在此處閱讀更多內容。 希望這有幫助!

這不應該太復雜。 希望它有所幫助。

import discord
from discord.ext import commands
import time
import asyncio
client = commands.Bot(command_prefix='!')

@commands.command(name="test")
async def test(ctx):
    message = 'Hi'
    msg = await ctx.send(message)
    await ctx.message.delete() # Deletes the users message
    await asyncio.sleep(5) # you want it to wait.
    await msg.delete() # Deletes the message the bot sends.
 
client.add_command(test)
client.run(' bot_token')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM