如何使用我自己的帐户向具有电报 API 的人发送消息

Leo*_*ick 9 python python-telegram-bot telegram-bot telegram-api

当你找不到合适的词时,谷歌的东西会很烦人,这真是太棒了。我找到了一百万个关于如何创建一个 Telegram Bot 来发送和接收消息的答案,这很容易,只需编写五行代码即可。

但是如何管理我自己的帐户?我想知道是否有可能使用 Python(电信或其他库)检索我的个人消息并从我的个人帐户发送消息,而不是使用机器人。

如果可能的话,我在哪里可以找到更多相关信息

Pac*_*ac0 7

Telegram 有一个完整的和文档化的公共 API

按照那里的一些链接,这里是相关部分的摘要:

  • API 不限于机器人,它们只是一种(特殊)用户;
  • API具有称为getMessagesand 的方法sendMessage,这应该是您所需要的;
  • 要调用 API,Telegram 建议使用可用于多种编程语言的专用库TDLib
  • GitHub 上几个可用的示例

在示例中,如果您选择 Python 部分,他们建议:

如果您使用现代 Python >= 3.6,请查看python-telegram

您将找到使用该库的说明,并且在示例文件夹中,您可以找到发送消息脚本

为了完整起见,我将其复制到此处:

import logging
import argparse

from utils import setup_logging
from telegram.client import Telegram

"""
Sends a message to a chat
Usage:
    python examples/send_message.py api_id api_hash phone chat_id text
"""


if __name__ == '__main__':
    setup_logging(level=logging.INFO)

    parser = argparse.ArgumentParser()
    parser.add_argument('api_id', help='API id')  # https://my.telegram.org/apps
    parser.add_argument('api_hash', help='API hash')
    parser.add_argument('phone', help='Phone')
    parser.add_argument('chat_id', help='Chat id', type=int)
    parser.add_argument('text', help='Message text')
    args = parser.parse_args()

    tg = Telegram(
        api_id=args.api_id,
        api_hash=args.api_hash,
        phone=args.phone,
        database_encryption_key='changeme1234',
    )
    # you must call login method before others
    tg.login()

    # if this is the first run, library needs to preload all chats
    # otherwise the message will not be sent
    result = tg.get_chats()

    # `tdlib` is asynchronous, so `python-telegram` always returns you an `AsyncResult` object.
    # You can wait for a result with the blocking `wait` method.
    result.wait()

    if result.error:
        print(f'get chats error: {result.error_info}')
    else:
        print(f'chats: {result.update}')

    result = tg.send_message(
        chat_id=args.chat_id,
        text=args.text,
    )

    result.wait()
    if result.error:
        print(f'send message error: {result.error_info}')
    else:
        print(f'message has been sent: {result.update}')
Run Code Online (Sandbox Code Playgroud)

当然,您需要浏览文档以获取您的案例中的所有变量/ID,但它会让您开始!