0

I am building a GroupMe chatbot--programmed in python 3--that runs on Heroku, with a Gunicorn framework, and with Flask on top of that.

Currently I am working on message statistics (who sent the most messages, what time of the day is the chat most active, etc). I would like to start simple by counting the number of messages that have been sent in the group chats since the initiation of the bot. However, what I thought would be a simple solution has brought on an error. Below is my basic code.

#~~~~~~~~~~~~~~~ Package imports.
import os
import sys
import json
from flask import Flask, request
import requests
from random import randint
import linecache
import datetime
import wget
import time
app = Flask(__name__)

message_count = 0 

#~~~~~~~~~~~~~~~ Endpoint for GroupMe messages.
@app.route('/', methods=['POST'])
def webhook():

        message_count += 1 
        if message_count > 9:
            post_message('The Talker', "We've already reached 10 messages! Since my last update, that is.", '')

    return "ok", 200

The bot crashes with this error :

 "UnboundLocalError: local variable 'message_count' referenced before assignment"

Now, I will fully admit that I am neither experienced in python, nor Heroku/Flask. If you could help me, with what I assume to be a variable scope problem, I would greatly appreciate it.

snatchysquid
  • 1,120
  • 4
  • 21
Strat5
  • 13
  • 1
  • 6
  • Put `global message_count` at the top of your function to be explicit that it should be referring to the module-level variable. (Or, better, make `webhook` a `__call__()`-able class, and make `message_count` an instance variable on it, instead of using module-level variables at all). – Charles Duffy Jun 03 '20 at 17:43
  • 1
    @PrateekDewan, well, the problem with doing that naively is that they want it to be persisted across multiple invocations. – Charles Duffy Jun 03 '20 at 17:44

0 Answers0