pythondockercronenvironment-variablestelethon

Why am Getting a "ValueError: Your API ID or Hash cannot be empty or None" when using Telethon inside a Docker Container


I am getting a ValueError: Your API ID or Hash cannot be empty or None when i try to run a python script that send files to a chat using telethon inside a docker container. I scheduled it with cron.

This is part of my docker_compose file...

...
name_xyz:
  env_file: .env
  environment:
    PYTHONUNBUFFERED: 1
    TELEGRAM_POSTING_API_HASH: ${TELEGRAM_POSTING_API_HASH}
    TELEGRAM_POSTING_API_ID: ${TELEGRAM_POSTING_API_ID}
  build:
    context: ./xyz/
    dockerfile: Dockerfile
  volumes:
    - ./xyz:/app
  working_dir: /app/xyz/
  restart: always
  command: ./entrypoint.sh
...

So... in my python script i have:

import os
import asyncio
import requests
from telethon import TelegramClient

TELEGRAM_POSTING_API_HASH = os.getenv('TELEGRAM_POSTING_API_HASH')
TELEGRAM_POSTING_API_ID = os.getenv('TELEGRAM_POSTING_API_ID')

client = TelegramClient('session_name', TELEGRAM_POSTING_API_ID, TELEGRAM_POSTING_API_HASH)
...

and in my .env file i have:

TELEGRAM_POSTING_API_ID=11111111111
TELEGRAM_POSTING_API_HASH=11111111111

i actually dont know what am i doing wrong maybe i am missing something. Please help!

I tried hardcoding the api id and api hash in the python script and it works perfect. But when i put the os.getenv() function it gives me a ValueError: Your API ID or Hash cannot be empty or None

When i change the docker compose file to this:

name_xyz:
  env_file: .env
  environment:
    PYTHONUNBUFFERED: 1
    TELEGRAM_POSTING_API_HASH: ${TELEGRAM_POSTING_API_HASH}
    TELEGRAM_POSTING_API_ID: ${TELEGRAM_POSTING_API_ID}
  build:
    context: ./xyz/
    dockerfile: Dockerfile
  volumes:
    - ./xyz:/app
  working_dir: /app/xyz/telegram
  restart: always
  command: python3 my_python_script.py

it also work... so i think maybe its cron.

here is my entrypoint.sh

#!/bin/bash

# Start the run once job.
echo "Docker container has been started"


# shellcheck disable=SC2046

# Setup a cron schedule
echo "SHELL=/bin/bash

*/2 * * * *  cd /app/xyz/telegram/ && python3 my_python_script.py  >> /var/log/cron.log 2>&1
# This extra line makes it a valid cron" > scheduler.txt

crontab scheduler.txt
cron -f

Solution

  • When cron executes a job, it doesn’t load the environmental variables because cron runs jobs from a non-interactive shell. And as my program needed environmental variables to function properly i was getting that error.

    I solved it by adding my environmental variables as shell variables in my entrypoint.sh

    I hope you find this answer useful! 😁