向 Telegram 发送消息

环境信息

  • Centos 7
  • Python 3

在 Telegram 中生成 Bot

  1. 首先在 telegram 中搜索 @BotFather,和其对话,根据提示创建 机器人,记录下生成的 token 信息

  2. 创建新的 Channel 或者 Group 或者将刚刚新建的 Bot 加入已有的 Channel/Group。

  3. 获取 ChatGroup ID,可以使用以下方法之一

    1. 添加机器人 @get_id_bot 到 Channel,会自动显示 Chat ID

    2. 使用以下代码获取

      >>> import requests
      >>> response = requests.get(f'https://api.telegram.org/bot{token}/getUpdates')
      >>> data = response.json()
      >>> chat_id = data['result'][0]['message']['chat']['id']
      >>> chat_id
      -992754669

使用 curl 向 telegram 发送消息

$ curl -v "https://api.telegram.org/bot{token}/sendMessage?text=sa&chat_id=-992754669"

> GET /bot{token}/sendMessage?text=sa&chat_id=-992754669 HTTP/1.1
> User-Agent: curl/7.29.0
> Host: api.telegram.org
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.18.0
< Date: Fri, 02 Jun 2023 03:03:58 GMT
< Content-Type: application/json
< Content-Length: 276
< Connection: keep-alive
< Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET, POST, OPTIONS
< Access-Control-Expose-Headers: Content-Length,Content-Type,Date,Server,Connection
<
* Connection #0 to host api.telegram.org left intact
{"ok":true,"result":{"message_id":12,"from":{"id":5683237521,"is_bot":true,"first_name":"AlertManager","username":"AlertManager_Bot"},"chat":{"id":-992754669,"title":"AlertManager Test","type":"group","all_members_are_administrators":true},"date":1685675038,"text":"sa"}}

使用 python 向 telegram 发送消息

使用 requests 库

>>> import requests
>>> response = requests.get(f'https://api.telegram.org/bot{token}/sendMessage?text=sa&chat_id=-992754669')

>>> response.text
'{"ok":true,"result":{"message_id":13,"from":{"id":5683237521,"is_bot":true,"first_name":"AlertManager","username":"AlertManager_Bot"},"chat":{"id":-992754669,"title":"AlertManager Test","type":"group","all_members_are_administrators":true},"date":1685675769,"text":"sa"}}'

使用 telegram 库

需要安装 python-telegram-bot

pip install --upgrade python-telegram-bot

发送消息代码

>>> import telegram
>>> import asyncio
>>> bot = telegram.Bot(token='5683231111:AAHzaGf0oRg8A')
>>> async def send_telegram_message():
... response = await bot.send_message(chat_id=-992754669, text="la")
... print(response)
...
>>> loop = asyncio.get_event_loop()
>>> loop.run_until_complete(send_telegram_message())
Message(channel_chat_created=False, chat=Chat(api_kwargs={'all_members_are_administrators': True}, id=-992754669, title='AlertManager Test', type=<ChatType.GROUP>), date=datetime.datetime(2023, 6, 2, 3, 39, 16, tzinfo=datetime.timezone.utc), delete_chat_photo=False, from_user=User(first_name='AlertManager', id=5683237521, is_bot=True, username='MS_AlertManager_Bot'), group_chat_created=False, message_id=14, supergroup_chat_created=False, text='la')

如果需要在非异步环境中(例如 Django 试图函数) 运行以上异步代码,会报错: RuntimeError: There is no current event loop in thread 'Thread-1'。需要特殊处理,可以使用 asyncio.run() 函数来运行异步代码,它可以在非异步环境中创建一个新的事件循环并运行异步函数。

Django 视图中参考代码如下

def send_message_to_tg(chat_id: int, text: str):
''' 发送消息到 tg'''
bot = telegram.Bot(token=tg_bot_token)

async def send_telegram_message():
response = await bot.send_message(chat_id=chat_id, text=text)
print(response)
# loop = asyncio.get_event_loop()
# loop.run_until_complete(send_telegram_message())
asyncio.run(send_telegram_message())