简体   繁体   English

Discord.py 通道检测

[英]Discord.py channel detection

I am creating a discord bot and would like to know if the argument detected after the context is a channel.我正在创建一个不和谐的机器人,想知道在上下文之后检测到的参数是否是一个通道。 I tried doing this.我试过这样做。

@client.command()
async def channeldetected(ctx, arg):
  if arg != channel.type:
    await ctx.send('Please mention a channel.')

But it didn't work.但它没有用。 I tried looking in the discord developer docs and across stackoverflow, but could not find the answer.我尝试查看 discord 开发人员文档和 stackoverflow,但找不到答案。 Help would be appreciated.帮助将不胜感激。 Thanks.谢谢。

Try this:试试这个:

import discord
from discord.ext import commands

@client.command()
async def channeldetected(ctx, channel: discord.TextChannel):
    print(channel)


@channeldetected.error
async def channeldetected_error(ctx, err):
    if isinstance(err, commands.ChannelNotFound):
        await ctx.send("Please mention a channel.")

What is happening: channeldetected funtion will try to modify the channel argument to a discord.TextChannel object.这是怎么回事: channeldetected funtion会尝试修改channel参数传递给一个discord.TextChannel对象。 If the argument can't be modified it will raise commands.ChannelNotFound error then in the @channeldetected.error function the error can be handeled.如果无法修改参数,则会引发commands.ChannelNotFound错误,然后在@channeldetected.error函数中可以处理该错误。 If the error is an instance of commands.ChannelNotFound it will send message saying "Please mention a channel.".如果错误是commands.ChannelNotFound一个实例,它将发送消息说“请提及一个频道。”。

To do something like this I would recommend iterating through guilds/servers channels to see if the channel's name is "arg".为了做这样的事情,我建议遍历公会/服务器频道以查看频道的名称是否为“arg”。 To do this you can use the guild attribute from ctx/context.为此,您可以使用 ctx/context 中的 guild 属性。

@client.command()
async def channeldetected(ctx, arg):
  guild = ctx.guild
  channel = None
  is_channel = False

  for i in guild.channels:
      if i.name == arg:
          is_channel = True
          channel = i

  print(is_channel, channel)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM