如何解决制作一个在指定聊天中每 10 秒发送一条消息的齿轮 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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。