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

Discord Bot运行无报错但无法跨频道转发消息问题求助

问题修复方案

代码核心错误点

  • Vedantu_channels列表中存储的是字符串类型的频道ID,而message.channel.id返回的是整数,类型不匹配导致判断永远不成立
  • 你在bot实例未完成登录初始化的阶段调用bot.get_channel(),此时bot无缓存数据,获取到的ch对象为None,无法执行发送动作
  • 启动client实例时参数错误,你定义的token变量是bot1_token,但代码里传的是未定义的bot1,导致client无法正常登录
  • 未开启Discord Bot的消息内容意图,discord.py v2.0+版本默认关闭该权限,会导致on_message事件无法正常获取消息内容
  • 冗余逻辑过多:重复的if判断、重复获取事件循环、同时运行两个Bot实例完全没必要,单个实例即可同时完成消息监听和发送功能
  • 目标频道需要确保对应Bot有权限在该频道发送消息

修复后代码

import discord
from discord.ext.commands import Bot
import asyncio

try:
    import requests,json,pytz,time
    from dhooks import Webhook, Embed
    import datetime
    from pytz import timezone
    import sys
    import subprocess
except Exception as e:
    print("Import Error:",str(e))

# 配置参数
bot_token = "你的Bot令牌" # 只用一个Bot即可,同时给它监听源频道和发送到目标频道的权限
bot_prefix = "#"

# 所有ID改成整数类型
Vedantu_channels = [873257403217481738] 
target_channel_id = 853480780214698014

# 开启必要的意图
intents = discord.Intents.default()
intents.message_content = True # 必须开启,否则无法获取消息内容

bot = Bot(command_prefix=bot_prefix, intents=intents)
bot.remove_command('help')

ch = None

@bot.event 
async def on_ready(): 
    global ch
    # 登录完成后再获取频道对象
    ch = bot.get_channel(target_channel_id)
    print(f"Logged in as {bot.user.name}")    
    if not ch:
        print("警告:无法获取目标频道,请检查频道ID和Bot权限")

@bot.event
async def on_message(message): 
    # 忽略Bot自己发的消息,避免循环触发
    if message.author.bot:
        return
    if message.channel.id in Vedantu_channels:
        content = message.content
        if "w1" in content:
            await ch.send("1")
        elif "w2" in content:
            await ch.send("2")
    # 保留命令处理逻辑,如果你需要使用前缀命令的话可以保留
    await bot.process_commands(message)

if __name__ == "__main__":
    asyncio.run(bot.start(bot_token))

额外检查项

  • 前往Discord开发者后台,在Bot设置页开启Message Content Intent开关
  • 确认Bot已经加入源频道和目标频道,且拥有「查看频道」「发送消息」权限
  • 确认所有频道ID填写正确,无复制错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 02:18:01