A set of scripts for a Telegram bot that posts pictures of space
Python3 should be already installed.
Download the ZIP archive of the code and unzip it.
Then open terminal form unzipped directory and use pip
(or pip3
, if there is a conflict with Python2) to install dependencies:
pip install -r requirements.txt
Before you run any of the scripts, you may need to configure environmental variables:
- Go to the unzipped directory and create a file with the name
.env
(yes, it has only the extension). It is the file to contain environmental variables that usually store data unique to each user, thus you will need to create your own. - Copy and paste this to
.env
file:
NASA_API_KEY='{nasa_key}'
TELEGRAM_API_TOKEN='{telegram_token}'
TELEGRAM_CHANNEL_ID='@{channel_id}'
IMAGES_DIR='{dir_path}'
- Replace
{nasa_key}
with NASA API key you will receive when you sign up. - Replace
{telegram_token}
with API token for the Telegram bot you have created with the help of BotFather. This token will look something like this:958423683:AAEAtJ5Lde5YYfkjergber
. - Replace
{channel_id}
with the identificator (as in thehttps://t.me/{identificator}
) of the Telegram channel you have created, it would look like this:TELEGRAM_CHANNEL_ID='@some_channel'
. - Don't forget to appoint the bot as an administrator of the channel (in the channel settings) and give it rights to post in the channel (in
BotFather
menu,Bot Settings
->Channel Admin Rights
->Post in the channel
). - Replace
{dir_path}
with the path to directory where you want to store downloaded images. It has default value - when you run one of thefetch_***.py
scripts, the directory with the nameimages
will be created in the unzipped directory. If you want to use the default value, simply deleteIMAGES_DIR='{dir_path}'
line from.env
file.
Download images by running either or all of fetch_***.py
scripts, like this:
python3 fetch_nasa_apod_images.py
python3 fetch_nasa_epic_images.py
python3 fetch_spacex_images.py
You can run fetch_spacex_images.py
script with --id
parameter, giving it the identificator of a particular SpaceX launch, like this:
python3 fetch_spacex_images.py --id 5eb87d47ffd86e000604b38a
If an identificator wasn't given, this script will fetch photos from latest launch.
If a picture's size is too big to be published in a Telegram channel (more than 10 megabytes), it will be compressed automatically.
Then, you can publish just one image to your channel either of these ways:
- a random picture from
IMAGES_DIR
python3 telegram_bot_single.py
- a specific picture from
IMAGES_DIR
python3 telegram_bot_single.py --file file_in_images_dir.ext
Or, you can set a loop which will shuffle pictures in IMAGES_DIR
and post one each X
hours (integer number, optional argument, default value is 4
):
python3 telegram_bot_loop.py --delay X
The code is written for educational purposes on online-course for web-developers dvmn.org.