yagop / node-telegram-bot-api

Telegram Bot API for NodeJS
MIT License
8.45k stars 1.53k forks source link

getUpdates ETELEGRAM 409 Conflict: terminated by other getUpdates request; #550

Closed ricustr closed 2 years ago

ricustr commented 6 years ago
 {"code":"ETELEGRAM","message":"ETELEGRAM: 409 Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}

I'm getting this error some times on restart bot. Does somebody know more information or how to check running instances?
I see more people catch the same error, but nobody can response.

488

sidelux commented 6 years ago

I think the session is not properly terminated, so getUpdates continue get updates after CTRL-C or similar and generate conflict, you can solve it by terminate process maybe. Can you provide server, platform and other infos?

ricustr commented 6 years ago

Do you mean, session as running instance of bot? I think so, because this error appear not every time. How terminate session correctly, or how can I catch getUpdates events to see what happens, if it is possible. Of course, I use a dev bot on my laptop (Ubuntu 17.04) and another for prod on physical server (Ubuntu 16.04.4 LTS) for prod.

sidelux commented 6 years ago

That error means: "There are two or more bots that listen updates at same bot token" So i think you can check process list in your server, what system you use to keep bot alway on? (for example i use pm2)

To print all exception use:

process.on('uncaughtException', function (error) {
    console.log("\x1b[31m", "Exception: ", error, "\x1b[0m");
});

process.on('unhandledRejection', function (error, p) {
    console.log("\x1b[31m","Error: ", error.message, "\x1b[0m");
});

But ETELEGRAM means an error printed by telegram server, you can't get other infos.

ricustr commented 6 years ago

Thank for you response. I use pm2, but i will check processes for bot instance. Okay. I will add methods and see more info and add here. thank you again.

askucher commented 6 years ago

but how to run 2 instances of the bot on one server?

sidelux commented 6 years ago

@askucher Only one istance can listen for updates, otherwise you must use two different bot token

ricustr commented 6 years ago

@sidelux Unfortunately, I can't catch `process.on('uncaughtException', function (error) { console.log("\x1b[31m", "Exception: ", error, "\x1b[0m"); });

process.on('unhandledRejection', function (error, p) { console.log("\x1b[31m","Error: ", error.message, "\x1b[0m"); });` , but the ETELEGRAM 409 Conflict: is still persist. I will try again to check processes after stoped running instance. Thanks.

nvcken commented 6 years ago

@sidelux as Telegram only allow on instance can listen for updates, then how can we scale that instance service what happen if that process handle large messages requests

vjrj commented 6 years ago

@saeedhei I have two telegram bots running with pm2 and this is quite straightforward and robust. I have two, one in English and one in Spanish. https://t.me/AllAgainstTheFire_bot https://t.me/TodosContraElFuego_bot

my only recommendation after pm2 start your bots its to use pm2 save to maintain this instances after this server reboots.

Also I configured this via systemd: http://pm2.keymetrics.io/docs/usage/startup/

vjrj commented 6 years ago

@saeedhei Yes.

I have the same code base that I pull from my github repo in two different directories and different settings.json on each with bot credentials, and sensible API data, etc.

I recommend you to play with pm2 startetc with two simple hello world apps.

Also, I don't use it, but maybe this yeoman generator is useful for you: https://github.com/ashneo76/generator-telegram-bot

saeedhei commented 6 years ago

@vjrj Is this process.yml ok for 2 bot?

apps:
  - script   : src/index1.js
    instances: 1
    exec_mode: cluster
  - script   : src/index2.js
    instances: 1
    exec_mode: cluster
mutantcornholio commented 6 years ago

I guess telegram engineers didn't want to make complex API with message balancing or synchronization tokens, or whatever.

If you want to run several node.js instances in one node.js cluster, I'd recommend polling events in master process and sending them to workers in process.send() If you want to run your bot on several servers, I would recommend creating a lightweight balancing proxy (possibly, with a failover instance waiting nearby) that sends updates to workers. You could do balancing on your own, or use some job queue, like RabbitMQ. The idea stays the same, basically =)

ozodrukh commented 6 years ago

This can be caused by manual startPolling() calling, due to polling start automatically if you passed {polling: true} when creating a bot

sutangu commented 5 years ago

Hi, everybody. It was fixed. Maybe it can be temporarily, but I have errors stopped:

https://github.com/benjick/meteor-telegram-bot/issues/37#issuecomment-389669310

rotimi-best commented 5 years ago

Hi, everybody. It was fixed. Maybe it can be temporarily, but I have mistakes stopped:

benjick/meteor-telegram-bot#37 (comment)

Mine didn't stop. Still have the same problem.

AndrewMZ6 commented 4 years ago

Had the same problem. The first bot listener was running in the background. Solved it with task manager (Ctr + Shift + Esc) -> "Python" process -> right click -> remove the task

jonit-dev commented 4 years ago

I solved it by manually starting and ending my pooling once my function starts and ends (and removed: { polling: true } option from the bot object instantiation). I also did a check to stop the polling if by any reason its active before we're trying to start a new poll. eg.

if(bot.isPolling()) { await bot.stopPolling(); }

await bot.startPolling();

[SOME CODE]

await bot.stopPolling();

newCodeUz commented 4 years ago

i after millions of hits. I decided to php the bot

defendson commented 3 years ago

Hi there. It looks like you try running the bot with token that is already in use.

I solved it when changed token value, created new one bot for development and testing, because previous bot had already been working in production.

const token = 'SET YOUR ANOTHER TOKEN HERE'; const telegramBot = new TelegramBot(token, { polling: true });

then, it should work

Shrikshel commented 3 years ago

I understand it's quite a late reply to this thread, in my case (and I think for most others) the issue is, pm2 tries to start loadbalancer with instances: 'max' , and when more than 1 (pm2) instance is possible then, for polling on both the instances telegrams complains this error which is logical.

AnimeKraze commented 3 years ago

That error means: "There are two or more bots that listen updates at same bot token" So i think you can check process list in your server, what system you use to keep bot alway on? (for example i use pm2)

To print all exception use:

process.on('uncaughtException', function (error) {
  console.log("\x1b[31m", "Exception: ", error, "\x1b[0m");
});

process.on('unhandledRejection', function (error, p) {
  console.log("\x1b[31m","Error: ", error.message, "\x1b[0m");
});

But ETELEGRAM means an error printed by telegram server, you can't get other infos.

How can I see what bot is using my commands

marshalmax888 commented 3 years ago

“ETELEGRAM: 409 Conflict: terminated by other getUpdates request; make sure that only one bot instance is running” Maybe you are running your local bot project, and the telegram think that is 2 bot instance...so you need to close that and then vist the https://api.telegram.org/bot....../getUpdates

Yonny24 commented 3 years ago

Great this solved my issue thanks. Just created a new bot and new token. I have nodered with telegram bot on 1 linux server and another on windows docker. Shame we can't use the same bot though.

mcpeblocker commented 3 years ago

The Telegraf examples section on GitHub has a piece of code that can solve this problem for me.

// Enable graceful stop process.once('SIGINT', () => bot.stop('SIGINT')) process.once('SIGTERM', () => bot.stop('SIGTERM'))

There may be processes that you were using and have not terminated yet. I think it is possible if you're using one of nodemon or pm2 packages. You can find not terminated nodemon processes on ubuntu like so: ps aux | grep -i nodemon and terminate them: kill -9 [process ID]

andrey-pavlenko commented 3 years ago

Works with nodemon in my case. Separate build process used with tsc -w to dist folder.

package.json

{
  "scripts": {
    "start:w": "NODE_ENV=development nodemon --signal SIGQUIT -w dist dist/index.js"
  }
}

index.ts


let telegramBot: TelegramBot | null = null;

async function start(token: string): Promise<void> {
  telegramBot = new TelegramBot(token);
  await telegramBot.startPolling({ restart: true });
}

async function stop(): Promise<void> {
  if (telegramBot != null) {
    await telegramBot.stopPolling({ cancel: true });
    telegramBot = null;
  }
  process.exit();
}

start();
process.on('SIGQUIT', stop);
process.on('SIGINT', stop);
ZoeMohamed commented 2 years ago

Pusing bot

evgeniy2702 commented 1 year ago

I also have this error when I use a Telegram bot extending from LongPollingTelegram. My bot is written in SpringBoot version 2.6.4, java version 1.8.0_271, which is deployed on tomcat version 9.0.56 under linux. I used the following dependencies for the Telegram bot : `

org.telegram
        <artifactId>telegrambots-spring-boot-starter</artifactId>
        <version>5.6.0</version>
    </dependency>

    <dependency>
        <groupId>org.telegram</groupId>
        <artifactId>telegrambots</artifactId>
        <version>5.6.0</version>
    </dependency>`

I use the following code to initialize my bot : @EventListener({ContextRefreshedEvent.class}) public void init() throws TelegramApiException{ consoleLogger.info("Start initializer MediaBot ."); TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class); try{ BotSession session = telegramBotsApi.registerBot(bot); bot.setSession(session); } catch (TelegramApiException e) { consoleLogger.error("Error occurred: " + e.getMessage()); } }

And my bot has the following PreDestroy method to close and release all resources: @PreDestroy public void preDestroy(){ consoleLogger.info("Stop bots session ."); this.onClosing(); this.getSession().stop(); consoleLogger.error("Bot session was stopped ."); }

But when I deploy my bot from tomcat, I get the following error : "409 Conflict: completed by another getUpdates request;". And this error repeats every second. What am I doing wrong? I can't figure it out. The support of Telegram is not answer for my email.

evgeniy2702 commented 1 year ago

The way I have was see it, the reason was using the telergambots-spring-boot-starter dependency. It automatically does telegram bot registration and if you try to create TelegramBotApi to register bot in the code - you actually do bot registration twice and end up with two bots with one token. And second - using this dependency I can't figure out how I can get BotSession (this is only for LongPollingBot) for closing my bot correctly and I got a memory leak error when removing my application from tomcate. Solution: I use the org.telegram.telegrambots dependency and then I can make my bot register by creating TelegramBotApi and as a result I get access to ExecutorService to release the executor resources and plus for LongPollingBot i get access to BotSession for close the session correctly.

ELHart05 commented 1 year ago

Same problem, any fix?

Cosmits commented 11 months ago

This code is work,when I deploy code on www.render.com

index.js

const TelegramBot = require('node-telegram-bot-api');

// Use environment variables for the token and webhook URL
const token = process.env.TELEGRAM_TOKEN;
const url = process.env.WEBHOOK_URL;

const bot = new TelegramBot(token, {webHook: {port: process.env.PORT || 443}});

// Set the webhook to the URL provided by Render
bot.setWebHook(`${url}/${token}`);

bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, 'Received your message');
});
mielpl commented 8 months ago

Finally, I found the cause of this problem in my situation. I created the telegram bot service and initialized it there. I used it in my Telegram bot service constructor and in the application service (injected it). Because of this, it was initialized twice when the application was launched. It was my mistake. I also tried telegraf.js and grammy.js, there also appeared this conflict error message. You should initialize TelegramBot once and in another file from service file. I hope it will be useful.

lipe-pepe commented 8 months ago

This code is work,when I deploy code on www.render.com

index.js

const TelegramBot = require('node-telegram-bot-api');

// Use environment variables for the token and webhook URL
const token = process.env.TELEGRAM_TOKEN;
const url = process.env.WEBHOOK_URL;

const bot = new TelegramBot(token, {webHook: {port: process.env.PORT || 443}});

// Set the webhook to the URL provided by Render
bot.setWebHook(`${url}/${token}`);

bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, 'Received your message');
});

Hey, do you have more information on this? How do we set up the web hook for render?

Cosmits commented 8 months ago

This code is work,when I deploy code on www.render.com index.js

const TelegramBot = require('node-telegram-bot-api');

// Use environment variables for the token and webhook URL
const token = process.env.TELEGRAM_TOKEN;
const url = process.env.WEBHOOK_URL;

const bot = new TelegramBot(token, {webHook: {port: process.env.PORT || 443}});

// Set the webhook to the URL provided by Render
bot.setWebHook(`${url}/${token}`);

bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, 'Received your message');
});

Hey, do you have more information on this? How do we set up the web hook for render?

show my code here ... https://github.com/Cosmits/test-telegram-bot

its-dibo commented 8 months ago

one reason is when you instantiate the class twice, make sure you create the instance as singleton

let instance1 =  new Telegram(this.token, { polling: true });

// in another place
let instance2 =  new Telegram(this.token, { polling: true });
Comandante7s commented 7 months ago
 {"code":"ETELEGRAM","message":"ETELEGRAM: 409 Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}

Recibo este error algunas veces al reiniciar el bot. ¿Alguien sabe más información o cómo comprobar las instancias en ejecución? Veo que más personas detectan el mismo error, pero nadie puede responder. #488

 {"code":"ETELEGRAM","message":"ETELEGRAM: 409 Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}

Recibo este error algunas veces al reiniciar el bot. ¿Alguien sabe más información o cómo comprobar las instancias en ejecución? Veo que más personas detectan el mismo error, pero nadie puede responder. #488

Hola, asegurate que en tu archivo que creaste package.json, haga referencia en main hacia el archivo creado manuelmente bot.js.

Esa fue mi solución. Saludos.

markpumpkin commented 1 month ago
 {"code":"ETELEGRAM","message":"ETELEGRAM: 409 Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}

I'm getting this error some times on restart bot. Does somebody know more information or how to check running instances? I see more people catch the same error, but nobody can response. #488

=>> The main issue lies in the fact that you are initializing the bot (new TelegramBot) multiple times, but you should only initialize it once for each bot_token