0

I set webhook to my telegram chatbot with the help of CherryPy. And now I am trying to handle data which I receive through webhook. I found the variable in cherrypy webhook class which contains needed json data. In my code, the variable name is json_string. I need to call this variable everywhere in my python script. How I can do that? Thanks.

class WebhookServer(object):
    @cherrypy.expose
    def index(self):
        if 'content-length' in cherrypy.request.headers and \
                        'content-type' in cherrypy.request.headers and \
                        cherrypy.request.headers['content-type'] == 'application/json':
            length = int(cherrypy.request.headers['content-length'])
            json_string = cherrypy.request.body.read(length).decode("utf-8")
            update = telebot.types.Update.de_json(json_string)
            bot.process_new_updates([update])
            return ''
        else:
            raise cherrypy.HTTPError(403) 
JohnLemon
  • 147
  • 1
  • 1
  • 13

1 Answers1

1

Let's consider simplified HTTP handler where json is automatically decoded into dict by json_in Tool and the result is stored in cherrypy.request.json.

You may write some function in an external module, say utils.py, import it along with your server code and pass that data in:

==>> your_server.py <<==

from utils import process_telegram_webhook

class WebhookServer(object):
    @cherrypy.expose
    @cherrypy.tools.json_in()
    def index(self):
        req = cherrypy.request
        incoming_dict_object = req.json
        process_telegram_webhook(incoming_dict_object)
        return ''

# ...

==>> utils.py <<==

def process_telegram_webhook(data):
    # ... do smth with json data from telegram: