You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中如何在@tasks.loop()任务循环中提及用户

解决discord.py任务循环无法获取ctx/用户信息的问题

要实现自动启动循环并提及触发消息的成员,核心思路是提前存储需要的频道ID和用户ID,让循环函数能通过bot实例获取对应的频道和用户对象,具体方案如下:

方案1:使用全局变量存储目标信息(快速实现)

from discord.ext import tasks, commands

client = commands.Bot(command_prefix='!')

# 存储触发循环的频道和用户ID
target_channel = None
target_user = None

@tasks.loop(seconds=120)
async def nameHere():
    global target_channel, target_user
    # 确保信息存在再执行
    if target_channel and target_user:
        # 通过ID获取频道和用户对象
        channel = client.get_channel(target_channel)
        user = client.get_user(target_user)
        if channel and user:
            await channel.send(f"@{user.name} 这是循环推送的消息!")

@client.event
async def on_message(message):
    global target_channel, target_user
    # 忽略bot自身发送的消息
    if message.author == client.user:
        return
    
    # 这里可自定义触发条件:比如指定频道、特定关键词等
    if message.channel.id == 123456789:  # 替换成你的目标频道ID
        target_channel = message.channel.id
        target_user = message.author.id
        # 避免重复启动循环
        if not nameHere.is_running():
            nameHere.start()
    
    # 必须保留,否则bot无法处理其他命令
    await client.process_commands(message)

client.run('你的BotToken')

方案2:使用类属性存储(更优雅的结构)

如果你的bot是基于类编写的,用实例属性替代全局变量更规范:

from discord.ext import tasks, commands

class CustomBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.target_channel_id = None
        self.target_user_id = None

    @tasks.loop(seconds=120)
    async def nameHere(self):
        if self.target_channel_id and self.target_user_id:
            channel = self.get_channel(self.target_channel_id)
            user = self.get_user(self.target_user_id)
            if channel and user:
                await channel.send(f"{user.mention} 循环消息提醒!")

    async def on_message(self, message):
        if message.author == self.user:
            return
        
        # 触发条件:比如消息包含"启动循环"关键词
        if "启动循环" in message.content:
            self.target_channel_id = message.channel.id
            self.target_user_id = message.author.id
            if not self.nameHere.is_running():
                self.nameHere.start()
        
        await self.process_commands(message)

bot = CustomBot(command_prefix='!')
bot.run('你的BotToken')

关键注意事项

  • 确保bot拥有对应频道的发送消息权限,否则会抛出权限错误。
  • 用is_running()判断循环状态,避免重复启动导致报错。
  • 如果需要支持多用户/多频道,可以用字典或列表存储多个目标ID,在循环里遍历处理。

内容的提问来源于stack exchange,提问作者user15229647

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 18:23:14