如何让discord.py机器人在一段时间后删除自己的消息



我在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中添加夸尔格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')

最新更新