// Using import statements instead of require
import express from "express";
import path, { dirname } from "path";
import { Telegraf, session } from "telegraf";
import { config } from "dotenv";
import { fileURLToPath } from "url";
import { PrismaClient } from "@prisma/client";
import { botSendMessage, sendServState, sendWPT } from "./helper_functions.js";
import ngrok from 'ngrok'
config();
// Using Prisma ORM
const prisma = new PrismaClient();
// Setup __dirname equivalent in ES module scope
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Initialize dotenv
// Initialize Express
const expressApp = express();
const port = process.env.PORT || 3000;
// Middleware to serve static files
expressApp.use(express.static("static"));
expressApp.use(express.json());
// Initialize the bot
const bot = new Telegraf(process.env.BOT_TOKEN, { telegram: { webhookReply: false } });
bot.use(session())
// Start ngrok and set the webhook
(async function() {
try {
// Connect ngrok to the specified port
const url = await ngrok.connect(port);
const WEBHOOK_URL = `${url}/telegram-webhook`;
// Set the webhook for the bot
await bot.telegram.setWebhook(WEBHOOK_URL);
console.log(`Webhook set to ${WEBHOOK_URL}`);
// Webhook handler for incoming Telegram updates
expressApp.post('/telegram-webhook', (req, res) => {
bot.handleUpdate(req.body)
.then(() => {
if (!res.headersSent) {
res.sendStatus(200);
}
})
.catch((error) => {
console.error('Error in webhook handler:', error);
if (!res.headersSent) {
res.sendStatus(500);
}
});
});
// Root endpoint to serve the main page
expressApp.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/index.html"));
});
// Start the Express server
expressApp.listen(port, () => {
console.log(`Server running on port ${port}`);
});
} catch (err) {
console.error('Error setting up webhook or server:', err);
}
})();
bot.command("start", (ctx) => {
console.log(ctx.from);
console.log(ctx.session);
ctx.session.state = 'idle'
ctx.session.cur_command = null
botSendMessage(bot, ctx, "Hello there! I am the FM helper bot.")
});
This is my botSendMessage:
export function botSendMessage(bot, ctx, message){
bot.telegram.sendMessage(ctx.chat.id, `@${ctx.from.username}n${message}`);
}
Here is a snippet of my code for the telegram bot, everything was working before I added in the usage of session() middleware. Howveer now, whenever I try the /start command, I always run into an error of
Error in webhook handler: TypeError: Cannot set properties of undefined (setting 'state')
at file:///C:/fm-telebot/index.js:134:21
at C:fm-telebotnode_modulestelegraflibcomposer.js:397:28
at C:fm-telebotnode_modulestelegraflibcomposer.js:165:111
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async execute (C:fm-telebotnode_modulestelegraflibcomposer.js:518:17)
at async C:fm-telebotnode_modulestelegraflibcomposer.js:519:21
at async execute (C:fm-telebotnode_modulestelegraflibcomposer.js:518:17)
at async C:fm-telebotnode_modulestelegraflibcomposer.js:519:21
at async C:fm-telebotnode_modulestelegraflibsession.js:104:13
at async execute (C:fm-telebotnode_modulestelegraflibcomposer.js:518:17)
because I have a catch block in the expressApp.post(). And when I console log out my ctx.session() in the /start command, it just shows undefined.
I tried to explicitly set the options for the session middleware but it also did not work. I think I have also searched online and didnt find posts of much relevance to mine. ClaudeAI also didnt manage to help find out the error.
If anyone has had any experience with this, on where I went wrong with this or how to solve this error (I was thinking of setting it manually BUT that will require me to check in every command if session is instantiated which is really inconvenient and undesirable)