Created
April 30, 2021 03:28
-
-
Save frostming/08a3db1bce709ffa2dd3cf32bab2422e to your computer and use it in GitHub Desktop.
Cusdis Telegram Bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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