【问题标题】:How to change channel name where the channel will be the mentioned channel or ctx.channel depending on if I mention a channel or not如何更改频道名称,其中频道将是提到的频道或 ctx.channel,具体取决于我是否提到频道
【发布时间】:2021-09-23 12:52:08
【问题描述】:

标题有点混乱,但我想创建一个命令,允许用户更改频道名称。现在,如果命令中未提及频道,我希望它更改 ctx.channel 的名称,如果提及频道,则更改提及的频道。这是我尝试过的,但它不起作用:

  @_channel.command(name="rename",
                    aliases=["re"],
                    brief="Renames channel.",
                    help="Renames the current channel or mentioned channel if argument passed.")
  async def _rename(self, ctx, channel, *, newname=None):
      if not newname:
          newname = channel
          channel = ctx.channel
          current_name = ctx.channel.name
          await ctx.channel.edit(name = newname)
          await ctx.send(f"Changed channel name from **{current_name}** to **{ctx.channel.name}**.")

      elif newname != None:
          current_name = ctx.channel.name
          await ctx.channel.edit(name = newname)
          await ctx.send(f"Changed channel name from **{current_name}** to **{ctx.channel.name}**.")

例如,如果我执行命令 >ch rename general 我希望它重命名 ctx.channel 的名称为“一般”,但如果我提到一个频道并执行 >ch rename #bot general 我想要它将提到的“bot”频道名称更改为“general”

【问题讨论】:

    标签: python-3.x discord.py


    【解决方案1】:

    您可以使用discord converters。这允许您要求 discord.py 尝试为您转换参数。 Optional[discord.TextChannel] 表示尝试将一个参数转换为discord.TextChannel,如果失败则将值设置为无。

    from typing import Optional
    
    @commands.command(name='rename')
    async def _rename(ctx, channel: Optional[discord.TextChannel] = None, *, new_name = None):
        if channel is None:
            channel = ctx.channel
        await ctx.send(f'Change {channel} to {new_name}')
    

    如果 new_name 为 None,你可能想抛出一个错误。

    【讨论】:

    • 谢谢!我很感激。
    • 哦,我的机器人在不同的 cog 中设置了一种通用错误处理程序,它基本上只是告诉您在可读文本中做错了什么,而不是在控制台中打印的内容
    【解决方案2】:

    这是最后的命令,感谢@Nevus 的帮助,根据我的需要进行了调整!

      @_channel.command(name="rename",
                        aliases=["re"],
                        brief="Renames channel.",
                        help="Renames the current channel or mentioned channel if argument passed.")
    
      async def _rename(self, ctx, channel: Optional[discord.TextChannel] = None, *, newname):
          if channel is None:
              channel = ctx.channel
    
          current_name = channel.name
          await channel.edit(name = newname)
          await ctx.send(f"Changed {channel.mention}'s name from **{current_name}** to **{channel.name}**.")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 2019-02-13
      • 2012-11-14
      • 2018-12-12
      • 2014-10-13
      • 2018-12-16
      • 1970-01-01
      相关资源
      最近更新 更多