Hello everybody,
In this article I am going to show you how to create a simple but very effective Motion detector that sends you the detected movements via Telegram using my Java library: TelegramBotUtilities.
First of all, we have to download a library called “webcam-capture” from here: http://webcam-capture.sarxos.pl/ .
Go on that page and download the zip file.
If you haven’t yet downloaded the TelegramBotUtilities library, then download it here!
Webcam-capture is a cross-platform and simple to use library that allows you to retrieve with few lines of code frames from your webcam.
All you have to do is download it, extract it and import the jar files under the “libs” folder and the “webcam-capture” jar into your project.
In order to code the bot you will need your user id.
To get it, just go to http://api.telegram.org/bot
Once done, we can start coding our bot.
In this video I show you how to set-up your environment and code your bot:
Here you have the source code:
package MotionDetection; import com.github.sarxos.webcam.Webcam; import com.github.sarxos.webcam.WebcamMotionDetector; import com.github.sarxos.webcam.WebcamMotionEvent; import com.github.sarxos.webcam.WebcamMotionListener; import org.altervista.leocus.telegrambotutilities.TelegramBot; import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; public class MotionDetector implements WebcamMotionListener{ private TelegramBot bot = new TelegramBot("<YOUR TOKEN>"); // Replace it with your api key private Webcam webcam; private int interval = 250; private String recipientId = "<YOUR ID>"; // Replace it with your id public MotionDetector() { webcam = Webcam.getDefault(); WebcamMotionDetector detector = new WebcamMotionDetector(webcam); detector.setInterval(this.interval); detector.addMotionListener(this); detector.start(); } @Override public void motionDetected(WebcamMotionEvent webcamMotionEvent) { try { // Create a temp file File temp = File.createTempFile("temp", ".jpg"); // Write the image onto the file ImageIO.write(webcam.getImage(), "jpeg", temp); // Send the photo bot.sendPhoto(recipientId, temp, "Motion detected", false, -1, null); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { new MotionDetector(); System.in.read(); // In order to keep the application alive } }
And here there is the output received on Telegram from the motion detection bot:
That’s all!
In the next episodes we will add more exciting features to our bot! Stay tuned!
Here is the link for the second part
Subscribe to the telegram group in order to get updates for next episodes and for asking your questions: Link to the group