Remotely controlled SpyCam with nodejs and telegram
Published: 2022-06-04 07:27:50

In this article you are going to see how to create a spy camera with nodejs and telegram that you can use to capture images over the internet , so lets start :) 


### Create a Telegram Bot 
go to telegram and search BotFather
![Search BotFather](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4o7ex8stz634dhp4oqio.png)
now if you click the menu you are going to see "create new bot" option along with some other options 
![create new bot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jbb0etg5mo2rhati76ky.png)
hit "create new bot" 
![create-new-bot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hheai7gy52f9insqgvuv.png)
now you have provide some name the bot and a username for the bot 
![BotFather](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ylthh68qi5nztk3g2cmh.png)
you will receive token and bot link in return , securely store them for later use and do not share them publicly .

### Create a node project 
you now have to create a node project , go to the directory you want to store you code in and hit 
```
yarn init -y 
```
now lets install some dependencies 
```
yarn add dotenv node-webcam node-telegram-bot-api
```
create a .env file in your project root , with TELEGRAM_TOKEN , MY_TELEGRAM_CHAT_ID , ACTIVATION_TEXT variables
![env-example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/97xug8dwh4l07q8wgc8o.png)
put the secret token that you received from BotFther in TELEGRAM_TOKEN , set ACTIVATION_TEXT , MY_TELEGRAM_CHAT_ID  is to make things more secure you will see how to find it below
(you can also work without chatId , there is a github link for that at the end of the article)
### getting MY_TELEGRAM_CHAT_ID 

```
// main.js 
require('dotenv').config()
const TelegramBot = require('node-telegram-bot-api');
const { TELEGRAM_TOKEN} = process.env

const bot = new TelegramBot(TELEGRAM_TOKEN, { polling: true });

bot.on('message', async (msg) => {
    const chatId = msg.chat.id;
    console.log({chatid})

});
```
if you run this code with `node main.js` and send a message in your bot channel ( bot channel can be found with token message from BotFather ) you will get your chatId , you can now set it in MY_TELEGRAM_CHAT_ID  in .env file 
![chat-id](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxozj99zws70yrh8otua.png)
### Taking pic from webcam with node 
you are going to use the below code to take pic with node from your webcam 
```
// takePic.js 
var NodeWebcam = require("node-webcam");


const takePic = async () => {
    try {
        return new Promise((resolve, reject) => {

            var fileName = Math.random().toString().slice(2, 8);

            var opts = {
                width: 1280,
                height: 720,
                quality: 100,
                frames: 60,
                delay: 0,
                saveShots: true,
                output: "jpeg",
                device: false,
                callbackReturn: "location",
                verbose: false
            };

            var Webcam = NodeWebcam.create(opts);

            Webcam.capture(`${fileName}`, function (err, data) {
                if(err) reject(err);
                resolve(`${fileName}.jpg`);
            });

        })


    } catch (error) {
        reject(error);
    }

}

module.exports = takePic ;
```



now that you have everything in your .env set up , you can now modify your main.js like this 
```
var takePic = require("./takePic");
require('dotenv').config()
const TelegramBot = require('node-telegram-bot-api');
const { TELEGRAM_TOKEN, MY_TELEGRAM_CHAT_ID, ACTIVATION_TEXT } = process.env

const bot = new TelegramBot(TELEGRAM_TOKEN, { polling: true });

bot.on('message', async (msg) => {
    const chatId = msg.chat.id;
    const { text } = msg;
    try {
        if (chatId == MY_TELEGRAM_CHAT_ID && text == ACTIVATION_TEXT) {
            bot.sendMessage(chatId, 'wait');
            const filename = await takePic();
            const url = `${__dirname}/${filename}`;
            bot.sendPhoto(chatId, url);
        }
    } catch (error) {
        console.log(error);
        bot.sendMessage(chatId, error);
        bot.sendMessage(chatId, 'an exception occurred');
    }

});
```
now run main.js `node main.js` , if you now send the activation text in your bots channel (hear it is "snap" , set in .env) you will initially receive a reply with "wait" followed by a Picture captured from your webcam  3:D .

![hello-spy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esbpgt3u9djasrfztyvl.png)

you can find the whole code in hear 

https://github.com/aistiak/node-telegram-spy-cam

without chatId

https://github.com/aistiak/node-telegram-spy-cam/tree/without-chat-id

Thank You for reading this article , hope you found it useful :)