Skip to content
Advertisement

How to update environment variables through python code on Heroku?

What I’m trying to do is:

  1. I’m trying to make a Telegram-bot that sends me a message when there’s a new post updated on a specific web page.
  2. I made the code and uploaded it on Heroku.
  3. The bot is set to keep starting every 10 minutes using Heroku Scheduler so that it would detect any new post updated every 10 minutes.

Now the problem is:

  1. The code is set to remember the latest post number and not to make any alarm if there’s nothing updated between the previous bot run and the current run.

  2. If the saved post number in the previous run matches the latest post number in the present run, the bot should not alarm me and keep doing the scheduled process (keep checking new posts every 10 minutes).

  3. This is what I made to make this work

    import os
    
    latest_num = os.environ.get("POST_ID")
    
    post_num = posts.find("td", {"class" : "no"}).text.strip()
    
    if latest_num != post_num :
      latest_num = post_num
      os.environ["POST_ID"] = latest_num
    
  4. I assume that if the latest post number from the previous run is saved as “POST_ID” through environment variables on Heroku, it should appear in the present run and be the value of latest_num when using os.environ to read "POST_ID" from the environment variable.

  5. But the problem is, it seems like os.environ["POST_ID"] doesn’t overwrite its value after the current run is done. Every time the Heroku scheduler starts the program, the 'latest_num' value is 0, the same as the default value of "POST_ID" on Heroku’s settings.

  6. So, even though there’s no new post, the bot keeps sending me a message because 'latest_num' doesn’t match 'post_num' all the time.

How can I fix this? Actually, I don’t know whether setting environment variables through python code is possible or not. Please tell me if there’s something better to make this work.

Advertisement

Answer

You can save those previous post id either in text file or in python variable. I prefer to save it in text file because if you restart or close your program then it forget all previous stuff but it isn’t for text file. Here’s the code: At first while saving do this:

post_num = posts.find("td", {"class" : "no"}).text.strip()
with open("pre.txt","wb") as f:
    f.write(post_num)

And now your scrape scrape second time then do this:

post_num = posts.find("td", {"class" : "no"}).text.strip()
with open("pre.txt","rb") as f:
    pre_num=f.read()
if post_num!=pre_num:
    #Do Something 
    with open("pre.txt","wb") as f:
        f.write(post_num)
else:
    #Do something
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement