Skip to content

Instantly share code, notes, and snippets.

@leduyquang753
Created February 2, 2022 05:57
Show Gist options
  • Save leduyquang753/8f8a7c8abfac413236f363dff2182ea9 to your computer and use it in GitHub Desktop.
Save leduyquang753/8f8a7c8abfac413236f363dff2182ea9 to your computer and use it in GitHub Desktop.
Windows terminal output converter into Discord's ANSI code block.
# Terminal output converter into Discord's ANSI code block.
# Targeted at Windows terminal. Enable HTML text format when copying.
from bs4 import BeautifulSoup as BS
import cssutils as CSS
import win32clipboard as Clipboard
# Map the colors of your scheme to the standard 16 colors supported by the ANSI
# code block.
colorMap = {
"282c34": "30",
"e06c75": "31",
"98c379": "32",
"e5c07b": "33",
"61afef": "34",
"c678dd": "35",
"56b6c2": "36",
"ffffff": "39",
"666666": "1;30",
"fd8d95": "1;31",
"abfd70": "1;32",
"feda98": "1;33",
"92ceff": "1;34",
"e9a2ff": "1;35",
"70eefe": "1;36"
}
Clipboard.OpenClipboard()
string = Clipboard.GetClipboardData(
Clipboard.RegisterClipboardFormat("HTML Format")
).decode("UTF-8")
elements = BS(string[
string.index("<!--StartFragment -->") + len("<!--StartFragment -->")
: string.index("<!--EndFragment -->")
], features="html5lib").body.div.children
string = "```ansi\n"
for element in elements:
color = (
CSS.parseStyle(element["style"])
.getProperty("color").propertyValue[0]
)
string += (
"\x1B[0m\x1B["
+ colorMap.get(
hex(color.red<<16 | color.green<<8 | color.blue)[2:],
"39"
)
+ "m"
)
for subElement in element.children:
string += '\n' if subElement.name == "br" else subElement.string
Clipboard.EmptyClipboard()
Clipboard.SetClipboardText(string + "\n```")
Clipboard.CloseClipboard()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment