【问题标题】:Can I use a variable inside a parameter of a function in py-cord?我可以在 py-cord 中的函数参数内使用变量吗?
【发布时间】:2022-11-14 20:11:18
【问题描述】:

我的问题

我正在尝试使用一个变量,该变量根据来自operation_select 的用户输入选择某个列表斜线命令在 py-cord 中。每当我在 select_role 中运行脚本 aircraft option命令总是别无选择。我预料到了这一点,因为我已经用 [ ] 定义了变量。

import shutil
import discord.ext
from discord import Option
from discord.ext import commands

bot = commands.Bot(intents=discord.Intents.all())

air = []

@bot.slash_command(name="operation_select")
async def operation_select(ctx,
mission: Option(str, "Select A Mission", choices=\["Night Terror", "Other"\]),

):

    if mission == ("Night Terror"):
        air = [
    
    if mission == ("Other"):
        air = ["1","2"]
    
    
    
    shutil.copyfile("EENight Terror.txt", "Night Terror.txt")
    with open(f"{mission}.txt", "r") as file:
    
        await ctx.respond(file.read())

@bot.slash_command(name="select_role", description="Select you role")
async def role_select(ctx,
aircraft: Option(str, "Select your aircraft", choices=air)

):

    await ctx.send(air)

bot.run(TOKEN HERE)

我试过的

我尝试使用变量 air 作为函数内外的全局变量。

if mission == ("Night Terror")
   global air
   air = ["AH64D", "MI24", "KA50"]

然而,我的任何尝试都没有奏效。

实际结果

当在不和谐中输入select_role 命令时,aircraft option 将没有选择,当在其中输入任何内容并按 Enter 时,它将返回列表**["AH64D", "MI24", "KA50"]** 我之所以选择是因为我之前运行过@选择角色之前的 987654329@ 命令。

我想要的结果

运行 operation_select 命令时,我希望它根据用户的选择更改变量选择列表。当select_role 命令运行时,这将改变您可以选择的aircraft

【问题讨论】:

    标签: python function discord bots pycord


    【解决方案1】:

    据我所知,不可能为命令分配动态变量。但是,我能想到 2 个解决方案。

    1. 回调函数可以在命令中使用。这使得动态搜索一大堆结果成为可能。当然,这可以通过全局变量对air 进行访问,从而使最高结果为aircraft option
    2. 使用discord.ui.View。这将创建一个视图窗口。这将需要更多的工作,并带来更灵活的好处。与第一个解决方案类似,可以在创建不和谐视图时通过回调函数分配变量。

      第一个解决方案类似于下面的代码片段。我确实从我的不和谐机器人中删除了它,这是关于出于某种原因选择世界上的一个城市。

      AUTOCOMPLETE_CITIES = ["Tokio", "Paris", "London"]
      
      def autocomplete_check(ctx: discord.AutocompleteContext) -> list:
          """Must return a list of strings"""
          return [val for val in AUTOCOMPLETE_CITIES[:25] if ctx.value in val]
      
      
      @client.slash_command(name="my command", description="oi mate")
      async def _my_command(ctx,
                       city: Option(str,
                                    name='city',
                                    description='Select a city.',
                                    required=True,
                                    autocomplete=autocomplete_check)
                       ):
          print(city, type(city))
          return await ctx.respond(f'You chose {city}')
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多