如何获取Discord Bot刚创建频道的ID以自动发送消息?
解决Discord Bot创建申请频道后无法发送消息的问题
你的核心问题是没有保存创建频道后的返回对象。guild.create_text_channel()方法执行后会返回刚创建的频道实例,直接用这个实例就能在频道里发消息,不需要单独获取ID。
修改后的代码:
import discord intents = discord.Intents.default() intents.message_content = True # 注意:discord.Client没有prefix参数,这里删掉多余的无效参数 client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'{client.user} est connecté !') @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('!startApply'): guild = message.guild Officier = discord.utils.get(message.guild.roles, name="Officier") overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), message.author: discord.PermissionOverwrite(read_messages=True), Officier: discord.PermissionOverwrite(read_messages=True) } # 把创建的频道对象保存到变量new_channel new_channel = await guild.create_text_channel(f'Apply {message.author}', overwrites=overwrites) # 直接用new_channel发送问题,示例如下 await new_channel.send(f"欢迎你 {message.author.mention}!请回答以下问题:") await new_channel.send("1. 你申请的职位是?") await new_channel.send("2. 你的相关经验有哪些?") client.run('my_token')
关键说明:
guild.create_text_channel()返回的new_channel就是刚创建的频道对象,直接调用它的send()方法就能发送消息- 移除了
discord.Client中无效的prefix参数(该参数属于commands.Bot,如果后续想使用更规范的命令框架,可以换成commands.Bot)
内容的提问来源于stack exchange,提问作者Rollzy_ug
相关产品推荐
相关产品推荐

