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

Sending messages in discord.py @tasks.loop()

目标:

我只是想从 @tasks.loop() 向不和谐频道发送消息,而不需要来自 @client.event async def on_message 的不和谐消息变量。使用 uptime robot 将 discord bot 运行 保存在 repl.it 中。

方法/背景:

一个简单的 while True 循环不适用于我将应用此原则的较大项目,详见 . I am now using @tasks.loop() which Lovesh has quickly detailed here:

问题:

我仍然收到使用 most common method to send a message in discord using discord.py. The error has to have something to do with the await channel.send( ) method. Neither of the messages get sent in discord. 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 保持在线 运行,这是一个免费网站,可以 ping repl.it 上的存储库。当机器人 ping 存储库时,消息变量丢失,因此循环将停止扫描我正在处理的较大项目中的数据,这给了我这个问题。

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

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