【问题标题】:Sending Telegram message from Python从 Python 发送 Telegram 消息
【发布时间】:2015-05-14 05:27:43
【问题描述】:

我想通过 Telegram 从 Python 脚本发送消息。 我试图通过电报 cli 来做到这一点,original version from vyshengpatched version from luckydonald。有了他们两个,我都可以成功地将消息发送到我的手机。 我的问题是:

  • pytg2 没有安装干净(导入 DictObject 失败,显然作者在 pypi 上单独有这个,但我在那一点停止了),需要 Python 3(与我的项目的其余部分不同,但半可接受)并且可以做比我需要的多。
  • 我无法将输入输入到随后在那里执行的 tg 控制台环境中。通过<<EOF ... EOF 输入此SO question 失败;程序在控制台上打开,但不输出任何内容。
  • 通过 -P 选项打开端口有效。然后我可以在 nc 环境中操作(类似于tg wiki),但我不确定在我的 Python 脚本中实现所有这些调用是否明智。

  • 我还发现了另一个将命令回显到 tg 中的脚本(忘记源代码),但它也不起作用(与上面的 <<EOF 类似的行为)

    #!/bin/bash
    to=Matthias_SG
    msg="test message"
    tgpath=/home/matthias/dvl/tg
    cd ${tgpath}
    (echo "add_contact +xxx Matthias SG"; echo "msg $to $msg") | ${tgpath}/bin/telegram-cli -k tg-server.pub
    

所以我的问题是: 我应该回到旧的pytg吗?我可以通过从 subprocess.call 或 popen 输入 stringIO 来修复 shell 脚本或将它们修改为 Python 吗?有没有人以强大的方式使用它?

背景

【问题讨论】:

    标签: python linux telegram


    【解决方案1】:

    第一步是创建bot 并获取token

    第二步是去获取chat_id:

    • 在聊天中写点东西
    • 访问https://api.telegram.org/bot<YourBOTToken>/getUpdates 并在message['chat']['id'] 键下获取chat_id

    最后一步是使用这段代码:

    import requests
    
    def telegram_bot_sendtext(bot_message):
    
       bot_token = ''
       bot_chatID = ''
       send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message
    
       response = requests.get(send_text)
    
       return response.json()
    
    
    test = telegram_bot_sendtext("Testing Telegram bot")
    print(test)
    

    Medium.com: How to create a Telegram bot, and send messages with Python提取的代码

    【讨论】:

      【解决方案2】:

      我宁愿使用包python-telegram-bot,它对我很有效。

      您可以找到 here 文档和一个简单的示例以开始使用。

      为了回复短信,可以在CommandHandler后面加一个MessageHandler如:

      updater.dispatcher.add_handler(MessageHandler(Filters.text, text_reply))
      
      def text_reply(bot, updater):
          text = update.message.text
      
          if text == 'ping':
              reply = 'pong'
      
          elif text == 'pong':
              reply = 'ping'
      
          # add any process to the text
      
          else:
              reply = "I only respond to ping pong"
      
          update.message.reply_text(reply)
      

      别忘了导入from telegram.ext import MessageHandler

      希望这有帮助!

      【讨论】:

        猜你喜欢
        • 2014-12-28
        • 2021-03-07
        • 2018-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-21
        • 2021-09-24
        相关资源
        最近更新 更多