Skip to content

Instantly share code, notes, and snippets.

@voskresla
Last active October 13, 2019 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voskresla/72c1e1d0f029e94bd24361175c3557ef to your computer and use it in GitHub Desktop.
Save voskresla/72c1e1d0f029e94bd24361175c3557ef to your computer and use it in GitHub Desktop.
pyTelegramBotAPI + webhooks + Azure Function
# Using Azure Functions as webhook for serverless telegram 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
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": ["get", "post"],
"route": "HttpTrigger"
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": ""
}
}
}
azure-functions==1.0.4
PySocks==1.7.1
pyTelegramBotAPI==3.6.6
requests==2.10.0
@masyanru
Copy link

нормально, чо, ваще красава!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment