[英]Make a cog that sends a message every 10 seconds in a specified chat discord.py
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'
我究竟做错了什么?
self
总是作为第一个参数,而不是第二个async def sendmessage(self, ctx):
您需要在启动任务时传递ctx
参数(或者根本不传递它,没有必要)
没有self.get_channel
这样的东西(请记住,您不是从discord.Client
或commands.Bot
继承的),它是self.client.get_channel
channel = self.client.get_channel(...)
@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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.