node-telegram-bot-api icon indicating copy to clipboard operation
node-telegram-bot-api copied to clipboard

Multiple bot, one nodejs process (help needed)

Open wisdomabioye opened this issue 6 years ago • 2 comments

I'm setting up multiple bot in one nodejs process. I need help on how to go about this I'm setting webhook for each bot from another application so I'm not using this library bot.setWebhook(url, options)

How can I refactor this code to work well? Is there a better way to do this?

index.js

app.post('*', function(req, res){
        //catches all request to bot, extract the API token and fetch configuration from DB
	//req.url.substring(1) is the token for the bot requested
	bots.findOne({token:req.url.substring(1)})
	.exec(function(err, conf){
		/*
                //Sample conf
                 {
		    "twitterUsername": "twurl_test",
		    "token": "697129:tYe_mJpjCvs",
		    "botUsername": "vps_svr",
		    "allowInfoUpdate": false,
		    "webhookUrl": "https://example.io/697129:tYe_mJpjCvs",
		    "paused": false
		}*/
                if(err){
			console.log(err);
			return;
		}
		let bot = require('./factory/vps')(conf);	
		bot.processUpdate(req.body);
		res.sendStatus(200);
	})
})

How can I implement an instance of a Telegram bot that listen and respond to event in vps.js Currently, this bot works but sometimes fail to respond to request.

vps.js

const TelegramBot = require('node-telegram-bot-api');
const helpers = require('./helpers');
module.exports = function(config){
	const bot = new TelegramBot(config.token);
	if(config.paused){
		//config.paused == true;
		console.log('Service is currently paused');
		return;
	}
	//*************************//
	//*****Bot Commands********//
	//*************************//
	bot.onText(/\/start/, (msg) => {
	  helpers.createRecord(msg);
	});
	//send message and get reply
	//*************************//
	//******Other Messages*****//
	//*************************//
	bot.on('text', async (msg) => {
	  let userId = msg.from.id;
	  let username = msg.username;
	  let msgId = msg.chat.Id;
	  let receivedMsg = msg.text.toLowerCase();
	
	  if(await helpers.isPrivate(msg)){
	      //check the message received
	      switch(receivedMsg){
	        case "⁉️help":
	        case "help":
	            helpers.sendPrivateMessage(msg,"instruction");
	          break;
	        case "about":
	        	helpers.sendPrivateMessage(msg,"aboutMsg");
	          break;   
	      }//end switch  
	  }
	});

	//handle all webhook error
	bot.on('webhook_error',(error)=>{
	  console.log('Webhook Error catched>>> ',error);
	});
	
	return bot;
}

wisdomabioye avatar Jan 06 '19 21:01 wisdomabioye

Your logic seems to be on the right track.

.. but sometimes fail to respond to request

Could you describe what exactly happens. Any logs that you could capture.

kamikazechaser avatar Feb 05 '19 11:02 kamikazechaser

Hey! Any breakthrough on the subject.

imdkbj avatar Aug 12 '19 20:08 imdkbj