繁体   English   中英

制作一个在指定聊天中每 10 秒发送一条消息的 cog discord.py

[英]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'

我究竟做错了什么?

  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. 您需要在 function 或命令中启动任务
@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM