简体   繁体   English

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

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

I have this code in Python:我在 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')

And I want the bot to delete its own message.我希望机器人删除自己的消息。 For example, after one minute, how do I do it?例如,一分钟后,我该怎么做?

There is a better way than what Dean Ambros and Dom suggested, you can simply add the kwarg delete_after in .send有比Dean AmbrosDom建议的更好的方法,您可以简单地在.send中添加 kwarg delete_after

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

reference 参考

Before we do anything, we want to import asyncio.在我们做任何事情之前,我们要导入 asyncio。 This can let us wait set amounts of time in the code.这可以让我们在代码中等待设定的时间。

import asyncio

Start by defining the message you send.首先定义您发送的消息。 That way we can come back to it for later.这样我们可以稍后再回来。

msg = await channel.send(response)

Then, we can wait a set amount of time using asyncio.然后,我们可以使用 asyncio 等待一段时间。 The time in the parentheses is counted in seconds, so one minute would be 60, two 120, and so on.括号中的时间以秒为单位,因此一分钟为 60,两分钟为 120,依此类推。

await asyncio.sleep(60)

Next, we actually delete the message that we originally sent.接下来,我们实际上删除了我们最初发送的消息。

await msg.delete()

So, altogether your code would end up looking something like this:所以,你的代码最终看起来像这样:

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

You can also read up more in this here .您还可以在此处阅读更多内容。 Hope this helped!希望这有帮助!

This shouldn't be too complicated.这不应该太复杂。 Hope it helped.希望它有所帮助。

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