GCM: cannot send message from python script - python

I'm following this tutorial to send GCM message from a server via a python script.
I've downloaded the GcmDemo that can successfully send messages to itself using my project num, server API key and reg id.
But no way to do it from python.
I've registered the client:
06-13 09:47:45.682 2272-32480/com.google.android.gcm.demo I/GcmDemo﹕ registration succeeded.
senderId: 11xxxxxxx07
token: fxq...xxxx..r5
My server API key:
The python script on the server:
from gcm import *
gcm = GCM("AIza...xxx...XQ")
data = {'ciao ciao': 'test message', 'param2': 'value2'}
reg_id = 'fxq...xxxx..r5'
gcm.plaintext_request(registration_id=reg_id, data=data)
No error messages but no messages received.
Is there a way to log and see where the problem is ?
The client doesn't react (log on Android Studio set to verbose, no log at all).
Any idea ?
The google project console just shows logs till 30 May.

I'm not using Python anymore as I switched to PHP but I had the same problem there and solved adding the icon field to the "data". So adding something like:
data = {'icon' : '#drawable/myAwesomeIcon', ...}
should solve the problem.

For me it was not working when i put dry_Run =True, but worked on removing drun_Run.dry_Run=True was giving me fake_message_id.

Related

Twilio Whatsapp Sandbox Configuration for deploying application via AWS elastic beanstalk

enter image description here
Currently I am developing a chatbot for my application with django, using a twilio trial account.
The chatbot functions properly with ngrok.io, i.e. when the server is operating locally, which mean that when I send a whatsapp message to the twilio sandbox with operation of simply "python manage.py runserver", he will automatically reply me according to my script.
However, as I started deploying the application using the AWS elastic beanstalk, I found that it is only possible for the sandbox to send out whatsapp message by POST request on the web application, but not capable to respond to POST request sent out from whatsapp.
In what way I can deal with it? Is it related to AWS settings or Twilio settings? Some CORS related issues?
Great thanks in advance.
(Please forgive me if my use of language is not accurate as I am not with computer science background.)
Below is part of the code that I applied.
#csrf_exempt
def message(request):
account_sid = 'xxx'
auth_token = 'xxx'
client = Client(account_sid, auth_token)
client_phone_number = request.POST.get('From').removeprefix("whatsapp:+852")
client_phone_number.removeprefix("+852")
incoming_message = request.POST.get('Body')
conversation_sid = request.POST.get('conversation_sid')
incoming_message = incoming_message.lower()
response = MessagingResponse()
#processing the incoming message to produce the text
resp = "text"
response.message(resp)
return HttpResponse(str(response))
I have tried pasting https://xxxxx-env.yyyyyyy.us-east-1.elasticbeanstalk.com/whatsapp/ to the sandbox configuration cell as shown in the image and it resulted to what I mentioned above. The whatsapp url is set just like typically done for other urls for django, followed by message(request) to process the request sent out from the whatsapp. Any other proper way I can do it?

Sending APNs notification returns Success but no notification appears on phone

I'm trying to send a push notification on an iphone using the pushjack library
(https://github.com/joseph-fox/pushjack).
I'm trying to run the provided example using my company's test phone token and pem file.
The code that I'm trying to run is this:
from pushjack_http2 import APNSClient
client = APNSClient(certificate='<mypem>.pem',
default_error_timeout=10,
default_expiration_offset=2592000,
default_batch_size=100,
default_retries=5)
token = '<mytoken>'
alert = 'Hello world.'
res = client.send([token], alert)
resp = {'successes': res.successes, 'failures': res.failures, 'tokens_sent': res.tokens, 'errors': res.errors,
'token_errors': res.token_errors}
return resp
and the response that I'm getting is the following:
{'successes': ['<mytoken>'], 'failures': [], 'tokens_sent': ['<mytoken>'], 'errors': [], 'token_errors': {}}
When using the same .pem and token via pushtry (https://pushtry.com/) I'm having the notification appear correctly on the phone (I wonder if it has to do with the bundle id which I also provided there, but had no option to provide in the sample code).
This is a rather vague question, but, does anybody have any idea why this would happen?
I've tried both the dev and the production .pem file and both return a success while none has a notification correctly pop up. Do you have any idea on what could be wrong or how I could probe around to find what's wrong?
Thanks!
Turns out that I didn't realise that apple changed something in their backend on March31 and the library I was trying to use was deprecated.
Solved it using apns2 instead.

IBM Watson IoT and Python Requests

I've created a IBM Watson IoT platform, and a device type "testdevice".
I would like a simple test where I push data via a Python script and the HTTP API.
So far I've managed to be able to push data, but getting:
(403, 'Not allowed')
I can see in the IBM Watson IoT log that my computer has tried to push data, but Authentication failed.
As a request header I'm using auth=('use-token-auth', 'MY-TOKEN')
so the entire code is:
import requests
response = requests.post('http://MY-ORG-ID.messaging.internetofthings.ibmcloud.com:1883/api/v0002/device/types/testdevice/devices/MY-DEVICE/events/test', data={'number': 1}, auth=('use-token-auth', 'MY-TOKEN'), headers={'Content-type': 'application/json'})
print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP
What could be the reason for authentication failing?
Have you tried connecting over HTTPS? Since the middle of the year, by default, organizations are configured to reject insecure connections, unless a user specifically enables this (you can find this option in the setting panel in the dashboard if you want to enable unencrypted connectivity in your organization), this is one possible reason you are getting 403 not allowed responses.
FYI, you might also be interested in the Python client library, which supports a HTTP only connection as well as the more feature rich MQTT client:
pip install ibmiotf
import ibmiotf.device
options = {"org": orgId, "type": "testdevice", "id": "MY-DEVICE", "auth-method": "token" , "auth-token": "MY-TOKEN"}
client = ibmiotf.device.HttpClient(options)
data={'number': 1}
client.publishEvent("test", "json", data)
Your code does work for me, so could be as DavidParker says http is not allowed. It could also be your token is getting messed up. I always encode the authentication header - x="use-token-auth:password".encode('base64')
`
Or, that token you have, is wrong.

HTTP 403 'Rate Limit Exceeded' ERROR in Google Blogger v3 API

I have a python script which uses Google Blogger API with oauth 2.0. Now the problem is that there is a function blogger.posts.insert. It is returning an error "HTTP 403 'Rate Limited Exceeded'".
Can anybody tell me how to fix this?
I also tried to do the same in python and the error is still there..
Note: blogger.posts.update function works perfectly!
credentials = storage.get()
http = httplib2.Http()
http = credentials.authorize(http)
service = build('blogger', 'v3', http=http)
TheBlogID = 'somethingHERE'
print "fetching posts, please wait!"
posts = service.posts()
thisposties = posts.list(blogId=TheBlogID).execute()
posts.insert(blogId=TheBlogID, # THIS IS THE PROBLEM
body=body,
isDraft=False, fetchImages=False, fetchBody=True).execute()
EDIT: Also I must tell you that just a few minutes ago I created credentials by selectingWeb Application here : https://console.developers.google.com/apis/credentials? but it stopped working after adding 50 posts and so I switched to other. Also I tried to create a new credential with Web Application but the redirect URL for urn:ietf:wg:oauth:2.0:oob is denying so currently I am using other as credential for oauth 2.0 and getting this error when trying to insert ...
I also tried from here: https://developers.google.com/apis-explorer/#p/blogger/v3/ Same ERROR... I'm assuming this is some bug with google API...
I was right, there is a bug with Google Blogger API when using the insert to add posts so this is how I fixed it:
I started Apache using XAMP and apache was running on port 80 ( can be different for you so check it in XAMP control panel ).
I created a Web Application here: https://console.developers.google.com/apis/credentials?
When creating a new web application I made sure to set the redirect URL to http://localhost:80/oauth2callback ( My apache is running on port 80 that is why it is localhost:80 ) You must also add this redirect URL to python code.
Create a new directory in XAMP C:\xampp\htdocs\ oauth2callback
Create an empty index.php in C:\xampp\htdocs\oauth2callback
Go to 192.168.1.1 and do port forwarding for port where apache is running BOTH TCP and UDP for port 80 ( since apache is running on this port for me )
Now simply run your python code and when you get the auth URL then simply open it in your browser and you will be asked to confirm it then do it. You will be redirected to your C:\xampp\htdocs\oauth2callback\index.php and now ignore the blank white screen and simply look at your browser address bar, you will see code=CODEHERE. Now copy that code and simply give it as input for python and then you will be able to use insert
Enjoy :)
I know this is pretty insane but this is how I was able to fix it.
NOTE: MAXMIMUM UPLOAD RATE FOR POSTS IS 50 POSTS/DAY.

What is the first step to getting in e-mail into my python / flask app code?

I am researching what it would take to make a web app that would interact with e-mails directly. Like you would send to something#myapp.com and the app would tear it apart and determine who it's from, if they are in the DB, what is the subject line, etc.
I am working with/most familiar with python and flask.
Could anyone get me started in the right direction of how to get an e-mail to interface with my flask app code?
There are several approach you can take:
write some code which uses IMAP or POP to retrieve emails and process them. Either run this from a crontab (or something similar) or add it to your flask app and trigger it in there, either through a crontab that requests a magic URL or setting up a custom timer thread.
configure your MTA to deliver email for something#myapp.com by feeding it to a program you write (for example in Exim you could use a pipe transport) . In that program you can either process it directly, or do something like POSTing it to your flask app.
I've done something along these lines recently, with a simple bookmarking web-app. I have the usual bookmarklet way of bookmarking something to it, but I also wanted to be able to e-mail links to it from apps like Reeder on my iPhone and whatever. You can see what I ended up with on GitHub: subMarks.
I use Google Apps for your Domain for my email, so I created a special address for my app to look at - I really didn't want to try building/configuring my own e-mail server.
the mail_daemon.py file from above is run as a cron job every 5 minutes. It connects to the email server using the poplib Python package, processes the emails that are there and then disconnects (one part I feel compelled to point out is that I check that the emails are from me before they are processed :) )
My Flask app then provides the front end to the bookmarks, displaying them from the database.
I decided not to put the email handling code into the actual flask app, because it can be rather slow and would only run when the page was visited, but you could do this if you wanted.
Here's some barebones code to get things going:
import poplib
from email import parser
from email.header import decode_header
import os
import sys
pop_conn = poplib.POP3_SSL('pop.example.com')
pop_conn.user('my-app#example.com')
pop_conn.pass_('password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message into an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
# check message is from a safe recipient
if 'me#example.com' in message['from']:
# Get the message body text
if message['Content-Type'][:4] == 'text':
text = message.get_payload() #plain text messages only have one payload
else:
text = message.get_payload()[0].get_payload() #HTML messages have more payloads
# decode the subject (odd symbols cause it to be encoded sometimes)
subject = decode_header(message['subject'])[0]
if subject[1]:
bookmark_title = subject[0].decode(subject[1]).encode('ascii', 'ignore') # icky
else:
bookmark_title = subject[0]
# in my system, you can use google's address+tag#gmail.com feature to specifiy
# where something goes, a useful feature.
project = message['to'].split('#')[0].split('+')
### Do something here with the message ###
pop_conn.quit()

Categories

Resources