discord.py 向频道名称而不是 ID 发送消息

时间:2021-05-26 02:06:05

标签: discord discord.py

我是这个编程东西的初学者,我有一个简单的问题。我正在尝试为多个服务器创建一个日志通道,我希望能够找到一个包含“日志”一词的通道,你能帮我吗?

代码:

@client.event
async def on_command_completion(ctx):
    channel = client.get_channel('829067962316750898')
    embed = discord.Embed(colour=discord.Color.green(),
                          title="Command Executed")
    embed.add_field(name="Command:", value=f"`,{ctx.command}`")
    embed.add_field(name="User:", value=f"{ctx.author.mention}", inline=False)
    embed.add_field(name="Channel:",
                    value=f"{ctx.channel} **( <#{ctx.channel.id}> )**")
    await channel.send(embed=embed)

1 个答案:

答案 0 :(得分:2)

您需要获取频道。我建议使用 discord.utils.get
此外,请尝试使用 {ctx.channel.mention} 来提及频道。

@client.event
async def on_command_completion(ctx):
    channel = discord.utils.get(ctx.guild.text_channels, name='logs')
    if channel is None:
         return # If there is no logs channel, do nothing (or what you want to do)
    embed = discord.Embed(colour=discord.Color.green(),
                          title="Command Executed")
    embed.add_field(name="Command:", value=f"`,{ctx.command}`")
    embed.add_field(name="User:", value=f"{ctx.author.mention}", inline=False)
    embed.add_field(name="Channel:",
                    value=f"{channel.name} **( {channel.mention} )**")
    await channel.send(embed=embed)

参见 discord.TextChannel docsdiscord.utils.get()