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

Discord.py实现消息多频道转发问题求助

解决Discord机器人多频道消息转发问题

你的问题出在test001to是多个频道ID的集合,但bot.get_channel()只能接收单个频道ID作为参数,直接传元组会触发错误。要实现多频道转发,只需要循环遍历每个目标频道ID,逐个处理即可。

修改后的完整代码

import discord
from discord.ext import commands

# 配置意图:discord.py v2.x需要显式开启message_content才能读取消息内容
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True

# 来源频道ID
source_channel_id = 1029028218684055562
# 目标频道ID列表(可添加更多)
target_channel_ids = [1028777554217291806, 1028777583808098304]

bot = commands.Bot(command_prefix=".", intents=intents)

@bot.event
async def on_ready():
    print("Bot Active")

@bot.event
async def on_message(message):
    # 忽略机器人自己发的消息,避免循环转发
    if message.author.bot:
        return
    
    # 判断消息是否来自指定来源频道
    if message.channel.id == source_channel_id:
        # 遍历所有目标频道ID
        for channel_id in target_channel_ids:
            target_channel = bot.get_channel(channel_id)
            # 检查频道是否存在(避免无效ID导致报错)
            if target_channel:
                try:
                    await target_channel.send(message.content)
                except discord.Forbidden:
                    print(f"无权限向频道 {channel_id} 发送消息")
                except Exception as e:
                    print(f"发送消息到频道 {channel_id} 失败: {str(e)}")
            else:
                print(f"未找到频道ID {channel_id}")

bot.run("YOUR_BOT_TOKEN")

关键修改说明

  1. 意图配置优化:discord.py v2.x版本默认关闭了message_content意图,必须显式开启才能读取消息内容,否则会无法获取message.content。
  2. 循环遍历目标频道:用for循环逐个处理每个目标频道ID,调用get_channel()获取对应频道对象后发送消息。
  3. 异常处理:添加了权限检查和错误捕获,避免单个频道出错导致整个转发流程中断,同时输出错误信息方便排查问题。
  4. 忽略机器人消息:新增判断message.author.bot,防止机器人转发自己的消息造成循环。

注意事项

  • 确保机器人已加入所有目标频道所在的服务器,并且拥有发送消息的权限。
  • 如果需要添加更多目标频道,直接在target_channel_ids列表中追加ID即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:50:28