Posting audio through webhook to Discord using Python - python

I have a file that is connected to another one of my programs, and upon being run, it sends an embed to Discord using the following code:
payload = {"embeds": [
{
"author": {
"name": "EAS Software",
"icon_url": "https://www.fema.gov/sites/default/files/styles/unicorn_rotator/public/uni-rotator-imgs/eas_logo_rev1_3.png?itok=56iK9r2a"
},
"title": lines,
"description": "Issued "+datetime.now().strftime('%m/%d/%Y %H:%M:%S') + " " + TMZ,
"color": 0xff9900,
"fields": [
{
"name": "Text Data:",
"value": args.text
},
{
"name": "EAS Protocol Data:",
"value": "ZCZC-"+args.org+"-"+args.event+"-"+args.fips+"+"+args.time+"-"+ts_val+"-"+args.calls+"-"
},
],
"timestamp" : datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.000Z'),
"footer": {
"text": "Nerp EAS Logger System"
}
}
]
}
header_data = {'content-type': 'application/json'}
requests.post(webhook1, json.dumps(payload), headers=header_data)
print("Succesfully posted.")
And this works, I get an embed to post to Discord. The issue I am having is that another program generates a file, combined.wav, and I would like to send it to the same webhook. I have settled on splitting the File-sending process and the Embed process for ease of debugging, but the issue is that the code that sends the file sends it, but it has no data.
Here's the code I use to send the file:
dataList = []
boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
dataList.append('--' + boundary)
dataList.append('Content-Disposition: form-data; name=file; filename={0}'.format('C:\Users\Brigan\Desktop\EAS-APPS\Encoder\combined.wav'))
fileType = mimetypes.guess_type('C:\Users\Brigan\Desktop\EAS-APPS\Encoder\combined.wav')[0] or 'application/octet-stream'
dataList.append('Content-Type: {}'.format(fileType))
dataList.append('')
with open('C:\Users\Brigan\Desktop\EAS-APPS\Encoder\combined.wav') as f:
dataList.append(f.read())
dataList.append('--'+boundary+'--')
dataList.append('')
body = '\r\n'.join(dataList)
payload = body
headers = {
'Content-Type': 'multipart/form-data; boundary=--------------------------248330258300818905783969',
'Content-type': 'multipart/form-data; boundary={}'.format(boundary)
}
conn.request("POST", "/api/webhooks/688944637209083926/vAv6UScav_j1AUun8GZ1RnYlYd2JvcvGvR1Wv5Db7_av3NhrBTsLWLlxH5PT8b0yQlpy", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Does anyone know how to send a .WAV file to Discord in Python, or am I just outta luck?
**EDIT
I found out that the system named discord-webhooks is cross platform, so I jsut used that using the following code:
#Post Json Embed to Discord!
webhook = DiscordWebhook(url='webhook1')
embed = DiscordEmbed(title=lines, description="Issued "+datetime.now().strftime('%m/%d/%Y %H:%M:%S') + " " + TMZ, color=0xff9900)
embed.set_author(name='EAS Software', icon_url='https://www.fema.gov/sites/default/files/styles/unicorn_rotator/public/uni-rotator-imgs/eas_logo_rev1_3.png?itok=56iK9r2a')
embed.set_footer(text='NERP EAS Logger System')
embed.set_timestamp()
embed.add_embed_field(name='EAS Text Data:', value=args.text, inline=False)
embed.add_embed_field(name='EAS Protocol Data:', value="ZCZC-"+args.org+"-"+args.event+"-"+args.fips+"+"+args.time+"-"+ts_val+"-"+args.calls+"-", inline=False)
webhook.add_embed(embed)
response = webhook.execute()
webhook = DiscordWebhook(url='webhook1')
with open("Output/FULL-ALERT-DATA.wav", "rb") as f:
webhook.add_file(file=f.read(), filename='Alert-Audio.wav')
response = webhook.execute()
print("Succesfully posted.")
Thanks for the help!

Related

Amadeus Flight Availabilities in Python - Error 400

I am trying to use the POST method of Amadeus flight availabilities API on Python, but is is still giving me error 400. Any suggestions? Many thanks.
from amadeus import Client, ResponseError, Location
import requests
amadeus = Client(
client_id='My ID',
client_secret='My Secret')
try:
flights = amadeus.get('/v2/shopping/flight-offers',originLocationCode = "GIG",destinationLocationCode = "ATL",departureDate = "2023-01-31",nonStop = "true",travelClass = "BUSINESS",adults = 1)
body = flights.data[0]
print(body)
except ResponseError as error:
print(error)
try:
availability = amadeus.post('/v1/shopping/availability/flight-availabilities', body)
print(availability.result)
except ResponseError as error:
print('headers: ', error.response.request.headers)
print('body: ', error.response.request.params)
As per their API documentation, the body of the second API call needs to be in the following format:
{
"originDestinations": [
{
"id": "1",
"originLocationCode": "BOS",
"destinationLocationCode": "MAD",
"departureDateTime": {
"date": "2021-11-14",
"time": "21:15:00"
}
}
],
"travelers": [
{
"id": "1",
"travelerType": "ADULT"
}
],
"sources": [
"GDS"
]
}
Right now you are just feeding the second call the return from the first, which doesn't seem to be what they're looking for.
You might also need to feed the proper headers, something like:
headers = {"Content-Type": "application/json; charset=utf-8"}
then you would do
response = requests.post(url, headers=headers, json=body)

How to send photos with multipart/form-data in media group with python requests?

json = {"chat_id":chat_id, "media":[{"type" : "photo", "media" : "attach://photo1.jpg"}, {"type" : "photo", "media" : "attach://photo2.jpg"}]}
files = {"photo1.jpg" : open(r"../photo1.jpg", 'rb'), "photo2.jpg" : open(r"../photo2.jpg", 'rb')}
temp = r.post("https://api.telegram.org/bot<TOKEN>/sendMediaGroup", json=json, files=files)
print(temp.json())
I keep getting this response: {'ok': False, 'error_code': 400, 'description': 'Bad Request: parameter "media" is required'}
How can I send photo.jpg with sendMediaGroup using multipart/form-data?
I'd recommend using data with a custom dict.
Then the only thing you should note is the media array inside data, should be JSON encoded using json.dumps
So the code becomes:
import json
import requests as r
#####
chat_id = 1010011
TOKEN = 'ABCDEF....'
#####
data = {
"chat_id": chat_id,
"media": json.dumps([
{"type": "photo", "media": "attach://photo1.png"},
{"type": "photo", "media": "attach://photo2.png"}
])
}
files = {
"photo1.png" : open("./photo1.png", 'rb'),
"photo2.png" : open("./photo2.png", 'rb')
}
temp = r.post("https://api.telegram.org/bot" + TOKEN + "/sendMediaGroup", data=data, files=files)
print(temp.json())
Result in Telegram desktop:

make an order kucoin API in python

import requests, json, time
url = 'https://api.kucoin.com/api/v1/orders'
headers = {
"KC-API-KEY": '',
"KC-API-PASSPHRASE": '',
"clientOid": "AAA",
"side": "sell",
"symbol": "BTC-USDT",
"type": "market",
"size": "0.001",
}
response = requests.post(url, headers=headers)
print(response.status_code)
print(response.json())
I am trying to place an order but it isn't working. Am I missing some parameters?
Error:
{'code': '400001', 'msg': 'Please check the header of your request for KC-API-KEY, KC-API-SIGN, KC-API-TIMESTAMP, KC-API-PASSPHRASE'}
According to the official docs, all private request must contain the following headers:
KC-API-KEY
KC-API-SIGN
KC-API-TIMESTAMP
KC-API-PASSPHRASE
KC-API-VERSION
Here is an example of the endpoint to place a order limit:
import base64, hmac, hashlib, json
# constants
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
API_PASSPHRASE = "YOUR_API_PASSPHRASE"
url = "https://api.kucoin.com/api/v1/orders"
now = int(time.time() * 1000)
data = {"clientOid": "AAA", "side": "sell", "symbol": "BTC-USDT", "type": "market", "size": "0.001"}
data_json = json.dumps(data)
str_to_sign = str(now) + 'POST' + '/api/v1/orders' + data_json
signature = base64.b64encode(hmac.new(API_SECRET.encode(
'utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(API_SECRET.encode(
'utf-8'), API_PASSPHRASE.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": API_KEY,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"Content-Type": "application/json"
}
try:
res = requests.post(
url, headers=headers, data=data_json).json()
print(res)
except Exception as err:
print(err)
Hope it will help.
Did you consider using wrapped library like Python-kucoin ?
https://python-kucoin.readthedocs.io/en/stable/index.html
it is really great and will definitely help you. Have a look to the documentation
from kucoin.client import Client
api_key = '<api_key>'
api_secret = '<api_secret>'
api_passphrase = '<api_passphrase>'
client = Client(api_key, api_secret, api_passphrase)
# place a market buy order
order = client.create_market_order('BTC-USDT', Client.SIDE_BUY, size=0.001)
try removing the spaces from :
data = {"clientOid": "AAA", "side": "sell", "symbol": "BTC-USDT", "type": "market", "size": "0.001"}

response 422 after trying to send post request with json file

I have been trying to find an answer that work on my case but had no success.
I am getting a response 422 when running the code below. I have replaced the json in the response variable and also used json.dumps around the data variable but I am still getting this response. Would you be able to find the issue within my json file? Thanks a lot
todaystr = datetime.today().strftime('%Y-%m-%d')
today = datetime.strptime(todaystr, '%Y-%m-%d')
first_day_of_month = today.replace(day=1)
day_count_str = today - first_day_of_month
day_count_int = day_count_str / timedelta(days=1)
day_count_split = str(day_count_int)
sep = '.'
day_count = day_count_split.split(sep, 1)[0]
dt = str(first_day_of_month.timestamp())
data = {"requestId": "numberOfUniqueAccountsAndVisitors", "timeSeries": {"period": "dayRange", "count": day_count, "first": dt}, "source": {"events": None}, "pipeline": [{"reduce": [{"reduce": {"visitors": {"count": "visitorId"}, "accounts": {"count": "accountId"}}}]}]}
headers = {
'x-pendo-integration-key': API_Key,
'content-type': "application/json"
}
response = requests.post(url, json=data, headers=headers)
print(response)
response_dictionary = json.loads(response.content)
print(response_dictionary)
In the payload to the Pendo Aggregation API, the request object should not be an array. And make sure the "key" should be named as "request"(singular), not as "requests"(plural).
Try something like this
{
"response": {
"mimeType": "application/json"
},
"request": {
"name": "accounts-last7days",
"requestId": "accounts-last7days"
}
}

JSONDecodeError: Expecting value: line 1 column 1 (char 0) error

I am facing this error while making request to fetch json from api.
I can get json data using the "/v1/articles' path.
conn = http.client.HTTPSConnection("api.xxxx.com.tr")
headers = {
'accept': "application/json",
'apikey': "cd6b6c96799847698d87dec9f9a731d6"
}
filter = "daily"
conn.request("GET", "/v1/articles", headers=headers)
reader = codecs.getreader("utf-8")
res = conn.getresponse()
data = json.load(reader(res))
json.dumps(data)
return data
But i am having JSONDecodeError if i set filter. Code:
conn = http.client.HTTPSConnection("api.xxxx.com.tr")
headers = {
'accept': "application/json",
'apikey': "cd6b6c96799847698d87dec9f9a731d6"
}
conn.request("GET", "/v1/articles?$filter=Path eq '/daily/'", headers=headers)
reader = codecs.getreader("utf-8")
res = conn.getresponse()
data = json.load(reader(res))
json.dumps(data)
return data
I tried same filter using Postman with no error and i can get Json data.
Returned Json data from Postman:
[
{
"Id": "40778196",
"ContentType": "Article",
"CreatedDate": "2018-03-20T08:28:05.385Z",
"Description": "İspanya'da 2016 yılında çalınan lüks otomobil, şasi numarası değiştirilerek Bulgaristan üzerinden getirildiği Türkiye'de bulundu.",
"Files": [
{
"FileUrl": "http://i.xxxx.com/i/xxxx/98/620x0/5ab0c6a9c9de3d18a866eb54.jpg",
"Metadata": {
"Title": "",
"Description": ""
}
}
],
"ModifiedDate": "2018-03-20T08:32:12.001Z",
"Path": "/gundem/",
"StartDate": "2018-03-20T08:32:12.001Z",
"Tags": [
"ispanya",
"Araç",
"Hırsız",
"Dolandırıcı"
],
"Title": "İspanya'da çalınan lüks araç Türkiye'de bulundu!",
"Url": "http://www.xxxx.com.tr/gundem/ispanyada-calinan-luks-arac-turkiyede-bulundu-40778196"
}
]
I can not figure out the problem. It would be great if anyone help me about this issue. Thank you.
I finally figured out the problem! Using the requests library have solved my problem now I can filter the api request.
data = requests.get('https://api.xxxxx.com.tr/v1/articles', headers =
headers, params={"$filter":"Path eq '/xxxxxx/'"}).json()
I am leaving this answer here for anyone else who can need this solution in the future.
Thanks for all your suggestions.
The problem is in the following line
data = json.load(reader(res))
when your response is not a json string, JSONDecodeError occurs. so, add an additional logic to see if the response is None or a json string. First thing, print the reader(res) and see what the return is

Categories

Resources