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

Discord.py 技术求助:如何实现机器人播报输入内容?

搞定你的Discord播报机器人问题!

嘿,我来帮你排查并修复这个问题!你的代码有几个关键的小问题导致它没法正常运行,我一步步给你拆解和修正:

原代码的核心问题

  1. client.say()已被弃用:在新版本的discord.py(v1.0+)里,这个方法早就被移除了,现在需要明确指定发送消息的频道,用channel.send()方法。
  2. 同步input()阻塞事件循环:discord.py是异步框架,你用while True加同步的input()会直接卡死整个机器人的事件处理,导致机器人连在线状态都维持不住,更别说发送消息了。
  3. on_ready可能重复触发:机器人重连时on_ready会再次执行,里面的循环会重复启动,引发混乱。

修复后的可行方案

下面给你两种稳定的实现方式,选一种你觉得顺手的就行:

方案一:用异步线程处理输入(推荐)

这种方式不会阻塞机器人的异步事件循环,兼容性更好:

import discord
import asyncio
from discord.ext import commands

# 替换成你的机器人令牌
TOKEN = "你的机器人令牌"
# 替换成你要发送消息的频道ID(右键频道复制,需开启开发者模式)
TARGET_CHANNEL_ID = 123456789012345678

# 开启必要的意图,Discord现在要求必须配置这个
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix="!", intents=intents)

async def input_broadcast_loop():
    # 等机器人完全就绪后再开始
    await client.wait_until_ready()
    target_channel = client.get_channel(TARGET_CHANNEL_ID)
    
    if not target_channel:
        print("找不到指定频道!请检查ID是否正确。")
        return
    
    print("机器人已就绪,输入内容按回车即可播报:")
    while not client.is_closed():
        # 把同步input放到单独线程,避免阻塞事件循环
        content = await asyncio.to_thread(input, "")
        if content.strip():  # 避免发送空消息
            await target_channel.send(content)

@client.event
async def on_ready():
    print(f"已登录为 {client.user} (ID: {client.user.id})")
    print("------")
    # 启动播报循环任务
    asyncio.create_task(input_broadcast_loop())

client.run(TOKEN)

方案二:用独立线程处理输入

如果你习惯用线程的方式,也可以这么写:

import discord
import threading
from discord.ext import commands

TOKEN = "你的机器人令牌"
TARGET_CHANNEL_ID = 123456789012345678

intents = discord.Intents.default()
client = commands.Bot(command_prefix="!", intents=intents)

def input_thread():
    # 等待机器人就绪
    while not client.is_ready():
        pass
    
    target_channel = client.get_channel(TARGET_CHANNEL_ID)
    if not target_channel:
        print("找不到指定频道!请检查ID是否正确。")
        return
    
    print("机器人已就绪,输入内容按回车即可播报:")
    while not client.is_closed():
        content = input("")
        if content.strip():
            # 在机器人的异步循环里执行发送操作
            client.loop.create_task(target_channel.send(content))

@client.event
async def on_ready():
    print(f"已登录为 {client.user} (ID: {client.user.id})")
    print("------")
    # 启动输入线程,设置为守护线程避免影响机器人退出
    threading.Thread(target=input_thread, daemon=True).start()

client.run(TOKEN)

额外注意事项

  • 去Discord开发者门户,找到你的机器人,开启Privileged Gateway Intents里的必要权限(比如Message Content Intent),不然机器人会无法正常工作。
  • 确保机器人有目标频道的「发送消息」权限。
  • 替换代码里的TOKEN和TARGET_CHANNEL_ID为你自己的信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:45:02