I have created a chat website using django channels and want to play some audio as notification alert when any message was send / received between users.
can anyone could help me in resolving it ?
Call this function in javascrict in your "message received" event.
function playSound() {
var audio = new Audio('audio_file.mp3');
audio.play();
}
Related
I'm trying to get a var to my consumers.py to send data to the client in real time as a function does API calls and returns that to the browser.
I know channels needs Redis to function, but why? Why can we not just pass a list as it's built to the consumers class or any variable for that matter? From another answer: to store the necessary information required for different instances of consumers to communicate with one another. But what if I only will use one websocket connection, and only one user is allowed to be logged in at a time? This will be locally hosted only and the function is outside of consumers.py that returns the data so subscribing to groups may be where I need these.
Am I missing something or is redis / memurai a must here? I just can't help but to feel there's an easier way.
I ended up using server side events (SSE), specifically django-eventstream, and so far it's worked great as I didn't need the client to interact with the server, for a chat application this would not work.
Eventstream creates an endpoint at /events/ the client can connect to and receive a streaming http response.
Sending data from externalFunc.py:
send_event('test', 'message', {'text': 'Hello World'})
Event listener in HTML page:
var es = new ReconnectingEventSource('/events/');
es.addEventListener('message', function (e) {
console.log(e.data);
var source = new EventSource("/events/")
var para = document.createElement("P");
const obj = JSON.parse(event.data)
para.innerText = obj.text;
document.body.appendChild(para)
}, false);
es.addEventListener('stream-reset', function (e) {
}, false);
I would like to write a bot that will listen to the specific chat and save messages to the local storage.
After starting the bot app, everything works properly, but after some time I can see such information in the logs:
pyrogram.client {
'_': 'types.UpdatesTooLong'
}
Immediately after this log, my userbot stops hearing any message from any user.
How can I fix this and handle such case updatesTooLong ?
I was wondering, if it is possible to connect (as an admin) with a user and to write messages? I already modified the message-table in the database, however, the message does only appear after reloading the whole website - which is not the optimal outcome. I appreciate every hint. Thank you.
You have to use a pub/sub service to get notification on the client side when a message is sent in server side
A good start is pusher.com service, in your server side code, you will run this example code whenever you send a message to your user:
pusher.trigger('my-channel', 'my-event', {
'message': 'hello world'
})
and in your client side, you add a code that listen to the above channel/topic and act accordingly
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert('Received my-event with message: ' + data.message);
});
I am planning to build a home automation system where IoT devices communicate with the MQTT broker.The system also involves a Django web server that serves API for ios/android devices. I will describe an example of what I want to implement.
An API call is made from mobile app to Django server to turn ON a device. When such API request is made to Django, it should push 'Turn ON' data to IoT device via MQTT protocol.
Also, IoT devices send some real time data to the MQTT broker. Upon receiving such data I want to send push notifications to a mobile app via apns/fcm.
How can I implement this?. Will Django channels serve the purpose or should I code my Django server to act as an MQTT client and communicate with the MQTT broker?. Or is there any other methods to implement this.
well, i did a little project on paho-MQTT it's a nice experience with google chrome extension MQTTLens.(you should try this if u aren't using this already)
in your case, I think you can use rest-framework of Django for building an API and on the front-end, you can use crispy-form to make ON-OFF signals and this will directly communicate to the views of Django in which you can write the client and subscriber details.
lets focus on An API call is made from mobile app to Django server to turn ON a device. When such API request is made to Django, it should push 'Turn ON' data to IoT device via MQTT protocol.
you can make views which response to the API call from any devices for that you can check django-rest-framework this is the best option that we have.
and now IoT devices send some real time data to the MQTT broker
for this, you can check Google's this artical. MQTT broker can be handed with the Django views easily and this process not very complex if you use the modular structure with Django's DRY concpet.
on the other hand, you can also make different views for just client or for broker it's up to you but i think this approach will take a long time to devlope such application I don't know about mobile development so i can't help you with that :(.
You can handle the task using JavaScript. I have experience in implementing MQTT protocol in Django and Django-REST projects using JavaScript. You should embed a JavaScript code block in your frontend file (in my case, HTML). First, you should call the Paho-MQTT jQuery package in your file.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.2/mqttws31.min.js"></script>
Then add this block of code.
#parameters
var hostname = "mqtt.eclipse.org"; #There are different brokers. You should enter the broker's hostname.
var port = 80; #The port number can be different based on a TLS or non-TLS connection.
var ClientID = "ClientID_" + parseInt(Math.random()*100);
#Create a client instance
var client = new Paho.MQTT.Client(hostname, Number(port), ClientID);
#Set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
#Connect the client
client.connect(
{onSuccess: onConnect}
);
#Called when client connects
function onConnect() {
#Once a connection has been established, make a subscription and send a message
console.log("onConnect");
client.subscribe("subTopic");
alert("Connected.");
}
#Called when the client loses its connection
function onConnectionLost(responseObject){
if(responseObject.errorCode != 0){
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
#Called when a message arrives
function onMessageArrived(message) {
console.log("Message arrived: topic=" + message.destinationName + ", message=" + message.payloadString);
if (message.destinationName == "subTopic") {
#Do something
}
By using the code your application will be connected to the broker and listen to one or multiple topics. It means you can get sensors' data realtime. This necessitates to publish sensor's data on your hardware device, say ESP module or Raspberry PI.
It is very likely that you want to send commands from your application to the actuators to turn them on or off. For doing that you need to publish some messages from your application that your hardware will listen to.
Assume you have a toggle switch that you want to publish a message by toggling that.
<label id="switch{{ device.unique_id }}" class="switch">
<input id="state{{ device.unique_id }}" type="checkbox" onclick="publish('{{ device.unique_id }}')">
<span class="slider round"></span>
</label>
The above HTML block should reside into a django for block. Then you should write the publish onclick function to call that on toggling the switch. You can see an example of such a function below.
function publish(x) {
if(!client){
return;
}
var status = document.getElementById(x);
if (status.innerHTML == 'ON'){
status.innerHTML = 'OFF';
var message = new Paho.MQTT.Message("TurnOFF");
message.destinationName = "pubTopic";
client.send(message);
} else {
status.innerHTML = 'ON';
var message = new Paho.MQTT.Message("TurnON");
message.destinationName = "pubTopic";
client.send(message);
}
}
x in the publish function is the id that is embedded in the HTML file. To receive your published messages you should listen to the specific topic(s) on your hardware device.
I would like to create a Slack bot to answer some simple question or perform some task on the server. Here is what I have tried
token = "i-put-my-bot-token-here" # found at https://api.slack.com/#auth)
sc = SlackClient(token)
sc.api_call("chat.postMessage", channel="magic", text="Hello World!")
It was posted as the Slackbot and not the bot account that I created?
Also if I were to listen the message, according to the python library it says
if sc.rtm_connect():
while True:
print sc.rtm_read()
time.sleep(1)
else:
print "Connection Failed, invalid token?"
Or should I use incoming webhook instead?
As you can see here this call accepts an argument 'as_user' which can be true. If you set it as true, messages will be posted as the bot you created.
I'm in the middle of creating a bot right now as well. I found that if you specified as_user='true', it would post as you, the authed user. If you want it to be your bot, pass in the name of our bot and other options like emoji's like so:
sc.api_call(
'chat.postMessage',
username='new_slack_bot',
icon_emoji=':ghost:',
as_user='false',
channel='magic',
text='Hello World!'
)
Check emoji cheat sheet for more.
Then, if you want to listen to events, like questions or commands, try intercepting the messages that are sent in. Example found on this post:
while True:
new_evts = sc.rtm_read()
for evt in new_evts:
print(evt)
if "type" in evt:
if evt["type"] == "message" and "text" in evt:
message=evt["text"]
# write operations below to receive commands and respond as you like