python - discord.py 的 cog 任务
问题描述
这应该每 15 分钟在频道中发送一条消息。由于某种原因,它不起作用。它也没有显示任何错误。有人可以帮我解决这个问题吗?
import time
from discord.ext import commands
message = 'choose roles from <#728984187041742888>'
channel_id = 742227160944869437 # the channel id (right click on the channel to get it)
time_spacing = 15*60 # s : 15min
class auto(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def spamm(self, ctx):
while True:
time.sleep(time_spacing)
await ctx.get_channel(channel_id).send(message)
@commands.Cog.listener()
async def on_ready(self):
print(f'Sp4mm3r {self.bot.user} has connected to Discord!')
print('Sending message :', message, 'every', time_spacing, 'seconds')
def setup(bot):
bot.add_cog(auto(bot))
----------更正版------------ 认为问题是我没有开始任务,并且 time.sleep 不应该在那里使用。
from discord.ext import tasks
from discord.ext import commands
time = 30*60
class Automessager(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.message = 'Choose roles from <#728984187041742888>'
self.channel1 = 725550664561983519
self.text.start()
@tasks.loop(seconds=time)
async def text(self):
try:
channel = self.bot.get_channel(self.channel1)
await channel.send(self.message)
except Exception as e:
print(e)
@commands.Cog.listener()
async def on_ready(self):
print(f'{self.bot.user} has connected to Discord!')
print(f'Sending message: {self.message} every {time} seconds')
def setup(bot):
bot.add_cog(Automessager(bot))
解决方案
您的代码中有两个错误:
get_channel()
是commands.Bot
方法,不是discord.Context
方法。- 如果你习惯
time.sleep()
等待 15 分钟,它会冻结你的整个齿轮。
要制作循环,您可以使用task.loop()
, 而不是使用 cog 侦听器:
from discord.ext import task
from discord.ext import commands
class auto(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.message = 'Choose roles from <#728984187041742888>'
self.channel_id = 742227160944869437
self.minutes = 15
@task.loop(minutes=self.minutes)
async def spamm(self, ctx):
channel = self.bot.get_channel(self.channel_id)
await channel.send(self.message)
@commands.Cog.listener()
async def on_ready(self):
print(f'Sp4mm3r {self.bot.user} has connected to Discord!')
print(f'Sending message: {self.message} every {self.minutes} minutes')
def setup(bot):
bot.add_cog(auto(bot))
PS:我已经设置channel_id
,message
和minutes
作为类变量。您也不需要使用time.sleep()
.
推荐阅读
- java - Netbeans org.apache.poi - 无法访问 Date1904Support
- python - 如何标准化与时间戳相关的分类变量
- json - 如何将 json 转换或映射为特定的 json 格式
- shell - “如何在 shell 中修复 'sed + grep no return status when no match' 错误”
- python - “django-admin makemessages”是否有任何解决方法不对已经更新的翻译进行更改?
- django - “如何修复“django 中的错误”无法导入通道路由 'projectname.routing.channal_routing' 没有模块名称路由
- android - 备份sqlite数据库的最佳方法是什么?
- python - 如何扩展/重用 Python C 扩展/API 实现?
- python - 如何使用python生成身份证号码?
- javascript - 在浏览器和服务器之间交换数据时,数据只能是文本。为什么?