Search code examples
pythonbotstelegram-botbinancepy-telegram-bot-api

bot terminated by other getUpdates request make sure that only one bot instance is running


Hello everyone In this module(telegram_interface.py) I have (send_msg) method which I need to call it in another modules, but whenever I try to import this module(telegram_interface) inside the other modules to call the send_msg method, I had the error that I'm calling getUpdates from more than one instance, is there away to avoid this to happen !

telegram_interface.py
import configparser
import telepot
import time
from database import Status
import datetime as dt
import place_orders as po
import requests

config = configparser.ConfigParser()
config.read("config1.ini")

bot_token = str(config["TelegramBot1"]["bot_token"])
my_chat_id = str(config["TelegramBot1"]["my_chat_id"])
bot111 = telepot.Bot(bot_token)


def time_now():
    time = dt.datetime.now()
    time = time.strftime("%H:%M:%S   //   %d-%m-%Y")
    return time


# def send_msg(text):
#     url = "https://api.telegram.org/bot"+bot_token + \
#         "/sendMessage?chat_id="+my_chat_id+"&parse_mode=Markdown&text="
#     http_request = url + text
#     response = requests.get(http_request)
#     return response.json()


def handle(msg):
    user_name = msg["from"]["first_name"] + " " + msg["from"]["last_name"]
    content_type, chat_type, chat_id = telepot.glance(msg)

    if content_type == "text":
        command = msg["text"]
        if "/START" == command.upper():
            bot111.sendMessage(chat_id,
                               "Welcome "+user_name+" in your Auto Trading Bot! \n command [/help] to get more information about the bot. ")
        elif "/HELP" == command.upper():
            bot111.sendMessage(chat_id,
                               "Available commands are: \n **[ON, OFF] - Control the bot. \n **[balance] - Get your free USDT balance.")
        elif "ON" == command.upper():
            Status.save_status(collection="Status",
                               status=command.upper(), time=time_now())
            bot111.sendMessage(chat_id, "System is *Activated*.",
                               parse_mode="Markdown")
            with open("log.txt", "a") as log_file:
                log_file.write(
                    "System is Activated at : " + time_now() + "\n")
        elif "OFF" == command.upper():
            Status.save_status(collection="Status",
                               status=command.upper(), time=time_now())
            bot111.sendMessage(chat_id, "System is *Deactivated*.",
                               parse_mode="Markdown")
            with open("log.txt", "a") as log_file:
                log_file.write("System is Deactivated at : " +
                               time_now() + "\n")
        elif "BALANCE" == command.upper():
            free_balance = po.get_usdt_balance()
            bot111.sendMessage(chat_id,
                               "Your free balance is : *"+str(free_balance)+" USDT*", parse_mode="Markdown")
        else:
            bot111.sendMessage(chat_id,
                               "Unknown command, use [/help] to get more information.")


bot111.message_loop(handle)


while True:
    time.sleep(20)

Solution

  • When you import any module in Python, it is being executed, for example let's imagine we have the following module print_hello.py:

    print('hello world')
    

    If you run it, it will print hello world. If you import this module:

    import print_hello
    

    it will print hello world too! So, if you import it multiple times, it will print hello world exactly that much times. To avoid this, you need to simulate main entrypoint, edit print_hello.py:

    if __name__ == '__main__':
        print('hello world')
    

    In this case, hello world will be printed only with running print_hello.py, but won't be printed if imported. So, you should apply this to your lines of code:

    bot111.message_loop(handle)
    
    
    while True:
        time.sleep(20)