Discord.py文本通道检查

时间:2020-08-09 19:53:55

标签: python discord.py

@client.command(aliases=["logchannel, setlog"])
@commands.has_permissions(manage_messages=True)
async def log(ctx, *args: discord.TextChannel):
    with open("configs/channels.json", "r") as f:
        channels = json.load(f)
    channel = channels.get(str(ctx.guild.id), ctx.channel.id)
    if len(args) == 0:
        await ctx.send("Which channel should I set the logs? :thinking:")
    elif args[0] != discord.TextChannel:
        await ctx.send("That is not a valid channel!")
    elif args[0] == discord.TextChannel:
        with open("configs/channels.json", "w") as f:
            json.dump(channels, f, indent=4)
        embed = discord.Embed(title="Log channel set! :white_check_mark:",
                              description=f"**{channel}** has been set as logs channel!",
                              color=0x2f3136)
        await ctx.send(embed=embed)

因此,我的代码的这一部分用于使用JSON设置日志通道。 json部分工作正常,因为我在其他几个命令中使用了它。但是它没有看到是否有一个有效的通道。据我了解,应该是discord.TextChannel,但事实并非如此。 if len(args) == 0部分有效,其他部分无效。我该如何工作?我应该代替discord.TextChannel放什么?

3 个答案:

答案 0 :(得分:0)

Return只是结束了您可以使用它的函数,而不是if语句。我不知道使用的JSON文件是什么,希望对您有所帮助

async def log(ctx, *, args=None):
    if not args:
        await ctx.send("Which channel should I set the logs? :thinking:")
        return

    for channel in ctx.guild.channels:
        if channel.name == args:
            await ctx.send('Found your channel')
            # channel is now an object, you can do what you want here
            await channel.send('This is the channel wanted')
            return

    await ctx.send("Can't find your channel")

答案 1 :(得分:0)

一种更精确的方法是使用TextChannelConverter,因为当提供ID /名称/提示(不仅是名称)时,它返回频道

from discord.ext import commands

async def log(ctx, *, args=None):
    if not args:
        await ctx.send("Please provide the channel to set the logs")
        return
    try:
        channel = await commands.TextChannelConverter().convert(ctx, args)
    except:
        return await ctx.send("Channel Not Found")
    #channel is not a TextChannel object, save its ID or send or whatever you want to do

答案 2 :(得分:0)

我认为它可以在此基础上工作。

    @commands.command()
    async def test(self, ctx, channel=None):

        channel2 = self.client.get_channel(id=int(channel))

        if type(channel2) != discord.channel.TextChannel:
            await ctx.send('Please do not enter an audio channel')

        else:
            await ctx.send('Perfect.')