def main(): """ Run the bot in perpetuity """ try: BOT_TOKEN = os.environ["BOT_TOKEN"] except KeyError: logging.error("Bot credentials not found in environment") bot = telegram.Bot(BOT_TOKEN) # Do a data refresh every time bot restarts read_status_logs() update_id = 0 # Try creating and analytics object try: lytics = Analytics() except Exception as e: logging.error(f"Analytics engine couldn't start : {e}") lytics = None while True: # Send scheduled message if it has been more than specified time interval with open("metadata.json", "r") as f: meta = json.load(f) try: scheduled_sent_time = datetime.strptime( meta["scheduled_sent_time"], "%Y-%m-%d %H:%M:%S%z") logging.debug( f"Last scheduled sent : {meta['scheduled_sent_time']}") except KeyError: scheduled_sent_time = datetime.strptime( "1900-01-01 00:00:00+05:30", "%Y-%m-%d %H:%M:%S%z") time_now = datetime.now(IST) if (time_now - scheduled_sent_time) > timedelta(minutes=SCHEDULE_MSG_MIN): send_to_channel(bot) logging.info("Sent scheduled message to channel") meta["scheduled_sent_time"] = time_now.strftime( "%Y-%m-%d %H:%M:%S%z") with open("metadata.json", "w") as f: json.dump(meta, f, indent=4) try: for update in bot.get_updates(offset=update_id, timeout=10): update_id = update.update_id + 1 logging.info(f"Update ID:{update_id}") entry(bot, update) # Try logging to Usage Log if lytics: try: timestamp = datetime.now(IST).strftime( "%Y-%m-%d %H:%M:%S%z") update_id = update_id try: tg_id = update["message"]["chat"]["id"] except TypeError: tg_id = "" try: tg_username = update["message"]["chat"]["username"] except TypeError: tg_username = "" try: tg_firstname = update["message"]["chat"][ "first_name"] except TypeError: tg_firstname = "" try: tg_lastname = update["message"]["chat"][ "last_name"] except TypeError: tg_lastname = "" try: text = update["message"]["text"] except TypeError: text = "" row = [[ timestamp, update_id, tg_id, tg_username, tg_firstname, tg_lastname, text, ]] logging.info(row) lytics.append_rows(row) except Exception as e: logging.error(f"Analytics post failed : {e}") except NetworkError: sleep(1) except Unauthorized: logging.error("User has blocked the bot") update_id = update_id + 1