如果没有人发布,如何使Discord bot不发送消息

以Python编写的以下Discord bot每6个小时发送一次随机消息 . 如果机器人之后没有人在 Channels 中发布,我怎么能修改代码以便机器人不会再发帖?

Code:

import os
import discord
import asyncio
import random
from messages import messages_list
from copy import deepcopy

key = os.environ['BOT_TOKEN']

client = discord.Client()

async def background_loop():
    await client.wait_until_ready()
    messages = deepcopy(messages_list)
    cleanmessages = deepcopy(messages_list)
    while not client.is_closed:
        channel = client.get_channel("Channel_ID")
        if not messages:
            messages = deepcopy(cleanmessages)
        await client.send_message(channel, messages.pop(random.randrange(0, len(messages))))
        await asyncio.sleep(21600)

client.loop.create_task(background_loop())
client.run(key)

回答(1)

2 years ago

我们将保存我们发送的消息,然后使用client.logs_from查看该消息之后的所有消息 .

async def background_loop():
    await client.wait_until_ready()
    last_message = None
    messages = deepcopy(messages_list)
    cleanmessages = deepcopy(messages_list)
    channel = client.get_channel("Channel_ID")

    while not client.is_closed:
        if not messages:
            messages = deepcopy(cleanmessages)
        if len([x async for x in client.logs_from(channel, limit=2, after=last_message)]) > 1:
            content = messages.pop(random.randrange(0, len(messages)))
            last_message = await client.send_message(channel, content)
        await asyncio.sleep(21600)