-
Notifications
You must be signed in to change notification settings - Fork 37
/
herokubotcp.py
73 lines (55 loc) · 2.24 KB
/
herokubotcp.py
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
69
70
71
72
73
import logging
import os
from queue import Queue
import cherrypy
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Dispatcher
class SimpleWebsite(object):
@cherrypy.expose
def index(self):
return """<H1>Welcome!</H1>"""
class BotComm(object):
exposed = True
def __init__(self, TOKEN, NAME):
super(BotComm, self).__init__()
self.TOKEN = TOKEN
self.NAME=NAME
self.bot = telegram.Bot(self.TOKEN)
try:
self.bot.setWebhook("https://{}.herokuapp.com/{}".format(self.NAME, self.TOKEN))
except:
raise RuntimeError("Failed to set the webhook")
self.update_queue = Queue()
self.dp = Dispatcher(self.bot, self.update_queue)
self.dp.add_handler(CommandHandler("start", self._start))
self.dp.add_handler(MessageHandler(Filters.text, self._echo))
self.dp.add_error_handler(self._error)
@cherrypy.tools.json_in()
def POST(self, *args, **kwargs):
update = cherrypy.request.json
update = telegram.Update.de_json(update, self.bot)
self.dp.process_update(update)
def _error(self, error):
cherrypy.log("Error occurred - {}".format(error))
def _start(self, bot, update):
update.effective_message.reply_text("Hi!")
def _echo(self, bot, update):
update.effective_message.reply_text(update.effective_message.text)
if __name__ == "__main__":
# Set these variable to the appropriate values
TOKEN = "Your token from @Botfather"
NAME = "The name of your app on Heroku"
# Port is given by Heroku
PORT = os.environ.get('PORT')
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Set up the cherrypy configuration
cherrypy.config.update({'server.socket_host': '0.0.0.0', })
cherrypy.config.update({'server.socket_port': int(PORT), })
cherrypy.tree.mount(SimpleWebsite(), "/")
cherrypy.tree.mount(BotComm(TOKEN, NAME),
"/{}".format(TOKEN),
{'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
cherrypy.engine.start()