SoFunction
Updated on 2024-11-17

Python builds message alerts with Telegram bots

I've been spending more time with Telgram lately

Probably the most appealing aspect of Telgram for developers is the Telgram bot, where you can build a bot to do something. But one of the most useful features for me at the moment is to do message alerts through the bot. As a developer, I want to know in real time how the site is running, and being instantly alerted when the system reports an error is a pain point issue.

Of course, there are some ready-made solutions in the country, such as access to enterprise WeChat or nail and so on in the chat tool, that is, access to the trouble, you still have to get a business first. There are also some third-party platforms to do reminders through the public number.

My previous practice was to be alerted by sending a text message, but I didn't even bother to read the text messages. SMS ran out of this option and gave up. Later, I thought of a new way, is to use the mail way, sendcloud has a certain free limit of mail sending every day. Email alerts integrated into the system, send messages to QQ mailbox, because QQ mailbox has the advantage that it can be associated with WeChat, so that whenever there is a system has reported errors can be the first time to receive WeChat message alerts.

Recently, I've found Telgram's bots to be an alternative, and you can quickly build one out in 10 minutes.

Apply for a robot

Getting a robot is easy too.

Request a bot directly from [Bot Dad], search for "BotFather" and send him a message/newbot

At this point he will prompt you to set a username for the bot, which must begin with_bot wind up

If you encounter a duplicate name you will be prompted to change it. After the application is successful, he will issue you a token.

This token is your credentials to call the api later, so keep it safe because anyone who gets this token can use your bot to operate the api, and you can update the token if it leaks.

Verify the token

The following interface can be used to verify if the token is available

/bot{token}/getMe

Note that the token is preceded by a fixedbot Word, if you don't write it will prompt a 404 error.

Normal will return a success message

{
  "ok": true,
  "result": {
    "id": 12345678,
    "is_bot": true,
    "first_name": "xxxx",
    "username": "xxxxxx",
    "can_join_groups": true,
    "can_read_all_group_messages": false,
    "supports_inline_queries": false
  }
}

send a message

  • Before we send a message, we create a channel dedicated to receiving messages.
  • Set a unique channel account for the channel
  • Pull the bots into the channel so that the bots can send messages in it

Calling the Send Message Interface

/bot{token}/sendMessage?text=hello&chat_id=@channel_id

  • text is the message you want to send
  • chat_id is the channel ID.

Return data:

{
  "ok": true,
  "result": {
    "message_id": 4,
    "sender_chat": {
      "id": -110201250852,
      "title": "Log message",
      "username": "Channel id",
      "type": "channel"
    },
    "chat": {
      "id": -110201250852,
      "title": "Log message",
      "username": "Channel id",
      "type": "channel"
    },
    "date": 1654791886,
    "text": "hello"
  }
}

The interface is validated and you can integrate it into your system with the appropriate libraries.

Let's take flask as an example, here is the core code

# 
@("/error")
def exception_test():
    s = 1/0
    return success()


# 
@(Exception)
def server_error(e):
    (f"internal error{str(e)}", exc_info=True)
    if ("ENV") in ("production", 'development', 'local'):
        tb = traceback.format_exc()
        telegram.send_message(f"error message:{str(e)} \nstack information:{tb}", chat_id=("TELEGRAM_CHAT_ID"))
    return error(code=500, http_code=500, msg="Internal error.")


# 
class Telegram:

    def __init__(self, app=None):
         = app
        self._session = ()
         = None
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
         = app
         = ("TELEGRAM_BOT_TOKEN")

    def send_message(self, text, chat_id):
        response = self._session.get(
            f"/bot{}/sendMessage?text={text}&chat_id=@{chat_id}")

Start the program, go to localhost:5000/error, and telgram will be alerted with the message

To this article on the use of Python Telegram Telegram robot to build a message reminder of the article is introduced to this, more related Python Telegram message reminder content, please search for my previous articles or continue to browse the following related articles I hope that you will later support me more!