获取频道名称并在该频道发送消息

get channel name and send a message over at that channel

所以我正在这里做一个小项目,非常想拥有其中一个“请在此服务器中输入频道的名称”功能。

差不多,机器人要求一个频道名称,我输入了例如“#changelog”——然后它会询问它应该在那个频道中写什么,等等。 所以需要获取频道 ID(我猜),但我不希望用户写 ID,而只写#server-name。然后每当我这样做时,机器人就会在那个频道中写信。

这是我当前的代码!

class Changelog(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        print('Changelog is loaded')

    @commands.command()
    async def clhook(self, ctx):
        await ctx.send('Write text-channel: ')
        text_channel = await self.client.wait_for("message", check=lambda message: message.author == ctx.author, timeout=300)
        clhook = self.client.get_channel(text_channel)


def setup(client):
    client.add_cog(Changelog(client))

编辑: 频道ID将“永久”保存,这意味着我不必重写消息应该去的频道名称!

您可以使用 message.channel_mentions。这将 return 使用 #channel-name 表示法提及的所有频道的 list。这样,您只需使用 channel.id 即可获得他们提到的频道的 id

但是,请不要忘记检查用户 确实 是否确实标记了一个频道(您也可以将其放入您的 check 中)。为了这个回复,我把它放在一个单独的函数中以使其更具可读性,但如果你真的想的话,你可以把它放在你的 lambda 中。

此外,请确保检查它是 Text Channel 而不是 Voice ChannelCategory Channel

@commands.command()
async def clhook(self, ctx):

    def check(self, message):
        author_ok = message.author == ctx.author  # Sent by the same author
        mentioned_channel = len(message.channel_mentions) == 1 and isinstance(message.channel_mentions[0], discord.TextChannel)
        return author_ok and mentioned_channel

    await ctx.send("Write text-channel: ")
    text_channel = await self.client.wait_for("message", check=check)
    chlhook = text_channel.channel_mentions[0]

我在 mentioned_channel 行放了两个条件,因为如果第一个失败,第二个可能会导致 IndexError。或者,您也可以在那个地方更快地使用 if-statement 到 return 来解决同样的问题。

您可以在这个例子中使用 discord.utils.get()

text_channel = await self.client.wait_for("message", check=lambda message: message.author == ctx.author, timeout=300)
channel = discord.utils.get(ctx.guild.text_channels, name=text_channel)
await channel.send('Bla Bla')

因此,当您键入 (prefix)clhook 时,仅输入频道名称,例如 general,它会将 Bla Bla 发送到名为 [=24= 的频道]一般 .

还有另一种方法,我认为它比第一种方法简单,这里是:

@commands.command()
async def clhook(self, ctx, channel: discord.TextChannel):
    await channel.send('Bla Bla')

所以在这条命令中,用法发生了变化。您可以将其与此一起使用:(prefix)clhook #general(mention the channel)。我推荐这个解决方案,我认为它更有用。