#!/usr/bin/perl
#
# This script sends a sequence of videos via Telegram to a list of students, one video from the sequence per day
# - telegram-cli must be installed and connected with an account
# - the video files can have any file extension recognised by Telegram and must reside in Telegram's "downloads" folder
# - the filename part of the video is just a number representing the position in the sequence e.g. 1.mp4 or 3.avi
# - each video can have an associated intro message in text files accompanying the videos e.g. intro1.txt
# - each video can have an associated caption text in a text file too, e.g. caption1.txt
#
# Configuration file:
# - the program is configured with a file called student-videos.conf in the same directory
# - the first line of the config file is the full path to the telegram downloads folder
# - subsequent lines are a list of the students, one per line, and the date they should receive their first video
# - the format of each entry in the students.txt file is yyyy-mm-dd: Telegram_Name_Using_Underscores
# - run with --test paramater to see the Telegram commands that would be executed
#
use Time::Local;
use Cwd qw( realpath );
# Are we just testing
$test = ( $ARGV[0] eq '--test' );
# Change to the directory this code's in
chdir $1 if realpath($0) =~ m|^(.+)/|;
# Open the conf file and get the downloads location from the first line
open CONF, '<', 'student-videos.conf' or die "No config file found!";
$downloads = <CONF>;
chomp $downloads;
# Loop through the rest of the lines, one student per line
while(<CONF>) {
# Extract info from this line
$time = timelocal(0,0,0,$3,$2-1,$1) if /\s*(\d\d\d\d)-(\d\d)-(\d\d):\s+(\S+)/;
$student = $4;
# Calculate the whole number of days since this students first video
$days = int( (time() - $time) / 86400 );
# Find video files matching this day
@files = glob( "$downloads/$days.*" );
# If there is one...
if( $#files == 0 ) {
print "Sending video $days to $student\n";
# If there is an intro file for this video, send it as a normal message
$intro = "$downloads/intro$days.txt";
if( -e $intro and open TXT, '<', $intro ) {
sysread TXT, $msg, -s $intro;
close TXT;
telegram( "msg $student", $msg );
}
# Get the text from the caption file for this video if there is one
$caption = "$downloads/caption$days.txt";
if( -e $caption and open TXT, '<', $caption ) {
sysread TXT, $captext, -s $caption;
close TXT;
} else { $captext = '' }
# Send the video file to the student
telegram( "send_video $student $files[0]", $captext );
}
}
close CONF;
# Send a command to telegram-cli or just print it if testing
sub telegram {
my( $cmd, $msg ) = @_;
if( $msg ) {
$msg =~ s/"/\\\\\\"/g;
$cmd .= " \\\"$msg\\\"";
}
$cmd =~ s/\n/\\n/g;
$cmd =~ s/\$/\\\$/g;
if( $test ) { print "\t$cmd\n" }
else { qx( telegram-cli -W -e "$cmd" ) }
}