Slack bot to download files using private_url - python

I'm developing a slack bot that takes images from a slack channel and uploads them to AWS S3. The Slack docs say it's possible to download a file using the private_url and an auth token but running the code redirects the bot to a sign up page instead of the file even with auth headers set.
Code used
import os
slack_token = 'token'
url = 'https://files.slack.com/files-pri/T04LKR03H8F-F04NP55S78Q/download/instagram_story_-_2.png'
res = requests.get(url, headers={f'Authorization': 'Bearer {slack_token}'})
res.raise_for_status()
with open('instagram_story_-_2.png', 'wb') as f:
f.write(res.content)

Related

Azure Websites Kudu REST API - Authentication in Python

I am trying to access the Azure Kudu Web API interface to get historical information about my WebJobs. The URL is https://myfakewebappname.scm.azurewebsites.net/api/triggeredwebjobs/HubSpot/history
This works just fine in a browser with a one time (first time you login) user and password authentication.
When I call it with a python script using the requests library, I get a 401 response code and 'WWW-Authenticate': 'Basic realm="site"'. I then send another request:
resp = requests.get('https://myfakewebappname.scm.azurewebsites.net/api/triggeredwebjobs/HubSpot/history', auth=('actualuser', 'actualpassword')). I use the user and Password that work using my browser.
I get the same 401 response code again with the same response.headers. What am I doing wrong?
The Authentication of the WebJobs Kudu API is via basic auth, to call the API successfully in python, please follow the steps below.
1.Navigate to the Azure portal -> your web app which has the webjob -> click Get publish profile.
2.Open the downloaded file with the format joyweb11.PublishSettings in step 1, note down the userName and userPWD in this file.
3.Then use the code below, replace the value of username and password with the values in step 2, also replace the webapp name in the url with yours, it works fine on my side.
import requests
from base64 import b64encode
username = '$joyweb11'
password = '7pWclexxxxxJlHwoLRwtrneE'
base64AuthInfo = b64encode((username+':'+password).encode('ascii')).decode('ascii')
url = 'https://joyweb11.scm.azurewebsites.net/api/triggeredwebjobs/HubSpot/history'
headers = {'Authorization': 'Basic ' + base64AuthInfo}
response = requests.get(url=url, headers=headers)
print(response.status_code)
print(response.text)

Telegram Bot SendDocument pdf

I am having a real headache with the way of sending a pdf file to a Telegram Bot.
Apparently I am following the documentation but never get it sent.
I am using the url: https://api.telegram.org/botBOTID/sendDocument?chat_id=CHATID&document=/home/lix/Downloads/2.pdf
It is a pdf file storaged locally, but I think it is just the way I am presenting it.
The error getting is:
{"ok":false,"error_code":400,"description":"Bad Request: URL host is empty"}
Does anybody knows how to send a pdf local file?
Many thanks
You should send a POST request, with the PDF as a payload, using the Python Requests library, your code should look something like this:
import requests
# Url with bot token + user id
url = "https://api.telegram.org/bot<MY-BOT-TOKEN>/sendDocument?chat_id=<MY_CHAT_ID>"
# Create payload with PDF file
payload = {}
files = [
('document', open('/home/lix/Downloads/2.pdf','rb'))
]
headers= {}
# Request
response = requests.request("POST", url, headers=headers, data = payload, files = files)
# Log reponse as UTF-8
print(response.text.encode('utf8'))

Python - Push Notification through FCM / APNs to IOS or Android Devices

I am working on my python project, i need to create my own push notification server for apns and fcm / gcm, which sends push notification to both ios and android at same time, I have looked through the Firebase documentation however, the there was no code examples on the site. Can any one give me an idea of how to complete this in Python code?
I struggled with this for a little while so I thought I will post the code that worked for me eventually. All you need to do is to do a pip install of oauth2client from Google (https://github.com/google/oauth2client):
pip install oauth2client
Now, you will need to import the service account which will generate for you a short lived token that you can use in your API so that your app server can communicate with the FCM Google server.
Do as instructed by the following website:
https://firebase.google.com/docs/cloud-messaging/auth-server
from oauth2client.service_account import ServiceAccountCredentials
def _get_access_token():
"""Retrieve a valid access token that can be used to authorize requests.
:return: Access token.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'service-account.json', FCM_SCOPE)
access_token_info = credentials.get_access_token()
return access_token_info.access_token
Now, once you have the short_lived token, you can use it in your API calls to send messages to your android / IOS devices:
import requests, json
values = {"message":{"token":"<insert android firebase token id here>","notification":{"body":"This is a Firebase Cloud Messaging Topic Message for testing!","title":"FCM Message!!"}}}
header ={ 'Content-Length': '33333', 'Content-Type': 'application/json; UTF-8', 'Authorization': 'Bearer ' + _get_access_token(), 'User-Agent': 'Mozilla/5.0'}
url = 'https://fcm.googleapis.com/v1/projects/<insert project name here>/messages:send'
print(header)
r = requests.post(url, data=json.dumps(values), headers=header)
print(r.text)
If the call is successful, you will receive a print on the screen of the reference of your FCM message that you have just sent:
{
"name": "projects/<your project name>/messages/0:1519633952417262%0958967209589672"
}

facebook credentials instead of access token

I am new in coding and I am using this code:
import requests
url = (
"https://graph.facebook.com/{album_id}/"
"photos?access_token={access_token}"
).format(
album_id= "ALBUM ID HERE",
access_token= "PUT HERE ACCESS TOKEN" )
files = {'file': open('C:\\Users\\Leonardo\\Desktop\\black_background_texture_86812_1024x1024.jpg', 'rb')}
r = requests.post(url, files=files)
to upload an image from a pc's folder to an album on a facebook page using an access token. How can I do the same thing using facebook credentials and page name instead of access token? I have already tried to look inside facebook SDK documentation and pythonforfacebook documentation but I can't understand how to use codes made for PHP or JAVA or IOS with python. Thanks
Use page_access_token instead of access_token then you can post that image through your page name.

Authentication using python requests. Getting redirect to login page

I am using python requests library to login the site:
http://www.zsrcpod.aviales.ru/login/login_auth2.pl
and then trying to get a file, but authentication fails and i am gettin redirect to login page.
I already had some experience in using requests library for other sites and it works fine with .seesion, but this script is not working:
login_to_site_URL= r'http://www.zsrcpod.aviales.ru/login/login_auth2.pl'
URL = r"http://www.zsrcpod.aviales.ru/modistlm-cgi/seances.pl?db=modistlm"
payload = {r'login': r'XXXXXX',
r'second': r'XXXXXX'}
with requests.session() as s:
s.post(login_to_site_URL, payload)
load = s.get(URL, stream=True)
# download
with open('G:\!Download\!TEST.html', "wb") as save_command:
for chunk in load.iter_content(chunk_size=1024):
if chunk:
save_command.write(chunk)
save_command.flush()
I need a help with adopting it.

Categories

Resources