-
Notifications
You must be signed in to change notification settings - Fork 0
/
codesintaxhighlightbot.py
81 lines (58 loc) · 2.3 KB
/
codesintaxhighlightbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from decouple import config
import re
import requests
TOKEN = config('TOKEN')
HCTI_API_USER_ID = config('HCTI_API_USER_ID')
HCTI_API_KEY = config('HCTI_API_KEY')
app = ApplicationBuilder().token(TOKEN).build()
langs = ['php','python', 'html', 'css']
async def helpCmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
text = """
*@CodeSintaxHightLight helps you to format messages with programming language code.*
*Usage:*
```
/format python
numbers = [1,2,3,4,5,6]
for number in numbers:
print(number)
```
"""
await update.message.reply_text(text, parse_mode='Markdown')
async def langsCmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
text = ''
for i in range(len(langs)):
text += '<b>'+str(i+1)+'.</b> '+langs[i] +'\r\n'
await update.message.reply_text(text, parse_mode='HTML')
async def formatCmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
msg = update['message']['text']
m = re.search('\\s.+\\n', msg)
lang = m.group(0).strip()
if(lang not in langs):
await update.message.reply_text("The format is not supported!")
return
code = msg.replace('/format@CodeSintaxHighLightBot '+lang+'\n', '')
code = msg.replace('/format '+lang+'\n', '')
lexer = get_lexer_by_name(lang, stripall=False)
formatter = HtmlFormatter(linenos=True)
html = highlight(code, lexer, formatter)
css = formatter.get_style_defs('.highlight')
data = {
'html': html,
'css':css
}
image = requests.post(url = "https://hcti.io/v1/image", data = data, auth=(HCTI_API_USER_ID, HCTI_API_KEY))
url = image.json()['url']
await update.message.reply_text(url)
except:
await update.message.reply_text("An error has ocurred parsing the message")
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("help", helpCmd))
app.add_handler(CommandHandler("langs", langsCmd))
app.add_handler(CommandHandler("format", formatCmd))
app.run_polling()