使用discord.py开发Discord机器人时如何从消息中获取频道ID
解决方法
直接从上下文对象ctx中即可获取触发指令的频道ID,同时需要注意存储的ID要能被定时任务访问,推荐使用bot实例属性存储,避免全局变量作用域问题。修正后的可运行代码如下:
# 提前给bot实例绑定属性存储目标频道ID,初始为None bot.target_channel = None @bot.command(name="start", description="Starts for a channel") async def start(ctx): await ctx.send("Started") # 直接获取当前触发指令的频道ID bot.target_channel = ctx.channel.id # 避免定时任务重复启动 if not message_loop.is_running(): message_loop.start() @tasks.loop(seconds=2) async def message_loop(): # 先判断是否有存储的频道ID,避免空值报错 if not bot.target_channel: return channel = bot.get_channel(bot.target_channel) # 额外判断频道是否存在,避免频道被删除后抛出异常 if channel: await channel.send("Message")
关键说明
ctx.channel.id就是你需要的频道ID,为整数类型,可直接传入bot.get_channel()使用- 用bot实例属性存储ID比全局变量更稳定,不会出现跨函数访问不到的问题
- 额外添加的运行状态判断、空值判断可以避免未触发指令就运行定时任务、频道被删除后代码报错的问题
内容的提问来源于stack exchange,提问作者Elliot Smith
相关产品推荐
相关产品推荐

