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
|
#!/bin/python
# This is based on
# https://github.com/python-telegram-bot/python-telegram-bot (GPLv3 License)
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import config
def _onStart(bot, update):
if config.CHAT_ID != -1:
bot.send_message(chat_id=update.message.chat_id,
text="Sod off, this is a private bot.")
else:
bot.send_message(chat_id=update.message.chat_id,
text="Your CHAT_ID is %i. Add this to your config file."
% update.message.chat_id)
class TGBot():
def __init__(self):
self._updater = Updater(token=config.API_TOKEN)
self._dispatcher = self._updater.dispatcher
self._dispatcher.add_handler(CommandHandler('start', _onStart))
self._dispatcher.add_handler(MessageHandler(Filters.text, self._onText))
self.texthandlers = []
def run(self):
self._updater.start_polling()
def stop(self):
self._updater.stop()
print("Telegram Bot shut down.")
def _onText(self, bot, update):
chat_id = update.message.chat_id
if chat_id != config.CHAT_ID:
return
for handler in self.texthandlers:
handler(update.message.text)
def send(self, text):
self._updater.bot.send_message(
chat_id=config.CHAT_ID,
text=text,
parse_mode=telegram.ParseMode.MARKDOWN
)
def addCommand(self, command, handler):
# Wrap the handler to include a CHAT_ID check
self._dispatcher.add_handler(CommandHandler(command,
lambda bot, update: self._commandWrapper(handler, bot, update)))
def _commandWrapper(self, handler, bot, update):
chat_id = update.message.chat_id
if chat_id != config.CHAT_ID:
return
else:
return handler(bot, update)
if __name__ == "__main__":
#logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
bot = TGBot()
bot.run()
|