Python 使用侦听器事件调用同一cog内的函数,使用discord.py
我正在尝试使用侦听器事件激活cog中的函数,使用Python 使用侦听器事件调用同一cog内的函数,使用discord.py,python,discord.py,Python,Discord.py,我正在尝试使用侦听器事件激活cog中的函数,使用discord.py。同样的代码在主bot.py文件中正常运行(删除self并使用@client.event而不是侦听器),但当在cog中使用时,它告诉我在侦听器事件中使用repeater()函数时,它是一个未定义的变量 导入不一致 从discord.ext导入命令、任务 类中继器(commands.Cog): 定义初始化(自我,客户机): self.client=client @tasks.loop(秒=10) 异步def中继器(自): 通道=s
discord.py
。同样的代码在主bot.py文件中正常运行(删除self
并使用@client.event
而不是侦听器),但当在cog中使用时,它告诉我在侦听器事件中使用repeater()
函数时,它是一个未定义的变量
导入不一致
从discord.ext导入命令、任务
类中继器(commands.Cog):
定义初始化(自我,客户机):
self.client=client
@tasks.loop(秒=10)
异步def中继器(自):
通道=self.client.get_通道(834554679265329172)
等待通道发送('test')
@commands.Cog.listener()
异步def on_就绪(自):
repeater.start()
def设置(客户端):
客户端。添加_cog(中继器(客户端))
编辑:
因此,我在一条注释推荐后更改了与此匹配的代码,控制台抛出此错误
@commands.Cog.listener()
异步def on_就绪(自):
self.repeater()
编辑2:
将代码更改为与此匹配,它将只运行一次循环,但实际上不会循环
@commands.Cog.listener()
异步def on_就绪(自):
等待self.repeater()
中继器
是该类的一个函数。所以你可以用self.repeater调用它。要启动不协调任务,请使用“开始”属性self.repeater.start()
就是答案。在课堂上,你必须使用self.
访问其方法self.repeater
和self.repeater.start()
我在这段代码上测试了它,它对我有效
import discord
from discord.ext import commands, tasks
import os
import datetime
TOKEN = os.getenv('DISCORD_TOKEN')
CHANNEL = 834554679265329172
class Repeater(commands.Cog):
def __init__(self, client):
self.client = client
@tasks.loop(seconds=10)
async def repeater(self):
#channel = self.client.get_channel(CHANNEL)
await self.channel.send(datetime.datetime.now().strftime("It's %H:%M.%S"))
@commands.Cog.listener()
async def on_ready(self):
self.channel = self.client.get_channel(CHANNEL)
print('starting repeater')
self.repeater.start()
def setup(client):
client.add_cog(Repeater(client))
# --- main ---
client = commands.Bot(command_prefix='!')
setup(client)
print('starting bot')
client.run(TOKEN)
self.repeater
?使用self.repeater.start()
时,出现错误“方法'repeater'没有'start'成员”
import discord
from discord.ext import commands, tasks
import os
import datetime
TOKEN = os.getenv('DISCORD_TOKEN')
CHANNEL = 834554679265329172
class Repeater(commands.Cog):
def __init__(self, client):
self.client = client
@tasks.loop(seconds=10)
async def repeater(self):
#channel = self.client.get_channel(CHANNEL)
await self.channel.send(datetime.datetime.now().strftime("It's %H:%M.%S"))
@commands.Cog.listener()
async def on_ready(self):
self.channel = self.client.get_channel(CHANNEL)
print('starting repeater')
self.repeater.start()
def setup(client):
client.add_cog(Repeater(client))
# --- main ---
client = commands.Bot(command_prefix='!')
setup(client)
print('starting bot')
client.run(TOKEN)