本文介绍了将 Prettytable 的输出发送到 Telegram的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

从prettytable 导入PrettyTable

from prettytable import PrettyTable

myTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"])

# Add rows
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 %"])

这会生成一个如下所示的表格:

This produces a table which 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 %   |
+--------------+-------+---------+------------+

我想完全按照它的显示方式发送这个表格,而不改变电报消息的格式.所以我把它写到一个文本文件中:

I want to send this table exactly how it appears with no changes to the format to the telegram messages. So i write this to a text file:

table_txt = table.get_string()
with open('output.txt','w') as file:
    file.write(table_txt)

接下来我使用这个代码:

Next i use this code:

import telegram

def send_msg(text):
    token = "******************:***********"
    chat_id = "********"
    bot = telegram.Bot(token=token)
    for i in text:
        bot.sendMessage(chat_id=chat_id, text=i)
new_list = []
with open("output.txt", 'r', encoding="utf-8") as file:
     new_list = file.read()
for i in new_list:
     send_msg()

它的作用是一次发送 1 个字符的文件内容,直到您收到电报错误:

What it does is send the content of the file 1 character at a time until you get the telegram error:

RetryAfter:超出洪水控制.43.0 秒后重试

请告诉我该怎么做才能解决这个问题?

Please advise what can i do to resolve this?

推荐答案

我不是 Python 开发人员,但我认为这会奏效.

I'm not a python developer, But I think this will work.

import telegram

def send_msg(text):
    token = "******************:***********"
    chat_id = "********"
    bot = telegram.Bot(token=token)
        bot.sendMessage(chat_id=chat_id, text=text)

with open("output.txt", 'r', encoding="utf-8") as file:
     send_msg(file.read())

这篇关于将 Prettytable 的输出发送到 Telegram的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-24 15:04