Skip to content

Instantly share code, notes, and snippets.

@Kylmakalle
Last active October 25, 2017 16:53
Show Gist options
  • Select an option

  • Save Kylmakalle/53fccaf25c5d76d9f97a667dc7279cef to your computer and use it in GitHub Desktop.

Select an option

Save Kylmakalle/53fccaf25c5d76d9f97a667dc7279cef to your computer and use it in GitHub Desktop.
Proxying telegram updates to local webserver using nginx
import telebot
import flask
from credentials import token, host, port, DEBUG
API_TOKEN = token
WEBHOOK_HOST = host
WEBHOOK_PORT = port
WEBHOOK_URL_BASE = "https://%s" % (WEBHOOK_HOST)
WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)
bot = telebot.AsyncTeleBot(API_TOKEN)
app = flask.Flask(__name__)
# Empty webserver index, return nothing, just http 200
@app.route('/', methods=['GET', 'HEAD'])
def index():
return ''
# Process webhook calls
@app.route('/', methods=['POST'])
def webhook():
if flask.request.headers.get('content-type') == 'application/json':
json_string = flask.request.get_data().decode('utf-8')
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return ''
else:
flask.abort(403)
### --- Bot's logic there --- ###
bot.remove_webhook()
if DEBUG:
bot.skip_pending = True
bot.polling()
else:
bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH)
# Start flask server
app.run(host='127.0.0.1', port=WEBHOOK_PORT, debug=True)
location /API_TOKEN/ {
proxy_pass http://127.0.0.1:WEBHOOK_PORT/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment