如何使用python-telegram-bot获取电报bot对象

时间:2019-07-18 11:21:20

标签: python-3.x telegram telegram-bot python-telegram-bot

我需要向用户发送电报通知。因此,我使用python-telegram-bot库。

现在将通知发送给我创建了以下方法的用户:

def send_notification(chat_id,text) :
    try :
        if chat_id is None or text is None :
            raise Exception("Invalid parameters")
        print(BOT)
        BOT.send_message(chat_id=chat_id, text=text,parse_mode="HTML")
    except Exception :
        logger.exception("AN exception occurred while sending telegram notification")


# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
    """Send a message when the command /start is issued."""
    get_chat_id(update.message)
    BOT = bot
    bot.send_message(chat_id=update.message.chat_id, text="Subscribed successfully to  Bot")

现在的问题是我无法获取机器人对象。如果我尝试通过创建类 telegram.Bot 的对象来再次初始化一个对象,则会收到以下异常:

[2019-07-18 10:52:56,517: ERROR/ForkPoolWorker-7] Error while getting Updates: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running (409)

我的机器人正在使用celery中的辅助队列运行。 我所需要的只是获取bot实例,以便可以发送消息,当用户发出 start 命令时,我已经将用户的聊天ID保存在数据库中。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您应该在txt或json文件中拥有用户,然后使用它:

def send_notification(text) :
  with open(file_path, "r") as jsonFile:
    data = json.load(jsonFile)
    for user in data:
      user_id = data[user]['id']
      try:
        bot.send_message(user_id,text)
      except:
        pass