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

时间:2018-03-06 13:25:23

标签: python python-3.x discord discord.py

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

代码:

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 个答案:

答案 0 :(得分:0)

我们会保存我们发送的邮件,然后使用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)