python aiogram:转换' state' to' int'

发布于 2025-02-12 23:03:07 字数 860 浏览 1 评论 0 原文

假设我想要:
一个机器人询问用户需要多少个甜甜圈,并在响应中收到“甜甜圈”一词乘以用户输入的数字。

简单示例:

bot:您想要多少个甜甜圈?
用户: 5
bot:甜甜圈甜甜圈甜甜圈

在这里我如何看:

class how_many(StatesGroup):
   set = State()

async def doughnut(message: types.Message):
   await how_many.set.set()
   await message.reply('How many doughnuts do you want?')


async def doughnut_answer(message: types.Message, state: FSMContext):
   await message.reply("doughnut" * int(how_many.set))
   await State.finish()


def handlers(dp: Dispatcher):
   dp.register_message_handler(doughnut, commands='doughnuts', state=None)
   dp.register_message_handler(doughnut_answer, state=how_many.set)

,但我遇到了一个错误: “ int()参数必须是字符串,类似字节的对象或一个真实数字,而不是'状态'“

我如何”状态“转换为“ int”? 为此,我需要在某个地方保存值然后将其转换?还是可以使用正确的语法直接执行此操作?

Let's say I want:
A bot to ask how many doughnuts the user needs, and in response it receives the word "doughnuts" multiplied by the number entered by the user.

Simple example:

Bot: How many doughnuts do you want?
User: 5
Bot: doughnut doughnut doughnut doughnut doughnut

Here how i see it:

class how_many(StatesGroup):
   set = State()

async def doughnut(message: types.Message):
   await how_many.set.set()
   await message.reply('How many doughnuts do you want?')


async def doughnut_answer(message: types.Message, state: FSMContext):
   await message.reply("doughnut" * int(how_many.set))
   await State.finish()


def handlers(dp: Dispatcher):
   dp.register_message_handler(doughnut, commands='doughnuts', state=None)
   dp.register_message_handler(doughnut_answer, state=how_many.set)

But I am getting an error:
" int() argument must be a string, a bytes-like object or a real number, not 'State' "

How do I "state" convert to "int"?
To do this, I need to save the value somewhere and then convert it? Or can I do it directly with the correct syntax?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

数理化全能战士 2025-02-19 23:03:07

州班的样子是什么样的?我假设您将值存储在状态对象中。此外,必须实现 __ INT __ 方法,否则 int 函数不能应用于状态对象。使用此方法,您可以返回存储的值(在下面的示例中,我称之为此值数量):

class State:

    def __int__(self):
        return self.amount

int 函数仅调用类的 __ INT __ 类的方法。由于您的 how_many.set 是状态对象,因此 int 函数返回存储的值数量,

以获取有关Python魔法方法的更多信息,请参见在这里

What does the State class look like? I assume you store the value in the State object. Furthermore, the __int__ method must be implemented, otherwise the int function cannot be applied to a State object. With this method you can return the stored value (in my example below I have called this value amount):

class State:

    def __int__(self):
        return self.amount

The int function only calls the __int__ method of a class. Since your how_many.set is a State object, the int function returns the stored value amount

For more information regarding Python Magic Methods see here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文