Skip to content
Advertisement

How to pass a variable to a different function (a different stage in ConversationHandler?)

So I have a bot which moves from stage to stage using the stage names as a product of return of each function. e.g.

STEP_1, STEP_2, STEP_3 = range(3)

def askforfile(update, context):
    chat_id = update.message.chat_id
    context.bot.send_message(chat_id=chat_id, text="give a file!")
    return STEP_1

def getfile(update, context):
    chat_id = update.message.chat_id
    filename = 'newfile'+str(chat_id)+ '.txt'
    f = open(filename, 'wb')
    context.bot.get_file(update.message.document.file_id).download(out=f)
    f.close()
    return STEP_2

def get_info(update, context):
    chat_id = update.message.chat_id
    info = update.message.text
    return STEP_3

def end(update, context):
    with open(filename, 'rb') as f:
       writecsv1 = some_module.some_function(filename, info)
    with open(writecsv1, 'rb') as doc:
        context.bot.send_document(chat_id=chat_id, document=doc)
    return ConversationHandler.END 

So in the end() function I need to pass the variables from functions getfile() and get_info() in the some_function. But I have no clue how to do it, because returning multiple values doesn’t work for me and even if it worked, obviously I can’t call functions.

Advertisement

Answer

You could use global variables filename and info (maybe don’t name them that) that you rewrite within your functions. Just define them with some default value above your function definitions. Right now they’re just defined locally and disappear once the function returns.

Advertisement