创建一个cog,在指定的chat discord.py中每10秒发送一条消息


from discord.ext import commands, tasks

class sendmessage10seconds(commands.Cog):
def __init__(self, client):
self.client = client
print("Cog is running")

@tasks.loop(seconds=10)
async def sendmessage(ctx, self):
channel = self.get_channel(802273252973477960)
await channel.send("Hi")
sendmessage.start()
def setup(client):
client.add_cog(sendmessage10seconds(client))

这是我到目前为止的代码。当我运行它时,我得到这个错误:

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
TypeError: sendmessage() missing 2 required positional arguments: 'ctx' and 'self'

我做错了什么?

  1. self总是作为第一个参数,而不是第二个
async def sendmessage(self, ctx):
  1. 您需要在启动任务时传递ctx参数(或者根本不传递它,没有必要)

  2. 没有self.get_channel这样的东西(记住,你不是继承discord.Clientcommands.Bot),它是self.client.get_channel

channel = self.client.get_channel(...)
  1. 需要在函数或命令中启动任务
@commands.command()
async def start(self, ctx):
self.sendmessage.start() # Pass the `ctx` parameter accordingly

编辑:在__init__方法中启动循环

def __init__(self, client):
self.client = client
self.sendmessages.start()

注意:你应该添加等待,直到机器人准备好加载内部缓存,这样做的一种方法是使用装饰器{task}.before_loop和使用Bot.wait_until_ready

@sendmessage.before_loop
async def before_sendmessage(self):
await self.client.wait_until_ready()

完整的固定代码

from discord.ext import commands, tasks

class sendmessage10seconds(commands.Cog):
def __init__(self, client):
self.client = client
self.sendmessage.start()

@tasks.loop(seconds=10)
async def sendmessage(self): # You can pass the `ctx` parameter if you want, but there's no point in doing that
channel = self.client.get_channel(802273252973477960)
await channel.send("Hi")

@sendmessage.before_loop
async def before_sendmessage(self):
await self.client.wait_until_ready()

def setup(client):
client.add_cog(sendmessage10seconds(client))

最新更新