机器人在while循环中发送消息

时间:2021-01-18 15:46:23

标签: discord.py

这是简化的代码。

import time
import discord
x=0
while True:
   x=x+1
   time.sleep(100)
   #here I want to send 'x' to my discord channel 

假设我的机器人已经配置和连接,我只需要一个可以无条件发送消息的函数。

1 个答案:

答案 0 :(得分:1)

为了做到这一点,您必须等到机器人准备就绪。所以你可以在 on_ready 事件中创建这个 while 循环。然后,您必须获取将发送消息的 discord.Channel 对象。

x = 0
@client.event
async def on_ready():
    channel = client.get_channel(<channel id>)
    while True:
        x+=1
        time.sleep(100)
        await channel.send(x)

但我不建议使用 while 循环来执行此操作。您可以改用 discord.ext.tasks

from discord.ext import tasks
import discord

x = 0
@tasks.loop(seconds=100.0)
async def example():
    channel = client.get_channel(<channel id>)
    x+=1
    await channel.send(x)

@client.event
async def on_ready():
    example.start() # This will start the loop when bot is ready.

有关 discord.ext.tasks 的更多信息,您可以访问 Tasks API References