pythontelegrampython-telegram-bot

How to send message to telegram as ```code````


Sending the output of Prettytable to Telegram

This question is a followup to an earlier question. The code which i have is this:

import telegram
from prettytable import PrettyTable

def send_msg(text):
    token = "*******:**************"
    chat_id = "***********"
    bot = telegram.Bot(token=token)
    
    bot.sendMessage(chat_id=chat_id, text=text)
        
myTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"])
  
myTable.add_row(["Leanord", "X", "B", "91.2 %"])
myTable.add_row(["Penny", "X", "C", "63.5 %"])
myTable.add_row(["Howard", "X", "A", "90.23 %"])
myTable.add_row(["Bernadette", "X", "D", "92.7 %"])
myTable.add_row(["Sheldon", "X", "A", "98.2 %"])
myTable.add_row(["Raj", "X", "B", "88.1 %"])
myTable.add_row(["Amy", "X", "B", "95.0 %"])
table_txt = myTable.get_string()
with open('output.txt','w') as file:
    file.write(table_txt)
new_list = []
with open("output.txt", 'r', encoding="utf-8") as file:
     send_msg(file.read())

The problem is that the message which is sent looks like this:

+--------------+-------+---------+------------+
| Student Name | Class | Section | Percentage |
+--------------+-------+---------+------------+
|   Leanord    |   X   |    B    |   91.2 %   |
|    Penny     |   X   |    C    |   63.5 %   |
|    Howard    |   X   |    A    |  90.23 %   |
|  Bernadette  |   X   |    D    |   92.7 %   |
|   Sheldon    |   X   |    A    |   98.2 %   |
|     Raj      |   X   |    B    |   88.1 %   |
|     Amy      |   X   |    B    |   95.0 %   |
+--------------+-------+---------+------------+

But when the message received in telegram looks like this:

enter image description here

How can i fix this? Telegram lets you send messages in code whereby i guess it would preserve the format. How can i send this message in format?


Solution

  • You have already solved it yourself: you used three backticks in the title of your question. In Markdown (including here on SO), you can put three backticks around a block of code, and that makes it use the code block formatting.

    ```
    this is inside a code block
    ```
    

    You can just add a line containing the three backticks in front and back of your text:

    backticked_text = "```\n" + text + "\n```"