如何使用 python 在 Messenger-Dialogflow 聊天机器人中将 Mysql 查询结果作为 Excel 报告发送

How to send a Mysql query result as Excel report in Messenger-Dialogflow chatbot using python

我使用 Python 程序作为 webhook 创建了一个带有 dialogflow 的 Messenger 聊天机器人。在一个用例中:用户通过给出周数(1 week/2 周等)来请求每周报告。 Python 程序将周数作为参数并将结果以 csv 格式保存在我的本地。我想将该 csv 作为聊天机器人的附件发送给用户。

截至目前,我将 csv 文件保存在与 google 驱动器同步的本地驱动器中,并将 link 发送给用户。每次用户想要不同周的销售文件更新。但是在现实生活中,当多个用户同时请求报告时,其中一个用户得到了错误的文件(最新的任何查询 运行)。

        inte = get_parameter_from_req(req)
        week_num = round(inte)
        print(week_num)
        #cusid = pd.DataFrame([inte],columns = ['Weeks'])
        #cusid.to_csv('C:/Users/Jon/Desktop/Reporting BOT/Reporting Bot Code/num_of_weeks.csv',index = False)
        print("Inside DB Test")
        mydb = mysql.connector.connect(host="localhost",user="root",passwd="****",database = "jon_bp")
        mycursor =  mydb.cursor()
        mycursor.execute("select * from trans where t_date between curdate()-interval %s week AND curdate()",(week_num,))
        result = mycursor.fetchall()
        dataf = pd.DataFrame(result)
        dataf.columns = ['Name','Amount','t_date']
        dataf.to_csv('C:/Users/jon/Desktop/Reporting BOT/Report on cloud/Weekly Report by Bot.csv',index = False)

        response = {
            'fulfillmentText': 'Hi! Sales report for {0} weeks is ready.'.format(str(week_num)) +"\n"+ 'You can download the report from here: fix url for report',
        }

经过更多研究,我找到了共享正确文件的方法。以下是步骤:

  1. 我在文件名中附加时间戳(包括微秒) filename = 'my_file_{0}.csv'.format(datetime.now().strftime("%Y%m%d_%H%M%S%f")

  2. 这次并将此文件保存到 AWS S3 存储桶。

  3. 借助文件名创建 link,然后与用户共享。