Mat*_*uer 13 python linux telegram
我想通过 Telegram 从 Python 脚本发送消息。我试图通过电报 cli 做到这一点,包括来自 vysheng的原始版本和来自luckydonald的补丁版本。有了他们,我可以成功地向我的手机发送消息。我的问题是:
<<EOF ... EOF在这个SO 问题中通过as输入失败;该程序在控制台上打开,但不输出任何内容。通过 -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
Run Code Online (Sandbox Code Playgroud)所以我的问题是:我应该回到旧的 pytg 吗?我可以通过从 subprocess.call 或 popen 输入 stringIO 来修复 shell 脚本或将它们修改为 Python 吗?有没有人以稳健的方式使用它?
jua*_*mah 23
第一步是创建一个机器人并获取token.
第二步是去获取chat_id:
https://api.telegram.org/bot<YourBOTToken>/getUpdates并获取chat_id密钥message['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)
Run Code Online (Sandbox Code Playgroud)
从Medium.com 中提取的代码:如何创建 Telegram bot,并使用 Python 发送消息
我宁愿使用该包python-telegram-bot,它对我来说效果很好。
您可以在此处找到文档和简单的入门示例。
为了回复短信,您可以在 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)
Run Code Online (Sandbox Code Playgroud)
不要忘记导入from telegram.ext import MessageHandler.
希望这有帮助!
| 归档时间: |
|
| 查看次数: |
25431 次 |
| 最近记录: |