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()
CodePudding user response:
The error means that ctx.message.reply_to_message
is undefined whil you are trying to access the property message_id
on it.
You can solve this by using optional chaining:
const reply_msg = ctx.message.reply_to_message?.message_id
CodePudding user response:
The error says that you are trying to read object property, but there is undefind
instead an object. Since undefind
has no property message_id
, JS is confused. To avoid getting this error, you should always ask yourself, "can may variable be undefined
or null
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:
if (ctx.message.reply_to_message !=== undefind)
// or even simplier
if (ctx.message.reply_to_message)
Or using logical AND statement:
const reply_msg = ctx.message.reply_to_message && ctx.message.reply_to_message.message.id
Or even simplier, using optional chaining operator. It works exactly as the previous option but it shorter.
const reply_msg = ctx.message.reply_to_message?.message.id