Good day. To create a bot in Telegram I use the TeleBot library. The task is as follows: the question is asked, the user answers. How to get the string of this answer? As I understand it, Telegram sends this message in the form of JSON'a. This is what produces when I write print(message) . How to isolate the text from here? Part of the issue cut, but I think the essence is clear.

 {'photo': None, 'location': None, 'pinned_message': None, 'entities': None, 'migrate_from_chat_id': None, 'document': None, 'date': 1480364732, 'video': None, 'caption': None, 'new_chat_title': None, 'content_type': 'text', 'forward_from': None, 'audio': None, 'text': 'NEED_TEXT_HERE', 'venue': None, 'message_id': 240, 'reply_to_message': None} 

I tried to decode it through the json library:

 with open(message, "r") as file: activity = json.load(file) print(activity.get("text")) 

Gives an error message:

File "C: /TelegramBot/bot.py", line 46, in set_activity with open (message, "r") as file:

TypeError: invalid file: <telebot.types.Message object at 0x00000208F3225FD0>

I try directly:

 activity = json.load(message) 

File "C: /TelegramBot/bot.py", line 46, in set_activity activity = json.load (message)

File "C: \ Users \ FLEX \ Anaconda3 \ lib \ json__init __. Py", line 265, in load return loads (fp.read (),

AttributeError: 'Message' object has no attribute 'read'

How to get text from Message type?

Thank you in advance.

    1 answer 1

    According to your explanations, I realized that the message variable contains a JSON string, i.e. answer. Why are you trying to open it as a file? with open(message, "r") as file .

    To decode JSON enough of this: activity = json.loads(message) . Attention: json.loads , and you use load , that's an error.

    json.load accepts a file-like object that has a read() method; it is not suitable for reading a string.

    • @ Nick16, you are bold, not loads , but loads . - neluzhin
    • Yes, corrected, thanks. True, another problem popped up, the error JSON object must be str, not 'Message'. Those. I was wrong about json'a? Then what could be what print (message) issued? If perceived as a dictionary ie activity = first_message.get ("text") Pops up AttributeError: 'Message' object has no attribute 'get' - Nick16
    • @ Nick16, but did you try to contact the keys directly? message["text"] - Klym 9:39
    • @Klym Yes, gives AttributeError: 'Message' object has no attribute 'get' - Nick16
    • @ Nick16, then try to explicitly bring it to a string, and then try to deserialize: activity = json.loads(str(message)) - Klym