# -*- coding: utf-8 -*-

import telegram
from settings import TELEGRAM_TOKEN
from pygeocoder import Geocoder
import pygeolib
from model import subscribe, unsubscribe
from utils import lat_lon_to_cell

bot = telegram.Bot(token=TELEGRAM_TOKEN)

commands = [
    '/subscribe Санкт-Петербург',
    '/unsubscribe'
]


def geo_code(address):
    try:
        business_geocoder = Geocoder(None, 'MY_API_KEY')
        results = business_geocoder.geocode(address)
        return results.latitude, results.longitude
    except pygeolib.GeocoderError:
        return None


def reply(update, message):
    bot.sendMessage(
        chat_id=update.message.chat_id,
        reply_to_message_id=update.message.message_id,
        text=message,
    )


def reply_by_chat_id(chat_id, message):
    bot.sendMessage(
        chat_id=chat_id,
        text=message,
    )


def main():
    offset = 0
    print 'Press Ctrl+C to kill...'
    while True:
        updates = bot.getUpdates(offset=offset+1)
        for update in updates:
            text = update.message.text
            text_split = text.split(' ', 1)
            command, arguments = text_split[0], None
            if len(text_split) > 1:
                arguments = text_split[1]

            if command == '/subscribe':
                geo = geo_code(arguments)
                if geo is None:
                    reply(update, "Не удалось определить координаты места")
                else:
                    geo_id = lat_lon_to_cell(geo[0], geo[1])
                    subscribe(update.message.chat_id, arguments, geo_id)
                    reply(update, "Вы подписаны и получите уведомление о сиянии в Ваше регионе как только так сразу!")

            elif command == '/unsubscribe':
                unsubscribe(update.message.chat_id)
                reply(update, "Вы успешно отписаны.")

            else:
                reply(update, "Неизвестная комманда")
            offset = update.update_id

if __name__ == '__main__':
    main()
@@ -1597,24 +1597,26 @@
 ply(update, 
+%22%22
 %22%D0%92%D1%8B %D0%BF%D0%BE%D0%B4%D0%BF%D0%B8%D1%81%D0%B0%D0%BD
@@ -1685,17 +1685,295 @@
 %D0%BA %D1%81%D1%80%D0%B0%D0%B7%D1%83!
-%22
+%0D%D0%9D%D0%B0 %D0%B2%D1%81%D1%8F%D0%BA%D0%B8%D0%B9 %D1%81%D0%BB%D1%83%D1%87%D0%B0%D0%B9 %D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D1%8C%D1%82%D0%B5, %D1%87%D1%82%D0%BE %D0%BC%D1%8B %D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D1%8C%D0%BD%D0%BE %D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B8%D0%BB%D0%B8 %D0%92%D0%B0%D1%88%D0%B5 %D0%BC%D0%B5%D1%81%D1%82%D0%BE%D0%BF%D0%BE%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5.%22%22%22)%0D                    bot.sendLocation(%0D                        chat_id=update.message.chat_id,%0D                        latitude=geo%5B0%5D,%0D                        longitude=geo%5B1%5D,%0D                    
 )%0D%0D     
@@ -2262,12 +2262,13 @@
 :%0D    main()
+%0D

attach location on map to verify that geocoder worked right