Skip to content

Instantly share code, notes, and snippets.

@frostming

frostming/napkin.py

Created Apr 30, 2021
Embed
What would you like to do?
Cusdis Telegram Bot
from napkin import response, request
import requests
import json
TELEGRAM_BOT_TOKEN = 'xxxxxx'
TELEGRAM_CHAT_ID = 'xxxxx'
def format_message(data):
"""data example:
{
"type": "new_comment",
"data": {
"by_nickname": "xxx",
"by_email": "xxx",
"content": "xxx",
"page_id": "xxx",
"page_title": "xxx", // page title, maybe NULL
"project_title": "haha", // project title
"approve_link": "" // use this link to approve this comment without login
}
}
"""
data_type = data['type'].replace('_', ' ').capitalize()
message_tmpl = """_{data_type} on *{page_title}* on website *{project_title}*:_
```
{content}
```
by: *{by_nickname}*
"""
return message_tmpl.format(data_type=data_type, **data['data'])
def send_to_telegram(data=None):
data = data or json.loads(request.data)
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
message = format_message(data)
reply_markup = {
'inline_keyboard': [[{'text': 'Approve', 'url': data['data'].get('approve_link')}]]
}
resp = requests.post(
url,
data={
'chat_id': TELEGRAM_CHAT_ID,
'text': message,
'parse_mode': 'MarkdownV2',
'reply_markup': json.dumps(reply_markup)
}
)
return resp.json(), resp.status_code
resp, status_code = send_to_telegram()
response.status_code = status_code
response.body = resp
response.headers = {
'Content-Type': 'application/json'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment