【发布时间】:2021-07-06 12:20:59
【问题描述】:
我在命令中检索通道对象时有点停滞不前。而不是使用async def command(ctx, channel:discord.TextChannel)或类似的,我想从用户的wait_for消息内容的产品中获取频道对象,我不会在这里包含。
例如,如果用户说general、id 757115231377031169,或者只是提到频道#general,则无论输出是否有效,机器人都可以检索 TextChannel 对象。
简而言之:我如何在代码本身中获得TextChannel Object?
以下是我尝试过的几件事:
我曾尝试在转换器的帮助下通过调用另一个命令来检索通道对象。这通常会引发错误'str' object has no attribute 'mention'(这是我最近的选择,我有比这更好的想法)
@client.command()
async def chan_convert(ctx, channel:discord.TextChannel):
return channel
@client.command()
async def test(ctx, channel):
try:
ch = await ctx.invoke(client.get_command("chan_convert"), channel=channel)
await ctx.send(ch.mention)
except Exception as e:
await ctx.send(str(e))
我解决问题的另一种方法是使用我尝试创建的自定义函数,但这只能工作到某个点,例如如果您输入了频道 ID,它会引发错误 AttributeError: 'NoneType' object has no attribute 'mention'。
def custom_chan(guild:discord.Guild, channel):
if channel.isnumeric(): # if it's all numbers, it could be an id
try:
channel = guild.get_channel(channel)
return [True, channel]
except:
return [False, "ID was not valid"]
else:
if channel.startswith("<#") and channel.endswith(">"): # <#123123123123123123> format of channel mention
channel = channel.replace("<#", "")
channel = channel.replace(">", "")
try:
channel = guild.get_channel(channel)
return [True, channel]
except:
return [False, "ID was not valid"]
else: # otherwise, it's just a name, check if it exists
try:
channel = discord.utils.get(guild.channels, name=channel)
return [True, channel]
except:
return [False, "No channel with that name was found"]
def channel_check(channel):
return type(channel)
chan = custom_chan(ctx.guild, "757115231377031169") # an id I put in here originally
await ctx.send(chan[1].mention)
await ctx.send(channel_check(chan))
提前谢谢你。
【问题讨论】:
标签: discord discord.py