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

Python Discord Bot中bot.loop.create_task函数不生效问题求助

问题根源

调用bot.loop.create_task时卡住的核心原因是Discord Bot的事件循环尚未启动,或调用代码与bot不在同一运行线程:

  • 你直接运行send_msg.py作为入口时,导入bot.py的过程中bot实例仅完成了初始化,并未执行bot.run()启动事件循环,向未启动的循环提交任务自然会阻塞
  • 若bot和send_msg运行在不同进程/线程,跨环境操作事件循环也会触发阻塞

修复方案

场景1:仅在Bot内部逻辑调用发消息

确保action函数的调用时机在bot.run()执行之后,比如在命令回调、事件回调中调用不会有问题,同时优化代码避免全局变量:

# bot.py
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
TARGET_CHANNEL_ID = 替换为实际频道ID

async def send_msg(word):
    await bot.wait_until_ready()
    ch = bot.get_channel(TARGET_CHANNEL_ID)
    if ch:
        await ch.send(f"The word {word} has been spoken :)")

def action(word):
    bot.loop.create_task(send_msg(word))

# 示例:在命令中调用action
@bot.command()
async def trigger(ctx, word):
    action(word)
    await ctx.send("消息已提交发送")

bot.run("你的Bot Token")

场景2:需要从外部独立脚本触发Bot发消息

不要直接跨脚本操作bot的事件循环,用消息队列做进程间通信即可:

  1. 先启动bot服务,后台监听消息队列
  2. 外部脚本把要发送的内容推到队列中,bot监听到内容后主动发送
# bot.py (加队列监听)
import discord
from discord.ext import commands
import asyncio
import redis

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
TARGET_CHANNEL_ID = 替换为实际频道ID
# 用redis做队列,也可以替换为本地socket、文件队列等其他方案
queue = redis.Redis(host="127.0.0.1", port=6379, db=0)

async def queue_listener():
    await bot.wait_until_ready()
    while not bot.is_closed():
        word = queue.lpop("discord_msg_queue")
        if word:
            ch = bot.get_channel(TARGET_CHANNEL_ID)
            if ch:
                await ch.send(f"The word {word.decode()} has been spoken :)")
        await asyncio.sleep(1)

@bot.event
async def on_ready():
    bot.loop.create_task(queue_listener())
    print("Bot启动完成")

bot.run("你的Bot Token")
# send_msg.py(外部触发脚本)
import redis
queue = redis.Redis(host="127.0.0.1", port=6379, db=0)

def action(word):
    queue.rpush("discord_msg_queue", word)

# 调用示例
action("test")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:54:02