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
Related
I wan to make a chatbot that will automatically reply . it will collect reply from client.listen and then decide the reply to the user.
from fbchat import log, Client
# Subclass fbchat.Client and override required methods
class EchoBot(Client):
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
# If you're not the author, echo
if author_id != self.uid:
self.send(message_object, thread_id=thread_id, thread_type=thread_type)
client = EchoBot("myaccount", "mypassword")
client.listen()
It worked fine until today.
Even it receive the message.the program still will stuck in client.listen
The output that i receive is this
Logging in myAccount...
Login of myAccount successful.
Listening...
When i try to contact my account , it still wont give me reply but it just stuck in client.listen
the output i wan to get is it will collect info from client.listen() and give me reply.
I believe that facebook has changed the structure of the website (id's, classes...) where fbchat library was scraping data from (Keep in mind that fbchat is not an official facebook library). This can happen with any API that is not official. I have hosted my bot 24/7 and all of sudden it stopped working. Your code is perfectly correct. From what I have tested so far I can tell that EchoBot class stopped working with all of it's event listeners, but at the other hand you can still send messages with client.send(...) We can only hope that developers of fbchat library will fix this soon.
See here for more info: https://github.com/carpedm20/fbchat/issues/483
2020 UPDATE
The issue was fixed in new version of fbchat 1.9.6.
Just update the module with:
pip install fbchat --upgrade
Hi I have an issue integrating slack custom bot-user into my slack app, based on python-slackclient documentation python-slackclient
to use the RTM
import time
from slackclient import SlackClient
token = "xoxp-xxxxxxxxx"# found at https://api.slack.com/web#authentication
sc = SlackClient(token)
if sc.rtm_connect():
while True:
print sc.rtm_read()
time.sleep(1)
else:
print "Connection Failed, invalid token?"
that code is working for bot-user token, but since I use oauth, I need to connect RTM using the bot_access_token everytime user install my app to act on behalf my app to the added team
any solution or example how to do it?
Cheers,
Your question is had to understand. You wrote:
since I use oauth, I need to connect RTM using the bot_access_token everytime user install my app to act on behalf my app to the added team
The access token you're using here...
token = "xoxp-xxxxxxxxx"# found at https://api.slack.com/web#authentication
...should be the same as the access token that is associated with your bot. (You should not make your bot use your own personal access token!) You can get an access token for your bot at https://my.slack.com/services/new/bot (assuming you're logged into Slack in the browser with which you follow that link).
If you participate in multiple Slack "teams" (a Slack "team" being basically a company), you'll need to set up a separate bot for each "team". Each bot will have a different access token. To pass the correct access token in to your bot, you could add a command-line parameter, or read the token from an environment variable, or read it from disk, among other options.
You can loop over tokens for connecting if you are planning to setup bot
for multiple teams, then your code can be converted to :-
clients = [SlackClient(token) for t in tokens]
for client in clients:
client.rtm_connect()
while True:
for client in clients:
print client.rtm_read()
time.sleep(1)
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.
I'm new to Python, new to the jira-python library, and new to network programming, though I do have quite a bit of experience with application and integration programming and database queries (though it's been a while).
Using Python 2.7 and requests 1.0.3
I'm trying to use this library - http://jira-python.readthedocs.org/en/latest/ to query Jira 5.1 using Python. I successfully connected using an unauthenticated query, though I had to make a change to a line in client.py, changing
I changed
self._session = requests.session(verify=verify, hooks={'args': self._add_content_type})
to
self._session = requests.session()
I didn't know what I was doing exactly but before the change I got an error and after the change I got a successful list of project names returned.
Then I tried basic authentication so I can take advantage of my Jira permissions and do reporting. That failed initially too. And I made the same change to
def _create_http_basic_session
in client.py , but now I just get another error. So problem not solved. Now I get a different error:
HTTP Status 415 - Unsupported Media Type
type Status report
message Unsupported Media Type
description The server refused this request because the request entity is in
a format not` `supported by the requested resource for the requested method
(Unsupported Media Type).
So then I decided to do a super simple test just using the requests module, which I believe is being used by the jira-python module and this code seemed to log me in. I got a good response:
import requests
r = requests.get(the_url, auth=(my username , password))
print r.text
Any suggestions?
Here's how I use the jira module with authentication in a Python script:
from jira.client import JIRA
import logging
# Defines a function for connecting to Jira
def connect_jira(log, jira_server, jira_user, jira_password):
'''
Connect to JIRA. Return None on error
'''
try:
log.info("Connecting to JIRA: %s" % jira_server)
jira_options = {'server': jira_server}
jira = JIRA(options=jira_options, basic_auth=(jira_user, jira_password))
# ^--- Note the tuple
return jira
except Exception,e:
log.error("Failed to connect to JIRA: %s" % e)
return None
# create logger
log = logging.getLogger(__name__)
# NOTE: You put your login details in the function call connect_jira(..) below!
# create a connection object, jc
jc = connect_jira(log, "https://myjira.mydom.com", "myusername", "mypassword")
# print names of all projects
projects = jc.projects()
for v in projects:
print v
Below Python script connects to Jira and does basic authentication and lists all projects.
from jira.client import JIRA
options = {'server': 'Jira-URL'}
jira = JIRA(options, basic_auth=('username', 'password'))
projects = jira.projects()
for v in projects:
print v
It prints a list of all the project's available within your instance of Jira.
Problem:
As of June 2019, Atlassian Cloud users who are using a REST endpoint in Jira or Confluence Cloud with basic or cookie-based authentication will need to update their app or integration processes to use an API token, OAuth, or Atlassian Connect.
After June 5th, 2019 attempts to authenticate via basic auth with an Atlassian account password will return an invalid credentials error.
Reference: Deprecation of basic authentication with passwords for Jira and Confluence APIs
Solution to the Above-mentioned Problem:
You can use an API token to authenticate a script or other process with an Atlassian cloud product. You generate the token from your Atlassian account, then copy and paste it to the script.
If you use two-step verification to authenticate, your script will need to use a REST API token to authenticate.
Steps to Create an API Token from your Atlassian Account:
Log in to https://id.atlassian.com/manage/api-tokens
Click Create API token.
From the dialog that appears, enter a memorable and concise Label for your token and click Create.
Click Copy to clipboard, then paste the token to your script.
Reference: API tokens
Python 3.8 Code Reference
from jira.client import JIRA
jira_client = JIRA(options={'server': JIRA_URL}, basic_auth=(JIRA_USERNAME, JIRA_TOKEN))
issue = jira_client.issue('PLAT-8742')
print(issue.fields.summary)
Don't change the library, instead put your credentials inside the ~/.netrc file.
If you put them there you will also be able to test your calls using curl or wget.
I am not sure anymore about compatibility with Jira 5.x, only 7.x and 6.4 are currently tested. If you setup an instance for testing I could modify the integration tests to run against it, too.
My lucky guess is that you broke it with that change.
As of 2019 Atlassian has deprecated authorizing with passwords.
You can easily replace the password with an API Token created here.
Here's a minimalistic example:
pip install jira
from jira import JIRA
jira = JIRA("YOUR-JIRA-URL", basic_auth=("YOUR-EMAIL", "YOUR-API-TOKEN"))
issue = jira.issue("YOUR-ISSUE-KEY (e.g. ABC-13)")
print(issue.fields.summary)
I recommend storing your API Token as an environment variable and accessing it with os.environ[key].
I am trying to put together a bash or python script to play with the facebook graph API. Using the API looks simple, but I'm having trouble setting up curl in my bash script to call authorize and access_token. Does anyone have a working example?
Update 2018-08-23
Since this still gets some views and upvotes I just want to mention that by now there seems to exist a maintained 3rd party SDK: https://github.com/mobolic/facebook-sdk
Better late than never, maybe others searching for that will find it. I got it working with Python 2.6 on a MacBook.
This requires you to have
the Python facebook module installed: https://github.com/pythonforfacebook/facebook-sdk,
an actual Facebook app set up
and the profile you want to post to must have granted proper permissions to allow all the different stuff like reading and writing.
You can read about the authentication stuff in the Facebook developer documentation. See https://developers.facebook.com/docs/authentication/ for details.
This blog post might also help with this: http://blog.theunical.com/facebook-integration/5-steps-to-publish-on-a-facebook-wall-using-php/
Here goes:
#!/usr/bin/python
# coding: utf-8
import facebook
import urllib
import urlparse
import subprocess
import warnings
# Hide deprecation warnings. The facebook module isn't that up-to-date (facebook.GraphAPIError).
warnings.filterwarnings('ignore', category=DeprecationWarning)
# Parameters of your app and the id of the profile you want to mess with.
FACEBOOK_APP_ID = 'XXXXXXXXXXXXXXX'
FACEBOOK_APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
FACEBOOK_PROFILE_ID = 'XXXXXX'
# Trying to get an access token. Very awkward.
oauth_args = dict(client_id = FACEBOOK_APP_ID,
client_secret = FACEBOOK_APP_SECRET,
grant_type = 'client_credentials')
oauth_curl_cmd = ['curl',
'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(oauth_args)]
oauth_response = subprocess.Popen(oauth_curl_cmd,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE).communicate()[0]
try:
oauth_access_token = urlparse.parse_qs(str(oauth_response))['access_token'][0]
except KeyError:
print('Unable to grab an access token!')
exit()
facebook_graph = facebook.GraphAPI(oauth_access_token)
# Try to post something on the wall.
try:
fb_response = facebook_graph.put_wall_post('Hello from Python', \
profile_id = FACEBOOK_PROFILE_ID)
print fb_response
except facebook.GraphAPIError as e:
print 'Something went wrong:', e.type, e.message
Error checking on getting the token might be better but you get the idea of what to do.
Here you go, as simple as it can get. Doesn’t require any 3rd-party SDK etc.
Make sure Python 'requests' module is installed
import requests
def get_fb_token(app_id, app_secret):
url = 'https://graph.facebook.com/oauth/access_token'
payload = {
'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret
}
response = requests.post(url, params=payload)
return response.json()['access_token']
Easy! Just use facebook-sdk.
import facebook
app_id = 'YOUR_APP_ID'
app_secret = 'YOUR_APP_SECRET'
graph = facebook.GraphAPI()
# exactly what you're after ;-)
access_token = graph.get_app_access_token(app_id, app_secret)
You first need to set up an application. The following will then spit out an access token given your application ID and secret:
> curl -F type=client_cred -F client_id=[...] -F client_secret=[...] https://graph.facebook.com/oauth/access_token
Since a web browser needs to be involved for the actual authorization, there is no such thing as a "standalone script" that does it all. If you're just playing with the API, or are writing a script to automate something yourself, and want a access_token for yourself that does not expire, you can grab one here: http://fbrell.com/auth/offline-access-token
There IS a way to do it, I've found it, but it's a lot of work and will require you to spoof a browser 100% (and you'll likely be breaking their terms of service)
Sorry I can't provide all the details, but the gist of it:
assuming you have a username/password for a facebook account, go curl for the oauth/authenticate... page. Extract any cookies returned in the "Set-Cookie" header and then follow any "Location" headers (compiling cookies along the way).
scrape the login form, preserving all fields, and submit it (setting the referer and content-type headers, and inserting your email/pass) same cookie collection from (1) required
same as (2) but now you're going to need to POST the approval form acquired after (2) was submitted, set the Referer header with thr URL where the form was acquired.
follow the redirects until it sends you back to your site, and get the "code" parameter out of that URL
Exchange the code for an access_token at the oauth endpoint
The main gotchas are cookie management and redirects. Basically, you MUST mimic a browser 100%. I think it's hackery but there is a way, it's just really hard!
s29 has the correct answer but leaves some steps to solve. The following script demonstrates a working script for acquiring an access token using the Facebook SDK:
__requires__ = ['facebook-sdk']
import os
import facebook
def get_app_access_token():
client = facebook.GraphAPI()
return client.get_app_access_token(
os.environ['FACEBOOK_APP_ID'],
os.environ['FACEBOOK_APP_SECRET'],
)
__name__ == '__main__' and print(get_app_access_token())
This script expects the FACEBOOK_APP_ID and FACEBOOK_APP_SECRET environment variables are set to the values for your app. Feel free to adapt that technique to load those values from a different source.
You must first install the Facebook SDK (pip install facebook-sdk; python get-token.py) or use another tool like rwt to invoke the script (rwt -- get-token.py).
Here is the Python Code. Try running some of these examples on command line, they work fine for me. See also — http://www.pythonforfacebook.com/