2017-09-05 19:50:20 +00:00
|
|
|
import telegram
|
|
|
|
from telegram.ext import CommandHandler, MessageHandler, Updater, Filters
|
|
|
|
|
|
|
|
import json
|
|
|
|
from datetime import datetime
|
|
|
|
from threading import Thread
|
|
|
|
|
|
|
|
class Module(Thread):
|
|
|
|
_name = "telegram"
|
|
|
|
|
2018-08-31 11:55:52 +00:00
|
|
|
def __init__(self, bot, events):
|
|
|
|
key = bot.config.get("telegram-api-key")
|
2017-09-05 23:17:55 +00:00
|
|
|
if not key: return
|
|
|
|
|
2018-08-31 11:55:52 +00:00
|
|
|
self.bot = bot
|
|
|
|
self.events = events
|
2017-09-05 19:50:20 +00:00
|
|
|
|
2017-09-05 23:17:55 +00:00
|
|
|
self.updater = Updater(key)
|
2017-09-05 19:50:20 +00:00
|
|
|
self.dispatcher = self.updater.dispatcher
|
|
|
|
|
|
|
|
start_handler = CommandHandler("start", self.start)
|
|
|
|
command_handler = MessageHandler(Filters.command, self.handle)
|
|
|
|
self.dispatcher.add_handler(start_handler)
|
|
|
|
self.dispatcher.add_handler(command_handler)
|
|
|
|
|
|
|
|
self.updater.start_polling()
|
2018-08-31 11:55:52 +00:00
|
|
|
events.on("signal").on("interrupt").hook(self.sigint)
|
2017-09-05 19:50:20 +00:00
|
|
|
|
|
|
|
def start(self, bot, update):
|
2018-08-31 09:51:47 +00:00
|
|
|
bot.send_message(chat_id=update.message.chat_id, text="`Dolphin, but Telegram`", parse_mode="Markdown")
|
2017-09-05 19:50:20 +00:00
|
|
|
|
|
|
|
def handle(self, bot, update):
|
|
|
|
message, text = update.message, update.message.text
|
|
|
|
text = text.replace("\r", '').replace("\n", " ")
|
|
|
|
command = text.split(" ")[0][1:]
|
|
|
|
command = command.split("@")[0]
|
|
|
|
args = text.split(" ", 1)[1:][0] if " " in text else ""
|
|
|
|
data = {
|
|
|
|
"chat_id": message.chat_id,
|
|
|
|
"message_id": message.message_id,
|
|
|
|
"line": text,
|
|
|
|
"command": command,
|
|
|
|
"args": args,
|
|
|
|
"args_split": text.split(" ")[1:],
|
|
|
|
"stdout": IOWrapper(bot, message.chat_id, message.message_id),
|
|
|
|
"stderr": IOWrapper(bot, message.chat_id, message.message_id),
|
|
|
|
"external": True,
|
2018-08-31 09:51:47 +00:00
|
|
|
}
|
2018-08-31 11:55:52 +00:00
|
|
|
self.events.on("telegram").on("command").on(command).call(**data)
|
2017-09-05 19:50:20 +00:00
|
|
|
|
|
|
|
def sigint(self, event):
|
|
|
|
self.updater.stop()
|
|
|
|
|
|
|
|
class IOWrapper:
|
|
|
|
def __init__(self, bot, chat_id, message_id):
|
|
|
|
self.bot = bot
|
|
|
|
self.chat_id = chat_id
|
|
|
|
self.message_id = message_id
|
|
|
|
def write(self, text):
|
2018-08-31 09:51:47 +00:00
|
|
|
if len(text)>4096-10:
|
2017-09-05 19:50:20 +00:00
|
|
|
text = text[:4086] + "…"
|
2018-08-31 09:51:47 +00:00
|
|
|
self.bot.send_message(chat_id=self.chat_id, text="```\n" + text + "\n```",
|
|
|
|
reply_to_message_id=self.message_id, parse_mode="Markdown")
|