如何在discord.py按钮类中更新变量?

huangapple go评论69阅读模式
英文:

How to update a variable in a discord.py buttons class?

问题

I understand your request. Here's the translated code portion:

所以我正在尝试创建一个命令其中包含按钮每次执行时都会发送不同的问题和不同的选项这些问题/选项是从文本文件中提取的我使用一个计数器来告诉代码提取不同的问题但似乎总是提取相同的问题

这是我用于按钮的代码
```python
class buttons(discord.ui.View):
    def __init__(self):
        super().__init__()
    with open("temp.txt", "r") as fp:
        for i, line in enumerate(fp):
            global count
            count = 0
            if i == count:
                answer = json.loads(line)
                global current_question
                current_question = {}
                current_question["Question"] = answer.get("Question")
                current_question["Option1"] = answer.get("Option1")
    global option1
    option1 = current_question.get("Option1")
    @discord.ui.button(label=option1, style=discord.ButtonStyle.blurple)
    async def op1(self, interaction: discord.Interaction, button: discord.ui.Button):
    ...

这是执行时应该提高计数器的命令的代码:

@bot.command()
async def test(ctx):
    await ctx.send(current_question.get("Question"), view=buttons())
    global count
    count += 1

我必须将按钮放在一个类中,我不知道如何在那里更新计数变量,它卡在0上,而且一直发送相同的问题和选项。
任何帮助都将不胜感激。


如果您有任何其他需要,请随时告诉我。

<details>
<summary>英文:</summary>

So I&#39;m trying to make a command that has buttons that sends a different question with different options each time it&#39;s executed, the questions/options are pulled from a text file. I&#39;m using a counter to tell the code to pull a different question, but it seems to be pulling the same one always.


This is the code I&#39;m using for the buttons:

class buttons(discord.ui.View):
def init(self):
super().init()
with open("temp.txt", "r") as fp:
for i, line in enumerate(fp):
global count
count = 0
if i == count:
answer = json.loads(line)
global current_question
current_question = {}
current_question["Question"] = answer.get("Question")
current_question["Option1"] = answer.get("Option1")
global option1
option1 = current_question.get("Option1")
@discord.ui.button(label=option1, style=discord.ButtonStyle.blurple)
async def op1(self, interaction: discord.Interaction, button: discord.ui.Button):
...

And this is the code for the command that when executed, should raise the counter by one:

@bot.command()
async def test(ctx):
await ctx.send(current_question.get("Question"), view=buttons())
global count
count +=1

I have to keep the buttons in a class, and I just don&#39;t know how to get the count variable to update there, It&#39;s stuck on 0 and it&#39;s sending the same questions and options.
Any help would be appreciated.

</details>


# 答案1
**得分**: 1

The `@discord.ui.button` 装饰器允许您创建一个按钮,将其关联到一个 `callback` 并以实际方式将其添加到视图中,但当您对这些按钮有可变参数时,我建议您手动创建和添加这些按钮。例如:

```py
class OptionButton(discord.ui.Button):
    def __init__(self, option: str):
        super().__init__(label=option, style=discord.ButtonStyle.blurple)

    async def callback(self, interaction: discord.Interaction):
        if self.label == self.view.answer:
            await interaction.response.send_message("正确答案!")
        else:
            await interaction.response.send_message("错误答案!")


class QuestionView(discord.ui.View):
    def __init__(self, options: list[str], answer: str):
        self.answer = answer
        for op in options:
            self.add_item(OptionButton(op))
        super().__init__()

count = 0

@bot.command()
async def test(ctx):
    global count

    with open("temp.txt", "r") as fp:
        lines = fp.read().splitlines()
    question = json.loads(lines[count])
    await ctx.send(
        content=question["question"],
        view=QuestionView(question["options"], question["answer"])
    )
    count += 1

请注意,我访问了 questionoptionsanswer 键。您的字典没有这些键,但我认为这是存储问题数据的最佳方式。

英文:

The @discord.ui.button decorator allows you to create a button, relate it to a callback and add it to a view in a practical way, but when you have variable parameters for these buttons, I suggest that you create and add the buttons manually. For example:

class OptionButton(discord.ui.Button):
    def __init__(self, option: str):
        super().__init__(label=option, style=discord.ButtonStyle.blurple)

    async def callback(self, interaction: discord.Interaction):
        if self.label == self.view.answer:
            await interaction.response.send_message(&quot;Right answer!&quot;)
        else:
            await interaction.response.send_message(&quot;Wrong answer!&quot;)


class QuestionView(discord.ui.View):
    def __init__(self, options: list[str], answer: str):
        self.answer = answer
        for op in options:
            self.add_item(OptionButton(op))
        super().__init__()


count = 0


@bot.command()
async def test(ctx):
    global count
    
    with open(&quot;temp.txt&quot;, &quot;r&quot;) as fp:
        lines = fp.read().splitlines()
    question = json.loads(lines[count])
    await ctx.send(
        content=question[&quot;question&quot;],
        view=QuestionView(question[&quot;options&quot;], question[&quot;answer&quot;])
    )
    count += 1

> Note that I'm accessing the question, options and answer keys. Your dictionary doesn't have these keys, but I think this would be the best way to store question data.

huangapple
  • 本文由 发表于 2023年4月17日 20:17:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定