如何在discord.py中获取所有DM频道的列表
获取Discord.py机器人的所有DM频道列表
当然可以实现!你遇到的问题大概率是方法调用方式不对或者版本适配问题,下面分版本给你详细说明解决方案:
Discord.py v2.x 及以上版本
在新版本中,获取私有频道(包含DM和群组DM)需要使用异步方法await bot.fetch_private_channels(),同步调用会返回一个协程对象而非实际列表,这也是你之前尝试失败的原因之一。
示例代码:
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.command() async def list_dms(ctx): # 获取所有私有频道 all_private_channels = await bot.fetch_private_channels() # 过滤出一对一的DM频道(排除群组DM) direct_messages = [channel for channel in all_private_channels if channel.type == discord.ChannelType.private] # 提取频道对象列表或ID列表 dm_objects = direct_messages dm_ids = [channel.id for channel in direct_messages] await ctx.send(f"获取到的DM频道对象:{dm_objects}\n对应的DM频道ID列表:{dm_ids}") bot.run("你的机器人Token")
Discord.py v1.x 版本(旧版本)
旧版本中可以直接通过同步属性bot.private_channels获取所有私有频道,同样可以过滤出一对一DM:
示例代码:
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!") @bot.command() async def list_dms(ctx): # 过滤出一对一DM频道 direct_messages = [channel for channel in bot.private_channels if channel.type == discord.ChannelType.private] dm_objects = direct_messages dm_ids = [channel.id for channel in direct_messages] await ctx.send(f"获取到的DM频道对象:{dm_objects}\n对应的DM频道ID列表:{dm_ids}") bot.run("你的机器人Token")
为什么你之前的尝试失败?
bot.get_private_channels():在v2.x中这是异步方法,必须用await调用,同步调用无法拿到实际数据;bot.get_channels()/bot.channels:这两个仅包含机器人加入的服务器中的频道,不包含DM频道;bot.get_dms():Discord.py中不存在这个方法,属于错误调用。
另外需要注意:机器人只能获取已经存在的DM频道,也就是和用户发起过对话的频道,无法获取未建立过对话的用户的DM(因为这类频道对象还未被创建)。
内容的提问来源于stack exchange,提问作者SirFire




