在Discord Interactions中通过ID获取频道的技术问询
解决discord-interactions无法通过ID获取频道的问题
discord-interactions的Client类确实没有get_channel方法,你需要用异步的fetch_channel方法来替代,具体用法如下:
核心解决方案
使用await bot.fetch_channel(channel_id)获取频道对象,注意这个方法必须在异步函数中调用——所有Discord API交互都是异步的,必须配合await使用。
修改后的代码示例
from interactions import Client, Intents bot = Client( token=my_token, intents=Intents.ALL ) # 在机器人就绪事件中获取频道并发送日志 @bot.event async def on_ready(): # 获取日志频道 logs_channel = await bot.fetch_channel(1015371164312424468) # 发送日志消息 await logs_channel.send("机器人启动完成,日志频道连接成功") print("机器人已上线") # 如果是在交互命令中使用 @bot.slash_command(name="test_log", description="发送测试日志") async def test_log_command(ctx): logs_channel = await bot.fetch_channel(1015371164312424468) await logs_channel.send("来自测试命令的日志消息") await ctx.send("测试日志已发送") bot.start()
注意事项
- 必须在
async def定义的异步函数中使用await调用fetch_channel,不能在全局代码中直接调用,否则会报错 - 确保机器人拥有目标频道的访问权限(查看频道、发送消息等)
fetch_channel会直接向Discord API发起请求获取频道数据,无需依赖本地缓存
内容的提问来源于stack exchange,提问作者Leums
相关产品推荐
相关产品推荐

