# Using Azure Functions for serverless bots.
# (Thanks to twitter.com/masyan for the idea)

# By default the Azure Functions url is https://.../api/HttpTrigger for HttpTrigger type.
# In this example we will use clear webhook url without /api/ -> https://.../HttpTrigger.
# Also we set "authLevel": "anonymous".

# For HttpTrigger type set "route" and "authLevel" in functions.json
# {
#   "bindings": [
#   ...
#   "authLevel": "anonymous"
#   "route": "HttpTrigger"
#   ]
# }

# To avoid using /api/ in url set "routePrefix":"" in host.json
# {
#   ...
#   "extensions": {
#     "http": {
#       "routePrefix": ""
#     }
#   }
# }

import logging

import azure.functions as func
import telebot
from telebot import apihelper, types

logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)

# Set bot token
TOKEN = ''

# Uncomment this for using proxy for request
# PROXY = ''
# apihelper.proxy = {'https': PROXY}

# Set WEBHOOK as your Azure Functions url (https://...azurewebsites.net/HttpTrigger)
WEBHOOK = ''

bot = telebot.TeleBot(TOKEN)

@bot.message_handler(commands=['start'])
def start(message):
    bot.reply_to(message, 'Hello, ' + message.from_user.first_name)

@bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_message(message):
    bot.reply_to(message, message.text)

# To avoid "error 429 too many request" set webhook only once. Or use time.sleep(1).
def main(req: func.HttpRequest) -> func.HttpResponse:
    bot.set_webhook(url=WEBHOOK)
    request_body_dict = req.get_json()
    update = telebot.types.Update.de_json(request_body_dict)
    bot.process_new_messages([update.message])
    return func.HttpResponse(body='', status_code=200)
    
# Sometimes "requests" version is important. 
# azure-functions==1.0.4
# PySocks==1.7.1
# pyTelegramBotAPI==3.6.6
# requests==2.10.0

