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:
Way One: make the Python script connect to the Telegram APIs directly and send the message (https://core.telegram.org/api).
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.
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
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.
Telegram recently released their new Bot API which makes sending/receiving messages trivial. I suggest you also take a look at that and see if it fits your needs, it beats wrapping the client library or integrating with their MTProto API.
import urllib
import urllib2
# Generate a bot ID here: https://core.telegram.org/bots#botfather
bot_id = "{YOUR_BOT_ID}"
# Request latest messages
result = urllib2.urlopen("https://api.telegram.org/bot" + bot_id + "/getUpdates").read()
print result
# Send a message to a chat room (chat room ID retrieved from getUpdates)
result = urllib2.urlopen("https://api.telegram.org/bot" + bot_id + "/sendMessage", urllib.urlencode({ "chat_id": 0, "text": 'my message' })).read()
print result
Unfortunately I haven't seen any Python libraries you can interact directly with, but here is a NodeJS equivalent I worked on for reference.
Since version 1.05 you can use the -P option to accept messages from a socket, which is a third option to solve your problem. Sorry that it is not really the answer to your question, but I am not able to comment your question because I do not have enough reputation.
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}
Then put the script in the same folder than your python script, and give it +x permission with chmod +x tg.sh
And finally from python, you can do:
import subprocess
subprocess.call(["./tg.sh", "user#****", "message here"])
I'm working with pytg which could be found here:
A Python package that wraps around Telegram messenger CLI
it works pretty good. I already have a python bot based on that project
You can use safe_quit to terminate the connection instead since it waits until everything is done before closing the connection and termination the application
#!/bin/bash
cd /home/username/tg
echo "msg user#******** messagehere\nsafe_quit\n" | ./telegram
use this as a simple script and call it from python code as the other answer suggested.
I would recommend the first option.
Once you are comfortable with generating an AuthKey, you should start to get a handle on the documentation.
To help, I have written a detailed step-by step guide of how I wrote the AuthKey generation code from scratch here.
It's in vb.net, but the steps should help you do same in python.
Related
I am not yet so into Python and I have the following problem (I am studying a course of Python applied to security).
On my Windows 10 machine there is installed Python 2.7.17 version.
Then I have this very simple script:
#!/usr/env/bin python
import subprocess
command = "msg you have been hacked !!!"
# Popen() continue the program and doesn't wait that the command is completly finished to terminate the script execution:
subprocess.Popen(command, shell=True)
The problem is that when I try to execute it I am obtaining this error:
C:\Users\myuser\Desktop\python_evil>python execute_command.py
C:\Users\myuser\Desktop\python_evil>you inesistente o disconnesso
The error seems very strange to me (and it is half in english (you) and half in italian). Basically it says: you doesn'te exist or disconntected
Why? What is wrong? What am I missing? How can I fix this issue and correctly execute this command?
The error seems very strange to me (and it is half in english (you) and half in italian). Basically it says: you doesn'te exist or disconntected
The you comes from the command, which is why it appears in English. The rest comes from Windows, which is why it appears in Italian (your localized language).
If you try msg by itself in a command window, you get the usage info, which explains the problem:
Send a message to a user.
MSG {username | sessionname | sessionid | #filename | *}
[/SERVER:servername] [/TIME:seconds] [/V] [/W] [message]
username Identifies the specified username.
sessionname The name of the session.
sessionid The ID of the session.
#filename Identifies a file containing a list of usernames,
sessionnames, and sessionids to send the message to.
* Send message to all sessions on specified server.
/SERVER:servername server to contact (default is current).
/TIME:seconds Time delay to wait for receiver to acknowledge msg.
/V Display information about actions being performed.
/W Wait for response from user, useful with /V.
message Message to send. If none specified, prompts for it
or reads from stdin.
What happens is that msg you have been hacked !!! is interpreted by the shell as a msg command, where you is the (username or session name or session ID), and have been hacked !!! is the message. But there is no user on your system named you, and there is no login session with that name or ID, so the msg program produces an error - it can't determine who is supposed to see the message.
By the way: especially as someone studying security, you really, really should update your Python installation. The 2.x branch is no longer maintained, even for security reasons and the final ever release (of code frozen since jan 1) is in the pipeline. The most recent version on the website is 3.8.2.
I just started trying to connect to my broker through the FIX protocol.
The broker gave me:
an IP:port address to connect to
a "sendercompid"
a "targetcompid"
a password
I would like, as a first test, simply send a logon message to the broker and hopefully receive a message back from it. I would have thought this should be possible with a simple, small python script?
(ie im not interested in installing a fully fledge python engine / or use wrapper for c++ language such as quickfix)
edit:
to be more precise:
I found on SO example of doing (or trying) such thing in PHP, for instance:
$fp = fsockopen($host, $port, $errno, $errstr, 3.0);
if ($fp)
{
$request = "8=FIX.4.49=11235=A49=SENDER56=RECEIVER34=152=20130921-18:52:4898=0108=30141=Y553=user554=pass10=124";
echo $request;
fwrite($fp, "GET / HTTP/1.0\r\n" .
"Host: $host\r\n".
"Connection: close\r\n".
"Content-Length: " . strlen($request) . "\r\n" .
"\r\n" .
$request);
stream_set_timeout($fp, 2, 0);
$response = '';
while (!feof($fp))
{
$response .= fread($fp, 1024);
}
print "Response: ".$response . "<BR>\n";
fclose($fp);
}
Do you know which library i can use to simply communicate (ie send/retrieve) message to the FIX server in the same fashion in python?
Well, there's no standard python library for that.
You mentioned quickfix, what is a big project that seems maintained, and has documentation.
Looking for other third-party libraries, there is a smaller one, yet only for python2.6 or 2.7, named fixlib and currently hosted on github (the PyPI and bitbucket versions seem to be abandoned; the github version has been active 6 months ago). Major inconvenient: there is no documentation.
Looking at the code of these two libraries shows they are not exactly "small", so if you don't want to use any of them, as you will certainly have to rewrite similar code from scratch, you'd better forget about a "simple and small python script".
If you want to do a test in FIX protocol over a FIX connection you can try using the FIXRobot. FIXRobot allows to easily write the tests in python.
How could I send a string(shell script file name) from an android app to a python program on my pc, and have python execute the script named in said string?
I have the python script done... doThis(./openNetflix) will run the ./openNetflix script, which as you probably guessed opens Netflix.
How do I configure a python server to recieve a string and pass it to my doThis(scriptNameString) function?
I started writing a bit lengthy comment on this case, but when you are approaching chars limit for a comment it's good to convert it into an answer I guess!
Easiest way to do this task would be with one of many excellent python libraries for creating REST services. My personal favourite is bottle, and implementing this type of service in with bottle would be as simple as:
from bottle import route, run, template
#route('/execute/<command>')
def execute(command):
if command == "list_blogs":
// Do something 1
elif command == "format_c":
// Do something 2
run(host='localhost', port=79897)
This will not only provide you with the REST service, but will also put a iron wall between user input and actual execution, so the user input will not get mangled with the file you are trying to execute. Just remember to never use command variable anywhere outside of the if/else.
As you can notice this comes with a weakness - anyone with this link can call those functions and potentially cause denial of service, or maybe even actual damage. This is why it would be nice to have some sort of control and added security, to know that the request was made from valid client.
There are many ways to tackle this issue, i strongly encourage you to have a deeper look into those available. Very simple one would be to store on your server a dict of keys and salts, like that:
salts["here_you_put_random_hash_as_key"] = "and_here_the_salt"
And then you also store the salt and key for this specific client in the clients code. Then when client makes a request he includes his key and a checksum (which consists of md5 made from the command, clients salt key and, for example, current hour) as additional arguments. Then when you receive the request and all 3 variables, you try to create your own checksum using same data (so you pick the salt for client key provided and calculate md5 for that salt, current hour and command coming from the client) and if they match then you know that the request is valid.
I read the mails from my gmail account with the code following below.
import poplib
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('user') # result: '+OK send PASS'
pop_conn.pass_('password') # result: '+OK Welcome.'
print pop_conn.list()[1]
pop_conn.quit()
It shows me 1 message as expected.
However, if I run this script for the second time, I get 0 messages as result. On the server the message is still there and unread.
How can I get all the messages also running the script for the second time?
For me it behaves as an email client that doesn't download the same mail twice. Is there some flag to force the program to download everything again?
I use python 2.7.x on ubuntu 12.10
Are you sure that's all that you were doing when it happened? As far as I know, just using list() shouldn't do that, but if you used retr() to read the message contents too, then POP3 servers often mark the message and won't return it on further connections anymore.
You could try using IMAP instead, since it lets you specify the behavior in more detail, eg. you can tell it to not mark messages as seen and allows you to retrieve them more than once. Google supports IMAP and python has imaplib for using it.
I need to write code to reply when a particular message is seen in the hub chat.
I tried using PyDC but was not able to get it to work, some problem because it expects old wxpython libraries or something. T
he command line one works, but as far as I can see does not support chat. The GUI one tries to import shell from wx.lib.PyCrust but PyCrust has been renamed to wx.py. I tried importing shell from wx.py then the GUI started but was unable to connect to any hub. The command line one connects fine.
Is there any other way I can do what I want?
Eiskalt DC++ QT lets you write scripts in QTScript. I can use this to do what I need.