Skip to content

Commit

Permalink
builtin webserver to close #6
Browse files Browse the repository at this point in the history
  • Loading branch information
fopina committed Jul 29, 2015
1 parent dd26410 commit d752aab
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 18 deletions.
19 changes: 12 additions & 7 deletions tgbot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ def build_parser():
parser.add_argument('--listcommands', '-l', dest='list', action='store_const',
const=True, default=False,
help='plugin method to be used for non-command messages (ex: plugins.simsimi.SimsimiPlugin.simsimi)')
parser.add_argument('--webhook', '-w', dest='webhook', nargs=2, metavar=('hook_url', 'port'),
help='use webhooks (instead of polling) - requires bottle')
return parser


def import_class(cl):
d = cl.rfind(".")
classname = cl[d + 1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
class_name = cl[d + 1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [class_name])
return getattr(m, class_name)


def main():
Expand Down Expand Up @@ -53,12 +55,15 @@ def main():

if args.list:
tg.print_commands()
else:
if args.token is None:
parser.error('--token is required')
return

if args.token is None:
parser.error('--token is required')

if args.token is not None:
if args.webhook is None:
tg.run()
else:
tg.run_web(args.webhook[0], host='0.0.0.0', port=int(args.webhook[1]))


if __name__ == '__main__':
Expand Down
5 changes: 4 additions & 1 deletion tgbot/pluginbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ def is_expected(self, bot, message):
msg = None
if message.reply_to_message is not None:
try:
msg = models.Message.get(models.Message.reply_id == message.reply_to_message.message_id)
msg = models.Message.get(
models.Message.reply_id == message.reply_to_message.message_id,
models.Message.reply_plugin == self.key_name,
)
except models.Message.DoesNotExist:
return False

Expand Down
38 changes: 28 additions & 10 deletions tgbot/tgbot.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
from time import sleep
from twx.botapi import TelegramBot
from twx.botapi import TelegramBot, Error
from . import models
from .pluginbase import TGPluginBase
from playhouse.db_url import connect


class TGBot(object):
def __init__(self, token, polling_time=2, plugins=[], no_command=None, db_url=None):
def __init__(self, token, plugins=[], no_command=None, db_url=None):
self._token = token
self.tg = TelegramBot(token)
self._last_id = None
self.cmds = {}
self._polling_time = polling_time
self._no_cmd = no_command
self._msgs = {}
self._plugins = plugins
Expand Down Expand Up @@ -65,14 +63,29 @@ def process_update(self, update):
def setup_db(self):
models.create_tables(self.db)

def run(self):
def run(self, polling_time=2):
from time import sleep
# make sure all webhooks are disabled
self.tg.set_webhook().wait()

while True:
ups = self.tg.get_updates(offset=self._last_id).wait()
for up in ups:
self.process_update(up)
self._last_id = up.update_id + 1
if isinstance(ups, Error):
print 'Error: ', ups
else:
for up in ups:
self.process_update(up)
self._last_id = up.update_id + 1

sleep(polling_time)

sleep(self._polling_time)
def run_web(self, hook_url, **kwargs):
from . import webserver
url = hook_url
if url[-1] != '/':
url += '/'
self.tg.set_webhook(url + 'update/' + self._token)
webserver.run_server(self, **kwargs)

def list_commands(self):
out = []
Expand All @@ -95,4 +108,9 @@ def process(self, cmd, text, message):
if spl > 0:
cmd = cmd[:spl]
if cmd in self.cmds:
self.cmds[cmd][0](self, message, text)
try:
self.cmds[cmd][0](self, message, text)
except:
import traceback
traceback.print_exc()
self.tg.send_message(message.chat.id, 'some error occurred... (logged and reported)', reply_to_message_id=message.message_id)
23 changes: 23 additions & 0 deletions tgbot/webserver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from bottle import route, run, request, abort
from twx.botapi import Update

tg_bot = None


@route('/ping/')
def ping():
return '<b>Pong!</b>'


@route('/update/<token>', method='POST')
def test(token):
if token != tg_bot._token:
abort(404, 'Not found: \'/update/%s\'' % token)
tg_bot.process_update(Update.from_dict(request.json))
return None


def run_server(bot, **kwargs):
global tg_bot
tg_bot = bot
run(**kwargs)

0 comments on commit d752aab

Please sign in to comment.