python-3.x Aiogram --为精确用户设置状态

ecfdbz9o  于 2024-01-10  发布在  Python
关注(0)|答案(4)|浏览(194)

我正在用python和aigram编写一个bot。关键是管理员接受(或拒绝)用户请求。因此,当管理员点击聊天中的按钮时,我需要更改用户的状态(他的uid是已知的)。我没有找到如何在任何地方做到这一点。
我在找一个

  1. dp.set_state(uid, User.accepted))

字符串
谢谢你,谢谢

sz81bmfz

sz81bmfz1#

我有同样的问题
在基类State中找到方法set():

  1. class State:
  2. ...
  3. async def set(self):
  4. state = Dispatcher.get_current().current_state()
  5. await state.set_state(self.state)

字符串
所以我从State创建了一个新的类,并以这种方式覆盖了方法:

  1. async def set(self, user=None):
  2. """Option to set state for concrete user"""
  3. state = Dispatcher.get_current().current_state(user=user)
  4. await state.set_state(self.state)


使用方法:

  1. @dp.message_handler(state='*')
  2. async def example_handler(message: Message):
  3. await SomeStateGroup.SomeState.set(user=message.from_user.id)


如果你想要一些邮件的东西,收集用户ID和使用提示。

展开查看全部
camsedfj

camsedfj2#

  1. from aiogram.dispatcher import FSMContext
  2. @dp.message_handler(state='*')
  3. async def example_handler(message: types.Message, state: FSMContext):
  4. new_state = FSMContext(storage, chat_id, user_id)

字符串
然后set_state()set_data()new_state上。
storage是FSM存储。

3pvhb19x

3pvhb19x3#

对于新的Aiogram 3.1.0

由于Aiogram 3.1.0访问存储和上下文的方法略有不同,我想分享我的想法:

  1. from aiogram.fsm.storage.base import StorageKey
  2. from aiogram.fsm.state import State, StatesGroup
  3. from aiogram.fsm.context import FSMContext
  4. class UserState(StatesGroup):
  5. # any other states
  6. EXPIRED = State()
  7. bot = Bot("your_token", parse_mode=ParseMode.HTML)
  8. storage = MemoryStorage() # for clarity it is created explicitly
  9. dp = Dispatcher(storage=storage)
  10. # here goes the desired userId and chatId (they are same in private chat)
  11. new_user_storage_key = StorageKey(bot.id,user_id,user_id)
  12. new_user_context = FSMContext(storage=storage,key=new_user_storage_key)
  13. await new_user_context.set_state(UserState.EXPIRED) # your specified state

字符串
用户自己的存储空间(MemoryRecord)现在是通过 * ESTKey * 访问的,而不仅仅是通过user_id访问的,这就是为什么需要先创建它,然后用值(ID)填充它,然后将它传递给FSM上下文。上下文创建后,调用set_state(...)set_data(...)将专门为所需的user_id设置state/data。
实际上,不需要像前面的代码片段中所示的那样显式地创建存储,因为它将自动创建,所以您可以通过
dispatcher.storage
属性访问它,如下所示:

  1. # the same imports
  2. # the same UserState class
  3. bot = Bot("your_token", parse_mode=ParseMode.HTML)
  4. dp = Dispatcher() # we don't create storage manually this time
  5. # here goes the desired userId and chatId (they are same in private chat)
  6. new_user_storage_key = StorageKey(bot.id,user_id,user_id)
  7. new_user_context = FSMContext(storage=dp.storage,key=new_user_storage_key)
  8. await new_user_context.set_state(UserState.EXPIRED) # your specified state


希望有帮助!:)

展开查看全部
qybjjes1

qybjjes14#

state = dp.current_state(chat=chat_id,user=user_id)await state.set_state(User.accepted)

dp -Dispatcher类的一个对象chat_id - chat id,如果这是与用户的通信,则必须等于用户id User.accepted -我们希望将用户带到的状态

相关问题