使用Telegram发送消息-API还是CLI? [英] Sending messages with Telegram - APIs or CLI?

查看:1183
本文介绍了使用Telegram发送消息-API还是CLI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够向Telegram中的群聊发送消息.我想运行一个python脚本(该脚本可以执行一些已运行的操作),然后,如果某些参数具有某些值,则该脚本应通过Telegram向群聊发送消息.我正在使用Ubuntu和Python 2.7

I would like to be able to send a message to a group chat in Telegram. I want to run a python script (which makes some operations that already works) and then, if some parameters have some values the script should send a message to a group chat through Telegram. I am using Ubuntu, and Python 2.7

我认为,如果我没记错的话,我有两种方法可以做到这一点:

I think, if I am not wrong, that I have two ways to do that:

方法二:使Python脚本调用Telegram的CLI( https://github.com/vysheng/tg),为此传递一些值,然后消息由Telegram的CLI发送.

Way Two: make the Python script call the Telegram's CLI (https://github.com/vysheng/tg), pass some values to this and then the message is sent by the Telegram's CLI.

我认为第一种方法更长,所以一个好主意可能是使用第二种方法.

I think that the first way is longer, so a good idea might be using the Way Two.

在这种情况下,我真的不知道该如何进行. 我对Linux中的脚本不了解很多,但是我尝试这样做:

In this case I really don't know how to proceed. I don't know lots about scripts in linux, but I tried to do this:

#!/bin/bash
cd /home/username/tg
echo "msg user#******** messagehere" | ./telegram
sleep 10
echo "quit" | ./telegram

这工作一半:它正确发送了消息,但随后该过程保持打开状态.第二个问题,我对如何从python调用以及如何向此脚本传递一些值一无所知.我想传递给脚本的值是"messagehere"变量:这是一条100/200个字符的消息,是从python脚本内部定义的.

this works at a half: it sends the message correctly, but then the process remains open. And second problem, I have no clue on how to call that from python and how to pass some value to this script. The value that I would like to pass to the script is the "messagehere" var: this would be a 100/200 characters message, defined from inside the python script.

有人对此有任何线索吗? 感谢您的答复,我希望这对其他人可能有用.

Does anyone has any clues on that? Thanks for replies, I hope this might be useful for someone else.

推荐答案

首先创建一个 bash脚本电报,名为tg.sh:

First create a bash script for telegram called tg.sh:

#!/bin/bash
now=$(date)
to=$1
subject=$2
body=$3
tgpath=/home/youruser/tg
LOGFILE="/home/youruser/tg.log"
cd ${tgpath}
${tgpath}/telegram -k ${tgpath}/tg-server.pub -W <<EOF
msg $to $subject
safe_quit
EOF
echo "$now Recipient=$to Message=$subject" >> ${LOGFILE}
echo "Finished" >> ${LOGFILE}

然后将脚本与python脚本放在同一文件夹中,并通过chmod +x tg.sh

Then put the script in the same folder than your python script, and give it +x permission with chmod +x tg.sh

最后通过python,您可以执行以下操作:

And finally from python, you can do:

import subprocess
subprocess.call(["./tg.sh", "user#****", "message here"])

这篇关于使用Telegram发送消息-API还是CLI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆