在discord.py@tasks.loop()中发送消息

2024-04-19 18:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

目标:

我只是尝试从@tasks.loop()向discord通道发送消息,而不需要来自@client.event async def on_message的discord消息变量。discord bot使用正常运行时间机器人在repl.it中保持运行

方法/背景:

一个简单的while True循环将不适用于我将应用此原则的更大项目,如Karen's answer here所述。我现在使用的@tasks.loop()洛夫什在这里很快详细介绍了:(see Lovesh's work)

问题:

使用most common method to send a message in discord using discord.py时仍然会出现错误。这个错误与await channel.send( )方法有关。这两条消息都不会不一致地发送Here is the error message

代码:

from discord.ext import tasks, commands
import os
from keep_alive import keep_alive
import time

token = os.environ['goofyToken']




# Set Up Discord Client & Ready Function
client = discord.Client()
channel = client.get_channel(CHANNEL-ID)


@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))



@tasks.loop(count=1)
async def myloop(word):
  
  await channel.send(word)




@client.event
async def on_message(message):
  msg = message.content
  
  if msg.startswith('!'):

    message_to_send = 'Hello World!'
    await channel.send(message_to_send)
  

    myloop.start(message_to_send)
    


keep_alive()
client.run(token)

尝试的解决方案:

可以使用语法await message.channel.send('Hello World!)on_message事件发送消息。然而,我就是不能用这个。代码由uptimerobot在线运行,这是一个免费网站,在repl.it上ping存储库。当robot ping存储库时,消息变量丢失,因此循环将停止扫描我正在处理的更大项目中的数据,该项目将导致此问题


Tags: toimportclientloopeventsend消息message
1条回答
网友
1楼 · 发布于 2024-04-19 18:21:32

当使用任何client.get_*方法时,bot将尝试从缓存中获取对象,在bot实际运行之前定义channel全局变量(因此缓存为空)。您应该在循环函数内获得通道

@tasks.loop(count=1)
async def myloop(word):
    channel = client.get_channel(CHANNEL_ID)
    await channel.send(word)

相关问题 更多 >