如何从Telethon的GetMessagesRequest返回结果中提取消息文本?
Hey there! Let's walk through how to pull that specific message text out—since the Telethon team noted this boils down to basic Python object handling, it's simpler than you might think.
First, let's recap what's happening: when you call client(GetMessagesRequest(...)), the response you get is a container object (usually of type messages.Messages) that holds a list of message objects in its messages attribute.
Here's a step-by-step example with code:
- First, make your request as you did before:
from telethon.tl.functions.messages import GetMessagesRequest # Assume you've already set up your client, defined your peer, and have pinnedMsgId response = client(GetMessagesRequest(peers=[your_target_peer], id=[pinnedMsgId]))
- Next, grab the actual message object from the response. Since you're requesting a single pinned message, you can access the first item in the
messageslist:
# Get the first (and only, in this case) message from the response target_msg = response.messages[0]
- Finally, extract the text. Telethon's
Messageobject stores the raw message content in themessageattribute. If you want text parsed with formatting entities (like links or bold), you can usetextinstead—but for your plain "test message test" string,messagewill work perfectly:
message_text = target_msg.message # Or, if you need parsed text: message_text = target_msg.text print(message_text) # This will output: test message test
A quick note: If you ever request multiple messages, you'd loop through response.messages to process each one individually, but since you're targeting a single pinned message, accessing the index [0] is the way to go.
内容的提问来源于stack exchange,提问作者Py_Dev

