butterrobot/butterrobot/platforms/telegram.py

69 lines
2.2 KiB
Python
Raw Normal View History

2020-04-22 21:58:06 +00:00
from datetime import datetime
import structlog
from butterrobot.platforms.base import Platform, PlatformMethods
from butterrobot.config import TELEGRAM_TOKEN, HOSTNAME
from butterrobot.lib.telegram import TelegramAPI
from butterrobot.objects import Message
logger = structlog.get_logger(__name__)
class TelegramMethods(PlatformMethods):
@classmethod
2020-10-28 10:19:30 +00:00
def send_message(self, message: Message):
2020-04-22 21:58:06 +00:00
logger.debug(
"Outgoing message", message=message.__dict__, platform=TelegramPlatform.ID
)
2020-10-28 10:19:30 +00:00
TelegramAPI.send_message(
2020-04-22 21:58:06 +00:00
chat_id=message.chat,
text=message.text,
reply_to_message_id=message.reply_to,
)
class TelegramPlatform(Platform):
ID = "telegram"
methods = TelegramMethods
@classmethod
2020-10-28 10:19:30 +00:00
def init(cls, app):
2020-04-22 21:58:06 +00:00
"""
Initializes the Telegram webhook endpoint to receive updates
"""
if not TELEGRAM_TOKEN:
logger.error("Missing token. platform not enabled.", platform=cls.ID)
return
webhook_url = f"https://{HOSTNAME}/telegram/incoming/{TELEGRAM_TOKEN}"
try:
2020-10-28 10:19:30 +00:00
TelegramAPI.set_webhook(webhook_url)
2020-04-22 21:58:06 +00:00
except TelegramAPI.TelegramError as error:
logger.error(f"Error setting Telegram webhook: {error}", platform=cls.ID)
raise Platform.PlatformInitError()
@classmethod
2020-10-28 10:19:30 +00:00
def parse_incoming_message(cls, request):
2020-04-22 21:58:06 +00:00
token = request.path.split("/")[-1]
if token != TELEGRAM_TOKEN:
raise cls.PlatformAuthError("Authentication error")
2020-10-28 10:19:30 +00:00
request_data = request.get_json()
2020-04-22 21:58:06 +00:00
logger.debug("Parsing message", data=request_data, platform=cls.ID)
if "text" in request_data["message"]:
# Ignore all messages but text messages
return Message(
id=request_data["message"]["message_id"],
date=datetime.fromtimestamp(request_data["message"]["date"]),
text=str(request_data["message"]["text"]),
2020-09-17 18:16:29 +00:00
from_bot=request_data["message"]["from"]["is_bot"],
2020-08-11 11:29:24 +00:00
author=request_data["message"]["from"]["id"],
2020-04-22 21:58:06 +00:00
chat=str(request_data["message"]["chat"]["id"]),
raw=request_data,
)