Telegram bot html table

Как отправить таблицы с помощью Telegram Bot API?

Я нашел эту библиотеку — TableJs — которая решает эту проблему. Отлично работает в клиентах для настольных ПК, однако клиенты Android не отображали его должным образом.

У меня была та же проблема на Android, но я исправил ее, переопределив свойство config.border и используя более простой набор символов.

```| Symbol | Price | Change | |--------|-------|--------| | ABC | 20.85 | 1.626 | | DEF | 78.95 | 0.099 | | GHI | 23.45 | 0.192 | | JKL | 98.85 | 0.292 |``` 

Установите для параметра Telegram API parse_mode значение HTML . и оберните сообщение в , но помните, что API Telegram не поддерживает вложенные теги.

 
| Tables | Are | Cool | |----------|:-------------:|------:| | col 1 is | left-aligned | $1600 | | col 2 is | centered | $12 | | col 3 is | right-aligned | $1 |

Результат в мессенджере Telegram:

ScreenShot from telegram bot

Обновлено. Как преобразовать таблицы на картинке

Будет проблема на маленьких экранах смартфонов. Так что этот метод не годится. Единственный вариант — преобразовать таблицы на картинке и отправить:

  1. Или вы можете преобразовать HTML в изображение, используя браузер без заголовка на вашем сервере.
  2. Или вы можете преобразовать HTML в изображение, используя здесь внешние службы API
  3. Или вы можете преобразовать HTML в изображение более сложным способом: php GD

Как я могу преобразовать фреймворк pandas в этот формат html? Я пробовал df.to_html (), но это не сработало.

Кундан, я не знаю фреймворка pandas для Python. Но я знаю, что слишком сложно преобразовать любой HTML в формат RTF для сообщения Telegram. Вам следует использовать службу Telegram, например, просматривать статьи в формате HTML telegram.org/blog/instant-view в ваш проект

Вы можете использовать разметку HTML или Markdown , чтобы отправить что-то вроде в HTML. Так же, как в этом примере.

Импортируйте библиотеку «prettytable» в Python для форматирования таблицы:

import prettytable as pt from telegram import ParseMode from telegram.ext import CallbackContext, Updater def send_table(update: Updater, context: CallbackContext): table = pt.PrettyTable(['Symbol', 'Price', 'Change']) table.align['Symbol'] = 'l' table.align['Price'] = 'r' table.align['Change'] = 'r' data = [ ('ABC', 20.85, 1.626), ('DEF', 78.95, 0.099), ('GHI', 23.45, 0.192), ('JKL', 98.85, 0.292), ] for symbol, price, change in data: table.add_row([symbol, f'', f'']) update.message.reply_text(f' 
', parse_mode=ParseMode.HTML) # or use markdown update.message.reply_text(f'``````', parse_mode=ParseMode.MARKDOWN_V2) 

Вы получите сообщение вроде:

+--------+-------+--------+ | Symbol | Price | Change | +--------+-------+--------+ | ABC | 20.85 | 1.626 | | DEF | 78.95 | 0.099 | | GHI | 23.45 | 0.192 | | JKL | 98.85 | 0.292 | +--------+-------+--------+ 

Форматирование текста как "Моноширинный" тоже работает

Я написал код для создания html-таблицы Telegram из массива строк.

Просто создайте массив со строками с данными столбцов, разделенными ";" и этот код выведет готовую таблицу Telegram.

Наслаждайтесь, разберитесь с параметрами 🙂

Вы должны использовать "parse_mode" = "html" при отправке сообщения в Telegram Api.

public string BuildTelegramTable( List table_lines, string tableColumnSeparator = "|", char inputArraySeparator = ';', int maxColumnWidth = 0, bool fixedColumnWidth = false, bool autoColumnWidth = false, int minimumColumnWidth = 4, int columnPadRight = 0, int columnPadLeft = 0, bool beginEndBorders = true) < var prereadyTable = new List() < "
" >; var columnsWidth = new List(); var firstLine = table_lines[0]; var lineVector = firstLine.Split(inputArraySeparator); if (fixedColumnWidth && maxColumnWidth == 0) throw new ArgumentException("For fixedColumnWidth usage must set maxColumnWidth > 0"); else if (fixedColumnWidth && maxColumnWidth > 0) < for(var x=0;xelse < for(var x=0;xcolumnFullLength = line.Split(inputArraySeparator)[x].Length > columnFullLength ? line.Split(inputArraySeparator)[x].Length : columnFullLength); columnFullLength = columnFullLength < minimumColumnWidth ? minimumColumnWidth : columnFullLength; var columnWidth = columnFullLength + columnPadRight + columnPadLeft; if (maxColumnWidth >0 && columnWidth > maxColumnWidth) columnWidth = maxColumnWidth; columnsWidth.Add(columnWidth); > > foreach(var line in table_lines) < lineVector = line.Split(inputArraySeparator); var fullLine = new string[lineVector.Length+(beginEndBorders ? 2 : 0)]; if (beginEndBorders) fullLine[0] = ""; for(var x=0;xdataLength ? dataLength : columnSizeWithoutTrimSize; var columnData = clearedData.Substring(0,dataCharsToRead); columnData = columnData.PadRight(columnData.Length + columnPadRight); columnData = columnData.PadLeft(columnData.Length + columnPadLeft); var column = columnData.PadRight(columnWidth); fullLine[x+(beginEndBorders ? 1 : 0)] = column; > if (beginEndBorders) fullLine[fullLine.Length - 1] = ""; prereadyTable.Add(string.Join(tableColumnSeparator,fullLine)); > prereadyTable.Add("

"); return string.Join("\r\n",prereadyTable); >

Источник

Telegram bot html table

I have a question regarding posting output/results/info into Telegram that I cannot find any relevant examples over AHK. I can only manage to produce one single sentence output without any format via the Telegram URL.

If gregster have any experience in deal these complex output to Telegram, a tip of how to achieve it will be super great!

Type 01 - Complex Table Output Format

Type 02 - Iterative Output Format with multiple lines (and formatting like Bold/Italic) 01.png (370.89 KiB) Viewed 11916 times

Last edited by gregster on 30 Aug 2021, 02:52, edited 1 time in total.
Reason: Topic was split from unrelated topic.

Re: Telegram Bot API - How to format messages ?

I'll have to look into it at the weekend.
I think I have experimented with the options, but I'll have to refresh my mind.

Re: Telegram Bot API - How to format messages ?

Re: Telegram Bot API - How to format messages ?

This is what I managed to achieve so far, which looks pretty close to your pictures.

One thing seems clear, tables are not really supported (afaics). Probably, you'll have to count characters and use the fixed-width mode, in order to get something table-like like below and in your pictures (or upload a picture of a table instead ?!)
Also, escaping certain characters in the right way seems crucial. To do that, you'll have to arrange with both Telegram's and AHK's escape preferences.

Screenshot with the Telegram Desktop App:

I assume your pictures were also taken in the Desktop App? On my mobile and in the browser app, it doesn't look as nice - especially the table is broken; the speech bubbles are just not wide enough for this table size. Generally, you can't choose any colors yourself, afaik.

* Telegram Bot API formatting options for SendMessage() : https://core.telegram.org/bots/api#formatting-options
(In the following, as far as possible, I'll use the MarkdownV2 style, but afaics there are more ways to do this.)
* AHK continuation sections (see method #2): https://www.autohotkey.com/docs/Scripts.htm#continuation
* AHK escape sequences: https://www.autohotkey.com/docs/misc/EscapeChar.htm
* URL Encoding Reference: https://www.w3schools.com/tags/ref_urlencode.ASP (in a few cases, like the + sign, this can be helpful)

Example code which should create the messages above (well, tables might not work as intended, depending on your Telegram client):

; add your credentials here: chatid := botToken := "" ; different formatting options, using MarkdownV2 format text := " ( *bold text* \* text with escaped characters \%2b \(\>\~\); escape character is \\ \* _italic text_ __underline__ ~strikethrough~ 😁😎✔❗🔼⤴🔺☎📊📈📉 ~__*_bold italic, underline and strikethrough_*__~ ``inline fixed-width code`` [inline URL](http://www.example.com/) `````` ; pre-formatted fixed-width code block MsgBox, 4, , Do you want to continue? (Press YES or NO) IfMsgBox No return `````` )" ; msgbox % text param := "chat_id=" chatid "&text=" text "&parse_mode=MarkdownV2" str := "https://api.telegram.org/bot" botToken "/sendmessage?" url_tovar(str, param) ; table output text := "*`nDaily Profit over the last 7 days:*" text .= "```````nDay" multi("`t", 9) "Profit BTC" multi("`t", 6) "Profit USD" multi("`t", 4) "Trades``````" text .= "```````n" multi("-", 10) " " multi("-", 14) " " multi("-", 12) " " multi("-", 9) "``````" loop 7 text .= "```````n2019-09-" Format("", 15-A_Index) " 0.00000000 BTC 0.000 USD 0 trade``````" param := "chat_id=" chatid "&text=" text "&parse_mode=MarkdownV2" ; HTML" url_tovar(str, param) ; iterative output obj := [, IOTA: >], text := "" for idx, item in obj for curr, data in item < text .= "*" curr "*`n" text .= "```````nAvailable: " data.avail "`n" text .= "Balance: " data.balance "`n``````" >param := "chat_id=" chatid "&text=" text "&parse_mode=MarkdownV2" url_tovar(str, param) ; add custom keyboard keyb= ( <"keyboard":[ ["⚽ Command1", "🎃 Command2"], ["‼ Command3", "🔼 Command4"] ], "resize_keyboard" : true >) param := "text=Keyboard added&chat_id=" chatID "&reply_markup=" keyb "&parse_mode=MarkdownV2" str := "https://api.telegram.org/bot" botToken "/sendmessage?" url_tovar(str, param) return ; ------------------------------- Multi(char, freq) < loop % freq str .= char return str >url_tovar(URL, param) < WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1") WebRequest.Open("POST", URL) WebRequest.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded") WebRequest.Send(param) res := WebRequest.ResponseText return res >

(save your script in UTF-8 with BOM encoding)

While escaping with \ seemed to work for many of the characters mentioned in the Telegram docs, it didn't work for the plus sign + . I had to resort to its url encoding %2b (plus a leading \ to escape the % ).

Tables don't seem to be supported natively. The fixed-width formatting should help a lot. If your values always have the same width, it will be easier - otherwise you will to have to count characters to be able to pad the separate values for perfect alignment. There is a small padding example with Format() in the Date column of the table code above.
It looks like it doesn't matter if you use spaces or tabs ( `t ) for spacing, Telegram will only use spaces anyway.

This was mainly for testing. There are probably some other ways to get the same results.
Of course, one could think about writing some helper functions, especially for adding escape sequences and creating tables

Please have a look at the code and the links about escaping, and feel free to ask any question you have about it!

PS: The MessageEntity parameter of SendText() offers a few additional special entities like phone numbers, hash tags, mentions, and so on. but I haven't tried it yet.

PPS: I will split these Telegram API-related posts form the Binance API topic, and create a separate topic for it.

Источник

Читайте также:  Python postgresql insert data
Оцените статью