Discord.py中通过命令获取频道ID,报get_channel()缺少id参数如何解决?
问题修复方案
报错核心原因
你遇到的TypeError: get_channel() missing 1 required positional argument: 'id'报错,是因为get_channel是实例方法,不能直接通过Client类调用,必须使用已经初始化完成的机器人实例(也就是你代码中的bot对象)调用该方法。
代码其他错误
- 存在拼写错误:将参数
chnl错写为cnhl,运行时会触发NameError get_channel仅接收整数类型的频道ID,你传入字符串格式的ID无法匹配到对应频道- 导入的
discord.channel模块被你作为全局变量覆盖,属于无效导入
修正后代码
from discord.ext import commands # 初始化机器人实例,指定命令前缀为>,配置基础Intents bot = commands.Bot(command_prefix='>', intents=commands.Intents.default()) saved_channel_id = 0 target_channel = None @bot.command() async def sending(ctx, chnl: int): global saved_channel_id, target_channel saved_channel_id = chnl # 用bot实例调用get_channel方法,传入整数类型ID target_channel = bot.get_channel(chnl) if target_channel: await ctx.send("Saving your ID") else: await ctx.send("频道ID无效,未找到对应频道") # 替换为你的机器人令牌后运行 # bot.run("YOUR_BOT_TOKEN")
注意事项
- 运行代码前需要先在Discord开发者后台的机器人设置中开启对应权限和Intents,否则无法正常获取频道信息
- 后续如果要向保存的频道发送消息,直接调用
await target_channel.send("你要发送的内容")即可 - 全局变量存储的频道信息会在机器人重启后清空,若需要持久化存储建议搭配本地文件或数据库使用
内容的提问来源于stack exchange,提问作者Daniel Rosas
相关产品推荐
相关产品推荐

