Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Slack App/Bot post a code block (Python)

In Slack you're able to post as a user in a code block like in Stackoverflow

like so

As a posting user, you're able to do this by typing "```" it then changes your input box to one formatted for code.

I need to get my Slack App/Bot to post a Tabluate Table as a code block so the formatting stays consistent with my Python output. At the moment, my code looks like this:

client.chat_postMessage(channel="#google-analytics-test",text="```" + table)

This simply posts the table in a text format with "```" added onto the start of it.

This is what comes from the bot:

This is what comes from the bot

How it should look coming from the user:

How it should look coming from the user

Any help on this would be greatly appreciated, any alternative methods to get the Tabulate Table being posted by the bot in the right format would also be very welcomed!

like image 824
James Gove Avatar asked Mar 08 '26 08:03

James Gove


2 Answers

You also need "```" after the table and both should be in a separate line. This should do it:

client.chat_postMessage(channel="#google-analytics-test",text="```\n" + table + "\n```")

Note the added newlines "\n".

like image 120
Florian Lauck Avatar answered Mar 11 '26 01:03

Florian Lauck


Make sure that chat_postMessage isn't splitting your text into separate messages -- happened to me at ~25 lines.

Docs are a bit vague on expected behavior: https://api.slack.com/methods/chat.postMessage#truncating

For best results, limit the number of characters in the text field to 4,000 characters. Ideally, messages should be short and human-readable. Slack will truncate messages containing more than 40,000 characters. If you need to post longer messages, please consider uploading a snippet instead.

like image 28
William Luxion Avatar answered Mar 10 '26 23:03

William Luxion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!