#  Copyright 2017 Christoph Mende
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import shelve
import sys
import time

import telepot
from telepot.loop import MessageLoop

import plugin_loader

commands = {}

def load_users():
    try:
        return d['users']
    except KeyError:
        return {}

def load_plugins():
    for i in plugin_loader.get_plugins():
        print('Loading plugin ' + i['name'])
        plugin = plugin_loader.load_plugin(i)
        commands.update(plugin.commands)

def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    # reject non-text messages
    if content_type != 'text':
        return

    # split message in command (first word) and args (rest)
    argv = msg['text'].strip().split(' ', 1)
    command = argv[0].lower()
    args = None
    if len(argv) == 2:
        args = argv[1]

    # reject non-commands
    if not command.startswith('/'):
        return

    # strip / from command
    command = command[1:]

    # strip username from command
    if command.endswith('@'+username):
        command = command[:-len(username)-1]

    # search for plugin handling command
    for c in commands:
        if c != command:
            continue

        # found it => look up user
        uid = msg['from']['id']
        user = users.setdefault(uid, msg['from'])

        retval = commands[c](user, args)
        bot.sendMessage(chat_id, retval)

def cleanup():
    d['users'] = users
    d.close()

if len(sys.argv) < 2:
    sys.exit('Usage: %s <telegram api token>' % sys.argv[0])

d = shelve.open('foob0t.users')
bot = telepot.Bot(sys.argv[1])
users = load_users()
load_plugins()
username = bot.getMe()['username']
MessageLoop(bot, handle).run_as_thread()

while 1:
    try:
        time.sleep(10)
    except KeyboardInterrupt:
        cleanup()
        sys.exit()

@@ -583,16 +583,46 @@
 cense.%0A%0A
+from functools import partial%0A
 import s
@@ -730,23 +730,8 @@
 er%0A%0A
-commands = %7B%7D%0A%0A
 def 
@@ -741,16 +741,17 @@
 d_users(
+d
 ):%0A    t
@@ -836,24 +836,42 @@
 _plugins():%0A
+    commands = %7B%7D%0A
     for i in
@@ -1036,20 +1036,62 @@
 ds)%0A
-%0Adef handle(
+    return commands%0A%0Adef handle(users, commands, bot, 
 msg)
@@ -1634,24 +1634,63 @@
 rom command%0A
+    username = bot.getMe()%5B'username'%5D%0A
     if comma
@@ -2086,16 +2086,24 @@
 cleanup(
+d, users
 ):%0A    d
@@ -2139,92 +2139,30 @@
 ()%0A%0A
-if len(sys.argv) %3C 2:%0A    sys.exit('Usage: %25s %3Ctelegram api token%3E' %25 sys.argv%5B0%5D)%0A%0A
+def start(token):%0A    
 d = 
@@ -2193,39 +2193,12 @@
 s')%0A
-bot = telepot.Bot(sys.argv%5B1%5D)%0A
+    
 user
@@ -2216,60 +2216,128 @@
 ers(
+d
 )%0A
-load_plugins()%0Ausername = bot.getMe()%5B'username'%5D%0A
+%0A    commands = load_plugins()%0A%0A    bot = telepot.Bot(token)%0A    handler = partial(handle, users, commands, bot)%0A    
 Mess
@@ -2355,16 +2355,17 @@
 , handle
+r
 ).run_as
@@ -2375,16 +2375,20 @@
 read()%0A%0A
+    
 while 1:
@@ -2388,29 +2388,37 @@
 hile 1:%0A    
+ 
+   
 try:%0A
+    
         time
@@ -2428,16 +2428,20 @@
 eep(10)%0A
+    
     exce
@@ -2470,24 +2470,28 @@
         
+    
 cleanup(
 )%0A      
@@ -2482,18 +2482,30 @@
 cleanup(
-)%0A
+d, users)%0A    
         
@@ -2515,8 +2515,113 @@
 .exit()%0A
+%0A%0Aif len(sys.argv) %3C 2:%0A    sys.exit('Usage: %25s %3Ctelegram api token%3E' %25 sys.argv%5B0%5D)%0A%0Astart(sys.argv%5B1%5D)%0A

Remove code from global scope