I've to send xmpp based chat client (hipchat) and I'm using xmpp.py for this purpose. For now, I'm trying to send message from shell. Following are the statements that I'm executing from the shell:
>>> import xmpp
>>> jid = xmpp.protocol.JID('99999_9999#chat.hipchat.com')
>>> cl=xmpp.Client(jid.getDomain(),debug=[])
>>> cl.connect()
'tls'
>>> cl.auth(jid.getNode(),'password')
'sasl'
>>> cl.send(xmpp.protocol.Message('99999_9999#chat.hipchat.com','hey!'))
'3'
I'm using the same jabber id for authentication and as a receiver. I'm also online in chat room but I don't get any message. What's missing?
Some older XMPP servers need an initial presence state.
The state is sent using the following call before the cl.send:
cl.SendInitPresence(requestRoster=0)
See also the xsend example from xmpppy home page:
http://xmpppy.sourceforge.net/examples/xsend.py
I was missing the typ parameter. Adding it with value chat solved the problem:
cl.send(xmpp.protocol.Message('99999_9999#chat.hipchat.com','hey!', typ='chat'))
Related
I am using ejabberd in python and I found a method to send the messages but how to get them messages or receive those messages in my python console please suggest me some method or way to do this.
to send the message my code is
import xmlrpc.client as xmlrpclib
server_url = 'http://127.0.0.1:5180/xmlrpc/'
server = xmlrpclib.ServerProxy(server_url)
EJABBERD_XMLRPC_LOGIN = {'user':'yatish', 'server':'localhost', 'password':'1234', 'admin':False}
def ejabberdctl(command, data):
fn = getattr(server, command)
print(fn.__dict__,'>>>>>>>>>>')
return fn(EJABBERD_XMLRPC_LOGIN, data)
result = ejabberdctl('send_message', {"type":"chat","from":"yatish#localhost","to":"1#localhost",
"subject":"backend subject","body":"Hey this is message from python1"})
here I can send messages from yatish#localhost to 1#localhost user I want to get all the messages received of the 1#lcoalhost, can you please suggest me some method I have checked all the docs and google by my side but unable to get some ay to receive all those messages in python. if the messages received the client should connected and receive the messages relatime.
thanks
You wrote a XMLRPC client to use the ejabberd's "send_message" administrative command to perform this task.
But there isn't any admin command in ejabberd to check or read XMPP messages.
I suggest you a different approach: forget about using XMLRPC or ejabberd commands. Instead, write a small XMPP client (there are libraries in python for that, see https://xmpp.org/software/libraries/ ).
Your XMPP client should:
login to the FROM account
send the message
logout
Then write another small client that
logins to the TO account, with a possitive presence number
ejabberd will immediately send him the offline messages that were stored
do whatever with those messages, and logout
If you are able to write those XMPP clients in your prefered language (Python or whatever), you can use those clients with any XMPP server: ejabberd, or any other that you may want to install in other machines, or in the future.
I'm using the sdk of the service bus to send to a queue and listen for the answer in another, but I can not find valid examples of how to make that flow. My biggest difficulty is being able to set reply_to and reply_to_group_id, as I did in the old versions directly in the MessageProperties, now in the class Message I am in doubt with what to inform in the index 'message' to achieve this objective
The Message class has a property called properties which is an instance of uamqp.message.MessageProperties which has the reply_to (and reply_to_group_id) property that you are looking for.
from azure.servicebus import Message
message = Message(
body="Hello World!"
)
message.properties.reply_to="replyTo"
message.properties.reply_to_group_id="replyGroupId"
You can read more about AMQP Request-Response Operations with Service Bus in the docs.
to add to #pramodValavala's answer, here's how you do it with the v7.0 https://pypi.org/project/azure-servicebus/7.0.0/
from azure.servicebus import ServiceBusMessage
message = ServiceBusMessage("hello world")
# set using application_properties
message.application_properties = {'reply_to': 'abc'}
I'm running some scripts and looking for an easy way to ping my phone once the script has finished running.
Doing some research on the web, I've seen ways of sending messages using Slack, Push bullet, twilio, email etc.
I am looking for recommendations for an easy way to send a ping/message from python to my phone.
Easy in the sense it dose not require considerable configuring of outside accounts or pay services.
I have found a much easier way, but it doesn't works on Linux. Here is a link for more details.
First you have to install notify_run:
pip install notify_run
Then you have to register:
notify-run register
It will give you a QR code (on windows the QR code doesn't works) and a link, which will take you to a website, there press the "Subscribe on this device" (Maybe you will have to refresh the site)
Then use this code:
from notify_run import Notify
notify = Notify()
notify.send('any message you want')
U can try cmd: pip install telegram-send and just send a message to your Telegram bot.
Create your telegram bot at BotFather, take a token from there, paste it to
cmd: telegram-send --configure
Usage:
import telegram_send
telegram_send.send(messages=["Hello world"])
I found this much better than any other push notification.
For more info:
Link1
Link2
I've tried a Twilio, but it's complicated and I don't think it can send you messages for free (anymore). Telegram seems an easy solution. To extend to the answer of #Nick PV, here are the steps I, as a Telegram beginner, took:
1) Get a Telegram account (free) using your phone number
Web: https://web.telegram.org
Also download the Telegram Andriod. Of course, you want the notifications on your phone after all
2) Go into settings (web or app) and set a username
This is needed to obtain an id which your bot will use to send messages to
3) Send a message to RawDataBot to get your id
Just search for RawDataBot and send any message (hi will do). Take a note of your id.
4) Create your bot (which you'll command with HTTP requests)
Now search for BotFather and send the message /start. Help is displayed. Send the message /newbot and follow the instructions. Take a note of your token to access the HTTP API
5) Send the API request using Python
You could install and use telegram-send, but if you are like me and you prefer the generic library requests which will give you the experience to handle any HTTP API, this is how to do it:
import requests
token = "token_from_step_4"
url = f"https://api.telegram.org/bot{token}"
params = {"chat_id": "id_from_step_3", "text": "Hello World"}
r = requests.get(url + "/sendMessage", params=params)
Links:
Telegram bots: https://core.telegram.org/bots
API Docs sendMessage https://core.telegram.org/bots/api#sendmessage
In the end, the easiest way I found was using Slack. It takes one Python function (about 6 lines) and an Slack account.
More details can be found here on medium
I tried pushsafer and notify-run without success on my computer (Linux Mint 19.3 tricia)
On my computer, only Slack works properly. This post comes from this Youtube video where you will see the full process in Video.
What you need first is Slack application on your device (iOs, Android, ...) and create an Slack account (if not done)
Tuto :
Create a workspace and an application (see details in this video. Sorry, I did not put the substeps here but I put this answer as a Community wiki in order to let you finish what I started :) )
Install the python library pip3 install sandesh
pip3 install sandesh
Get your webhook => https://hooks.slack.com/services/blablabla
Use this sample to send a message to Slack :
python code:
import sandesh
sandesh.send("This is my test", webhook="<put here the https link of your webhook>")
You can find the open source sandesh python module here in gitHub
You already mentioned it in your answer but Pushbullet is pretty easy:
Create a pushbullet account on their website using a gmail (I recommend not using your main one).
Install the android app and login with the same gmail. (Despite what their instructions say, you do not need to give any permissions to the Android app. Not even notifcations.)
From the website go to settings -> Account -> Create Access Token. Copy this token to use in your python script.
From python (yes you need the "py" at the end of the name)
pip install pushbullet.py (see project on pypi)
import pushbullet
pb = pushbullet.PushBullet(YOUR_ACCESS_TOKEN)
push = pb.push_note('Some Title', 'Some message you want to send')
This will pop up a notification on your Android phone with the message you specified. Works from Windows or Linux.
Using firebase fcm
One of the easiest and reliable way is to use Firebase Cloud Messaging for sending push notifications.
You can get server key from the firebase console after creating your project.
You can get device token by generating it in your device
see: https://firebase.google.com/docs/cloud-messaging/android/client (iOS, android and web)
## Install request module by running ->
# pip3 install requests
# Replace the deviceToken key with the device Token for which you want to send push notification.
# Replace serverToken key with your serverKey from Firebase Console
# Run script by ->
# python3 fcm_python.py
import requests
import json
serverToken = 'your server key here'
deviceToken = 'device token here'
headers = {
'Content-Type': 'application/json',
'Authorization': 'key=' + serverToken,
}
body = {
'notification': {'title': 'Sending push form python script',
'body': 'New Message'
},
'to':
deviceToken,
'priority': 'high',
# 'data': dataPayLoad,
}
response = requests.post("https://fcm.googleapis.com/fcm/send",headers = headers, data=json.dumps(body))
print(response.status_code)
print(response.json())
Hope you found helpful
I am using the apns library to send push notifications to my iPhone. While I'm successfully receiving push notifications to my device, the script asks for the Certificate password every time I run it to send a push notification. I'm trying to figure out a way to include the password somehow in the code but have been unsuccessful so far.
I'm running the example code from their repository:
from apns import APNs, Payload
apns = APNs(use_sandbox=True, cert_file='TestCert.pem', key_file='TestKey.pem')
# Send a notification
token_hex = '<token hidden for obvious reasons>'
payload = Payload(alert="Hello World!", sound="default", badge=1)
apns.gateway_server.send_notification(token_hex, payload)
I've also been checking the library source code but it doesn't seem to have any useful option.
I've finally found a decent solution on the answer to this question.
I've also found out that from Python 3.3 it's possible to use the password adding the method SSLContext.load_cert_chain(certfile, keyfile, password) in the function that opens the SSL connection.
Is there an ejabberd python library wherein I can register user to ejabberd from python programmatically?
Right now I'm executing "ejabberdctl register" command using the python commands module.
XMPP XEP-0077
If you have activated mod_register for In-Band registration on your Ejabberd server, then, as pointed out by #Drake, you can use an XMPP library to register users.
In Python, I would recommend Sleek XMPP. The Getting started examples are, well, a good starting point.
HTTP
If you have activated mod_register_web then you can send a HTTP POST request to http://<SERVERNAME>:5280/admin/server/<VIRTUALHOSTNAME>/users/. This URL expects the following 3 parameters:
newusername
newuserpassword
addnewuser
where the expected value for the addnewuser param seems to be the string "Add User".
Assuming you have an ejabberd admin user called user and with password password, using the requests HTTP library for Python, you could do something like the following:
import requests
from requests.auth import HTTPBasicAuth
server = "NAME OF YOUR EJABBERD SERVER"
virtualhost = "NAME OF YOUR EJABBERD HOST"
url = "http://%s:5280/admin/server/%s/user/" % (server, virtualhost)
auth = HTTPBasicAuth("user", "password")
data = {
'newusername': "new_user",
'newuserpassword': "new_password",
'addnewuser': "Add User"
}
resp = requests.post(url, data=data, auth=auth)
assert resp.status_code == 200
ejabberd is a Jabber/XMPP instant messaging server. That means you can make use of any XMPP module, like xmppy.
Also, check this thread: Which is the most mature Python XMPP library for a GChat client?.