【问题标题】:How can I send a message to someone with telegram API using my own account如何使用我自己的帐户向使用电报 API 的人发送消息
【发布时间】:2020-11-26 01:23:57
【问题描述】:

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

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

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

【问题讨论】:

    标签: python telegram-bot python-telegram-bot telegram-api


    【解决方案1】:

    Telegram 有一个完整且有记录的public API

    根据那里的一些链接,以下是相关部分的摘要:

    • API 不限于机器人,它们只是一种(特殊)用户;
    • API has methods 称为 getMessagessendMessage,这应该是您需要的;
    • 要调用 API,Telegram 建议使用可用于多种编程语言的专用库 TDLib
    • several examples available on GitHub

    在示例中,如果您使用 Python 部分,他们推荐:

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

    您将找到使用该库的说明,并且在 examples 文件夹中您可以找到 script to send a message

    为了完整起见,我将它复制在这里:

    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}')
    

    当然,您需要浏览文档以了解您的案例中的所有这些变量/ID,但它会让您入门!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-30
      • 2016-06-02
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      相关资源
      最近更新 更多