node-telegram-bot-api: Problems with a welcome message and the rest of the commands

Hi, I’ve been experiencing an error for a while. Until recently everything worked correctly, but out of nowhere it shows me the following error:

Unable to read property ‘username’ from undefined It happens with all the properties: msg.new_chat_member.first_name msg.new_chat_member.id

I understand that if it were not defined, it would show this error, but if it is defined. I show you the code

bot.on('message',function(msg, match){
    console.log(msg);

    var chatId = msg.chat.id;
    var newUserName = msg.new_chat_member.username;
    var newUserId = msg.new_chat_member.id;
    var firstName = msg.new_chat_member.first_name;
    var messageId = msg.message_id;

    if(msg.new_chat_members != undefined){
        
        bot.deleteMessage(msg.chat.id, messageId);
    	bot.sendMessage(msg.chat.id, "¡Hola " + firstName + ", bienvenid@ al grupo " + msg.chat.title)
            } 
        });

Show the error when I try to use another command, but it does not respond Given this error, it does not let me execute any other function / command

Thanks in advance

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 19 (1 by maintainers)

Most upvoted comments

how to close Chat section in node js by node-telegram-bot-api

Ahhhh. I got it. Thanks @sidelux!

Event new_chat_members not longer exists. You should use:

bot.on('message', (msg) => {
    if (msg.new_chat_members != undefined)
        console.log(message.new_chat_member);
});

I currently have the following. As above, I was trying to make use of the new_chat_members event. The new chat message works only when the bot.on('message') part is commented out. Can we not have multiple bot.on? Or am I missing something?

bot.on("new_chat_members", function (msg) {
    console.log(msg.new_chat_members);
    console.log(msg.new_chat_members[0].first_name);
    bot.sendMessage(msg.chat.id, "Hello " + msg.new_chat_members[0].first_name);
})
bot.on('message', (msg) => {
    //other code
});

You must assign that variables ONLY when msg.new_chat_members != undefined, so:

//...
var chatId = msg.chat.id;
var messageId = msg.message_id;

if (msg.new_chat_members != undefined){
    var newUserName = msg.new_chat_member.username;
    var newUserId = msg.new_chat_member.id;
    var firstName = msg.new_chat_member.first_name;

    //...
}

For the second question, maybe when you solve that error it should be working fine.