如何在Rasa聊天机器人中获取最新机器人回复?已知用户输入获取语法
Hey there! Glad you asked this—fetching the latest bot response is a common need when building custom logic in Rasa, and it's a bit different from grabbing the user's input with tracker.latest_message['text']. Let's break it down clearly:
The Core Approach: Check BotUttered Events
Rasa logs every part of the conversation in the tracker, and bot replies are stored as BotUttered events. To get the most recent one, you can loop backward through the tracker's events to find the last matching entry.
Here's a reusable function you can drop right into your custom actions:
from rasa_sdk.events import BotUttered def get_latest_bot_reply(tracker): # Iterate through events in reverse to find the newest bot message for event in reversed(tracker.events): if isinstance(event, BotUttered): return event.text # Returns the actual text of the bot's reply return None # Return None if no bot responses exist yet
Need More Than Just Text?
The BotUttered event holds extra data beyond just the reply text. If you need attachments, buttons, or custom metadata, you can access these properties too:
event.attachment: For media like images or filesevent.buttons: For quick reply buttons included in the responseevent.custom: For any custom metadata you added to the bot's reply
Quick Tip for Immediate Responses
If you're trying to access a reply you just sent in the same custom action, you could reference the response template directly (if you used one). But the BotUttered method is more reliable—it works no matter where the reply came from (template, custom action, etc.).
内容的提问来源于stack exchange,提问作者youssef mellah

