print udates in telegram via telethon - python

I am trying to print updates to my telegram acount . This is my code :
client = TelegramClient('session_name', api_id, api_hash, update_workers=4)
client.connect()
from telethon.tl.types import UpdateShortMessage, PeerUser
def callback(update):
print(1)
print('I received', update)
client.add_update_handler(callback)
whats wrong ? nothing prints .

First of all I suggest you add:
import logging
logging.basicConfig(level=logging.INFO)
So you can see what errors you are getting but can't yet see.
Significantly your program will end straight away because it never waits to receive any inbound messages. You will need to use something like client.loop.run_until_complete(somefunctionthattreadswater) at the end so that it hangs around until you press ctrl-C.

Related

how to terminate the handler after receiving a message? pyrogram python

instead of client.terminate I tried client.stop, disconnect but the program continues to work smoothly
from pyrogram import Client
from pyrogram.handlers import MessageHandler
app = Client(name='345674565245693979010')
messages = []
def log(client, message):
messages.append(message.text)
print(*messages)
client.terminate()
app.add_handler(MessageHandler(log))
app.run()
the log() function stops working after receiving the message as planned, but for some reason the program works smoothly!

MQTT will not publish over Python

I'm somewhat experienced when it comes to MQTT and in Python and this has baffled me for the last hour or so.
This is the script I'm working with:
#!/usr/bin/python
import json
import socket
import paho.mqtt.client as mqtt
client = mqtt.Client()
try:
client.connect('localhost', 4444)
except:
print "ERROR: Could not connect to MQTT."
mode_msg = {
'mode': '2'
}
client.publish("set", payload=json.dumps(mode_msg), qos=2, retain=False)
This code won't run. I have no idea why. Most baffeling is, when I add " client.loop_forever()" at the bottom, it will run...
I've tried adding "client.disconnect()" at the bottom as well to get it to disconnect properly, but it all won't help. Is there something I'm missing right now?
It looks like you are trying to publish a single message, the paho client has a specific message to do just that.
#!/usr/bin/python
import paho.mqtt.publish as publish
mode_msg = {
'mode': '2'
}
publish.single("paho/test/single", payload=json.dumps(mode_msg), qos=2, hostname="localhost", port=4444)
The problem with your original code is that you are you need to run the network loop to handle the publish (and because you are publishing with qos=2 which needs to reply to the broker acknowledgement of the publish), you can do it as follows:
#!/usr/bin/python
import json
import paho.mqtt.client as mqtt
run = True
def on_publish(client, userdata, mid):
run = False;
client = mqtt.Client()
client.on_publish = on_publish
try:
client.connect('localhost', 4444)
except:
print "ERROR: Could not connect to MQTT."
mode_msg = {
'mode': '2'
}
client.publish("set", payload=json.dumps(mode_msg), qos=2, retain=False)
while run:
client.loop()
client.disconnect()
client.loop_forever() won't work because it does exactly what the name suggests, it loops forever, so would never reach your client.disconnect(). This uses the on_publish callback to break out of the loop calling client.loop() and then disconnect.
The paho.mqtt client library is built around an event loop that must run to properly process and maintain the MQTT protocol.
Thus to make things happen you need to call some of the loop() functions, as mentioned in the documentation

How to make a Tornado websocket client recieve server notifications?

I'm trying to make an application that normally sends a request to a server and receives a response. If it would have been only that, I'd go with HTTP and call it a deal. But some requests to the server make a change for other clients, so I want the server to send all the affected clients a message that they should update.
For that, I've chosen WebSockets protocol and the Tornado library to work with it using Python. The simple message exchange was pretty straightforward, despite the asynchrony. However, the WebSocket client is really not that configurable and I've been struggling to make a client listen for incoming notifications without this interrupting the main message exchange.
The server part is represented by the tornado.websocket.WebSocketHandler, which has an on_message method:
from tornado.websocket import WebSocketHandler
class MyHandler(WebSocketHandler):
def on_message(self, message):
print('message:', message)
And I'd like something like that in the client part, which is only represented by a function tornado.websocket.websocket_connect (source). This function initiates a tornado.websocket.WebSocketClientConnection (source) object, which has an on_message method, but due to the entangled asynchronous structure, I haven't been able to override it properly, without breaking the main message exchange.
Another way I tried to go was the on_message_callback. This sounded like something I could use, but I couldn't figure out how to use it with read_message. This was my best attempt:
import tornado.websocket
import tornado.ioloop
ioloop = tornado.ioloop.IOLoop.current()
def clbk(message):
print('received', message)
async def main():
url = 'server_url_here'
conn = await tornado.websocket.websocket_connect(url, io_loop = ioloop, on_message_callback=clbk)
while True:
print(await conn.read_message()) # The execution hangs here
st = input()
conn.write_message(st)
ioloop.run_sync(main)
With this being the server code:
import tornado.ioloop
import tornado.web
import tornado.websocket
import os
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
self.write_message('hello')
def on_message(self, message):
self.write_message(message)
self.write_message('notification')
if __name__ == "__main__":
app = tornado.web.Application([(r"/", EchoWebSocket)])
app.listen(os.getenv('PORT', 8080))
tornado.ioloop.IOLoop.current().start()
I don't know what's going on here. Am I even going in the right direction with this?
There are two issues here:
Use on_message_callback or loop on await read_message(), but not both. If you give a callback the messages will only be passed to that callback and not saved for use by read_message.
input is blocking and doesn't play well with Tornado. It's fine in this little toy demo but if you want to do something like this in production you'll probably want to do something like wrap a PipeIOStream around sys.stdin and use stream.read_until('\n').

tornado-redis: Why the 'listen' and the 'brpop' of tornado-redis can't work at the same time

The code like this:
from tornadoredis import Client
from tornado.ioloop import IOLoop
from tornado.gen import coroutine, Task
rds = Client()
#coroutine
def listen_pub():
def handle(msg):
print msg
yield Task(rds.subscribe, channels='pub')
rds.listen(handle)
#coroutine
def listen_list():
while True:
res = yield Task(rds.brpop, keys='list')
print res
def test():
listen_pub()
listen_list()
test()
IOLoop.current().start()
When I running the code above, only 'listen_list' can receive messages.
Why the 'listen_list' doesn't work?
How can I listen the message from LIST and PUB/SUB at the same time?
Take a look at the redis documentation:
A client subscribed to one or more channels should not issue
commands, although it can subscribe and unsubscribe to and from
other channels. The reply of the SUBSCRIBE and UNSUBSCRIBE operations
are sent in the form of messages, so that the client can just read a
coherent stream of messages where the first element indicates the type
of message.
You have to use two connection clients.
Source: http://redis.io/topics/pubsub

Typed in message breaks when receiving a message

i am doing a little client\server threading chat and I have a problem,
if one of the sides is receiving a message while typing one it's breaks the message that is being typed here is a image for illustration
Here is the threading code:
import threading
import socket
class sendTread(threading.Thread):
def __init__(self,soc):
threading.Thread.__init__(self,name='sender')
self.s=soc
def run(self):
while True:
self.s.send(bytes(str(input('>>> ')), 'UTF-8'))
print('sent.')
class recvTread(threading.Thread):
def __init__(self,soc):
threading.Thread.__init__(self,name='recver')
self.s=soc
def run(self):
while True:
data=self.s.recv(1024)
print('\nrecv:',str(data)[2:len(str(data))-1],end="\n>>> ")
I understand why it happens but I have no idea how to fix it and I would be happy
for some help and Suggestions :)
You have to approach the problem as a concurrent problem. In your case, the console is a shared resource and what is happening is that the thread of the receiver is using it while is still "taken" by the sender.
You can add a lock that protect the print statements, you can find details about it here:
http://docs.python.org/2/library/threading.html#lock-objects

Categories