i try to create my pm telebot with telegraf. im new at javascript. can someone help to fix my code?
const { Telegraf, Telegram} = require("telegraf");
const n = new Telegraf(process.env.token)
const chat_id = process.env.chat_id
n.start((ctx) => ctx.reply('Hello! '))
n.on('message', (ctx) => {
let msg = ctx.message.from.id
let text = ctx.message.message_id
if (msg == chat_id){
;
} else {
ctx.forwardMessage(chat_id, msg, text);
}
const reply_msg = ctx.message.reply_to_message.message_id
const reply_msg_user_id = reply_msg.forward_from.id
const own_msg = ctx.message.text
if (reply_msg){
ctx.telegram.sendMessage(reply_msg_user_id, own_msg)
}
})
n.launch()
2
Answers
The error means that
ctx.message.reply_to_message
is undefined whil you are trying to access the propertymessage_id
on it.You can solve this by using optional chaining:
The error says that you are trying to read object property, but there is
undefind
instead an object. Sinceundefind
has no propertymessage_id
, JS is confused. To avoid getting this error, you should always ask yourself, "can may variable beundefined
ornull
instead of an object?" If so, before trying to read its property, check the variable content itself, is it an object?You can do it in several ways. For example, by simple if statement:
Or using logical AND statement:
Or even simplier, using optional chaining operator. It works exactly as the previous option but it shorter.