Telegram wrong URL host - python

I'm making bots. I tried every thing and this my code:
def send_photo(chat_id, location , reply_markup=None):
url = URL + "sendPhoto?chat_id={}&photo={}".format(chat_id,open('1.jpg', 'rb'))
if reply_markup:
url += "&reply_markup={}".format(reply_markup)
print(get_url(url))
get_url(url)
My file is in my .py folder and I double checked every thing, I even used photo telegram id's and url's and I'm still getting:
{"ok":false,"error_code":400,"description":"Bad Request: wrong URL host"}

#https://core.telegram.org/bots/api#sendphoto
import requests
import json
token = 'Token'
def send_photo(chat_id, photo, caption='', parse_mode=None, disable_notification=False, reply_to_message_id=0, reply_markup=None):
with open(photo, 'rb') as file:
response = requests.post(
'https://api.telegram.org/bot{token}/sendPhoto?'.format(token=token),
data={
'chat_id':chat_id, #Integer or String
'caption':caption, #String
'parse_mode': parse_mode, #String https://core.telegram.org/bots/api#formatting-options
'disable_notification': disable_notification, #Boolean
'reply_to_message_id': reply_to_message_id, #Integer
'reply_markup': json.dumps(reply_markup) if reply_markup is not None else reply_markup, #List
},
files={
'photo': file.read()
}
)
file.close()
if response.status_code == 200:
return json.loads(response.text)
reply_markup = {
'inline_keyboard':[
[
{'text':'stackoverflow', 'url':'https://stackoverflow.com'}
]
]
}
print(send_photo('802959264', 'test.png', caption='caption', reply_markup=reply_markup))
This is the output
{'ok': True, 'result': {'message_id': 10, 'from': {'id': 1157936984, 'is_bot': True, 'first_name': 'test', 'username': 'RoomSupervisorBot'}, 'chat': {'id': 802959264, 'firs
t_name': 'milad', 'username': 'milad_dev', 'type': 'private'}, 'date': 1597892647, 'photo': [{'file_id': 'AgACAgQAAxkDAAMKXz3oJ8X-3jkfsP8GgT_oAtOUhUwAArO0MRuwP_BR0owk2ZSqQ
RdwWPEiXQADAQADAgADbQADaNoEAAEbBA', 'file_unique_id': 'AQADcFjxIl0AA2jaBAAB', 'file_size': 8226, 'width': 320, 'height': 180}, {'file_id': 'AgACAgQAAxkDAAMKXz3oJ8X-3jkfsP8GgT_
oAtOUhUwAArO0MRuwP_BR0owk2ZSqQRdwWPEiXQADAQADAgADeAADadoEAAEbBA', 'file_unique_id': 'AQADcFjxIl0AA2naBAAB', 'file_size': 35836, 'width': 800, 'height': 450}, {'file_id': 'AgAC
AgQAAxkDAAMKXz3oJ8X-3jkfsP8GgT_oAtOUhUwAArO0MRuwP_BR0owk2ZSqQRdwWPEiXQADAQADAgADeQADatoEAAEbBA', 'file_unique_id': 'AQADcFjxIl0AA2raBAAB', 'file_size': 78830, 'width': 1280, '
height': 720}, {'file_id': 'AgACAgQAAxkDAAMKXz3oJ8X-3jkfsP8GgT_oAtOUhUwAArO0MRuwP_BR0owk2ZSqQRdwWPEiXQADAQADAgADdwADZtoEAAEbBA', 'file_unique_id': 'AQADcFjxIl0AA2baBAAB', 'fil
e_size': 88002, 'width': 1366, 'height': 768}], 'caption': 'caption', 'reply_markup': {'inline_keyboard': [[{'text': 'stackoverflow', 'url': 'https://stackoverflow.com'}]]}}}

Kindly use http url instead of local,
It will work else
upload the file first and then get the file_id
then send that file id to the bot.

Related

How to applying POST method using Python?

I have struggled with gettting bad response while I request POST method in Python.
API DOCS : https://docs.wemix.com/v/en/dapp-developer/api-reference/account-apis#get-wemix-balance-for-a-single-address
For example, body data is like
data = {
'addresses': [
'0xaC45d8b7ED8bDCBaF5F59F4622F9B351CDb9E956',
'0x5b2d775cA52Ad27524e3581980D56694D9E1A83C',
'0xc000250d0CdFb43e2F5C03f6ea73807e0694e795',
'0x501226d260513C4B6f2Ef67B6213AF5A9e3cdC7B',
'0x779a605C753cea01d23D9BB7a5F961A8AF315011',
'0x8FEC9850DAd02AB726b6822927c8B402bC993d58',
'0xeFE753A89B5f1836A44744DF626F5E47eeDa18F7',
'0xf9F20C6dbaF7D70FCEADDDBD13d9Bcb6b66298DA',
'0x290Fa3FE65dF509cb27bA55b493841cB92DA083B',
'0x2ED5972f39109D1818024bF84Ce8F2230c4d99D9',
'0xbed789c6008f788a28fc222c83082d67033daf7f',
'0x1393bba2f90fe4d040bf70c24183dd6e27274de5',
'0xb93de30f956a03d8c597ba0c7a7d08cf4644a571',
'0xf68aed73c86127de4047533da58b419e1aca7c0a'
]
}
I tried to get balance of each addresses.
url = 'https://explorerapi.wemix.com/v1/accounts/balance'
headers = {
'api-key': API_KEY
}
response = requests.get(url, headers=headers, json=data)
But, response is
{'status': '404',
'message': "Maybe you're requesting not supported http method"}
I could get right response when I use Postman.
How can I fix it correctly?
You can try:
import json
url = 'https://explorerapi.wemix.com/v1/accounts/balance'
headers = {
'api-key': '1ba5e446edf1997f67b51bf9e60b3fbba6fa1bf84301115292805d7e24f43539',
'Content-Type': 'application/json', # Mandatory, check documentation
}
response = requests.post(url, headers=headers, data=json.dumps(data))
Output:
>>> response.json()
{'status': '200',
'message': 'success',
'results': {'data': [{'address': '0xaC45d8b7ED8bDCBaF5F59F4622F9B351CDb9E956',
'balance': '50000000000000000000'},
{'address': '0x5b2d775cA52Ad27524e3581980D56694D9E1A83C',
'balance': '50000000000000000000'},
{'address': '0xc000250d0CdFb43e2F5C03f6ea73807e0694e795',
'balance': '50000000000000000000'},
{'address': '0x501226d260513C4B6f2Ef67B6213AF5A9e3cdC7B',
'balance': '50000000000000000000'},
{'address': '0x779a605C753cea01d23D9BB7a5F961A8AF315011',
'balance': '50000000000000000000'},
{'address': '0x8FEC9850DAd02AB726b6822927c8B402bC993d58',
'balance': '50000000000000000000'},
{'address': '0xeFE753A89B5f1836A44744DF626F5E47eeDa18F7',
'balance': '50000000000000000000'},
{'address': '0xf9F20C6dbaF7D70FCEADDDBD13d9Bcb6b66298DA',
'balance': '50000000000000000000'},
{'address': '0x290Fa3FE65dF509cb27bA55b493841cB92DA083B', 'balance': '0'},
{'address': '0x2ED5972f39109D1818024bF84Ce8F2230c4d99D9', 'balance': '0'},
{'address': '0xBEd789c6008F788a28fc222C83082D67033Daf7F',
'balance': '60000000000000000000000000'},
{'address': '0x1393BBA2F90fE4D040Bf70C24183Dd6e27274DE5',
'balance': '783714822540624807922423'},
{'address': '0xb93de30f956A03D8c597Ba0c7A7d08Cf4644a571',
'balance': '499998995799999999958000'},
{'address': '0xF68AEd73c86127dE4047533Da58b419E1AcA7c0A',
'balance': '500000089500000000000000'}]}}
Shortcut:
url = 'https://explorerapi.wemix.com/v1/accounts/balance'
headers = {
'api-key': '1ba5e446edf1997f67b51bf9e60b3fbba6fa1bf84301115292805d7e24f43539',
}
response = requests.post(url, headers=headers, json=data)

Scraping dynamic website with unchanging urls

I need to scrape data of all dental clinis. What's the next step? Can someone help me out? I have now 2 options of code:
1, Here i don't know how to set 'for loop' for all pages
url = "https://www.dent.cz/zubni-lekari"
s = HTMLSession()
r = s.get(url)
r.html.render(sleep=1)
for x in range(1, 31):
clinic = r.html.xpath(
f'//*[#id="main"]/div/div[3]/div[1]/div/div[{x}]/h3', first=True)
adress = r.html.xpath(
f'//*[#id="main"]/div/div[3]/div[1]/div/div[{x}]/p[1]', first=True)
try:
phone = r.html.xpath(
f'//*[#id="main"]/div/div[3]/div[1]/div/div[{x}]/p[1]/strong[1]', first=True)
except:
phone = "None"
try:
email = r.html.xpath(
f'//*[#id="main"]/div/div[3]/div[1]/div/div[{x}]/p[1]/strong[2]', first=True)
except:
email = "None"
clinics_list = {
"Clinic": clinic.text,
"Adress": adress.text,
"Phone": phone.text,
"Email": email.text
}
print(clinics_list)
2, Here i don't know how to find out the rest of data (adresses, phone, email)
api_url = "https://is-api.dent.cz/api/v1/web/workplaces"
payload = {
"deleted": False,
"filter": "accepts_new_patients=false",
"fulltext": "",
"page": 1, # <--- you can implement pagination via this parameter
"per_page": 30,
"sort_fields": "name",
}
data = requests.post(api_url, json=payload).json()
for item in data["data"]:
print(format(item["name"]))
You just need to change the page number. And extract the information from the json response
api_url = "https://is-api.dent.cz/api/v1/web/workplaces"
payload = {
"deleted": False,
"filter": "accepts_new_patients=false",
"fulltext": "",
"page": 1, # <--- you can implement pagination via this parameter
"per_page": 30,
"sort_fields": "name",
}
PAGES = 233
for i in range(1, PAGES):
payload['page'] = i
response = requests.post(api_url, json=payload)
data = response.json()
The output looks like this:
{'data': [{'id': 'df313eba-7447-4496-bca5-abd8a840394a',
'name': '#staycool s.r.o.',
'regional_chamber': {'id': 'ce0d8c8a-99db-46ed-85ff-87b6650c677a',
'name': 'OSK UHERSKÉ HRADIŠTĚ',
'checked': False,
'code': '',
'tooltip': ''},
'provider': {'id': '256f41bd-a9f1-452b-99e7-63f77005ecfa',
'name': '#staycool s.r.o.',
'is_also_member': False,
'registration_number': '11982861',
'identification_number': '',
'type_cares': []},
'accepts_new_patients': False,
'address': {'city': 'Uherské Hradiště',
'state': '',
'country_name': '',
'print': 'J.E.Purkyně 365, 686 06 Uherské Hradiště',
'street': 'J.E.Purkyně 365',
'postcode': '686 06',
'name': ''},
'contact': {'email1': '',
'email2': '',
'full': '',
'phone1': '',
'phone2': '',
'web': '',
'deleted': False},
'membes': [],
'insurance_companies': []},
so we just need to extract the data from the dictionary inside the data list
for i in range(1, PAGES):
payload['page'] = i
response = requests.post(api_url, json=payload)
data = response.json()
for item in data['data']:
clinic = item['name']
address_city = item['address']['city']
address_street = item['address']['street']
address_postcode = item['address']['postcode']
phone = item['contact']['phone1']
email = item['contact']['email1']

python - aiohttp.ClientSession().post

So, I had this code and it worked perfectly fine:
def upload_to_imgur(url):
j1 = requests.post(
"https://api.imgur.com/3/upload.json",
headers=headers,
data={
'key': api_key,
'image': b64encode(requests.get(url).content),
'type': 'base64',
'name': '1.jpg',
'title': 'Picture no. 1'
}
)
data = json.loads(j1.text)['data']
return data['link']
Now, I wanted to make all this async, but that doesn't really seem to work. Here's my current code:
async def async_upload_to_imgur(url):
image = await get_as_base64(url)
j1 = await aiohttp.ClientSession().post(
"https://api.imgur.com/3/upload.json",
headers=headers,
data={
'key': api_key,
'image': image,
'type': 'base64',
'name': '1.jpg',
'title': 'Picture no. 1'
}
)
data = await j1.json()
return data['link']
The get_as_base64-function is not the issue.
Header and Api Key are the same
This is the output when I print "data" in the second example.
{'data': {'error': {'code': 1001, 'message': 'File was not uploaded correctly', 'type': 'Exception_Logged', 'exception': {}}, 'request': '/3/upload.json', 'method': 'POST'}, 'success': False, 'status': 500}
It has to be the get_as_base64, for 2 reasons -:
1.) It says the file was not uploaded correctly meaning it doesn't support the URL or something like that
2.) I think you need to link a file not a link containing the file in it.

Uploading a file to Slack has no response in chat

I'm trying to send some txt data with this code
my_file = {'file' : ('/home/suomi/_data.txt', open('/home/suomi/_data.txt', 'r'), 'txt')}
payload={
"filename":"aaaa.txt",
"token":API_BOT,
"channel":'*my_user_id*',
}
x = requests.post("https://slack.com/api/files.upload", params=payload, files=my_file)
print(x)
print(x.json())
getting this response
<Response [200]>
{'ok': True, 'file': {'id': '*private_id*', 'created': 1603941396, 'timestamp': 1603941396, 'name': 'aaaa.txt', 'title': 'aaaa', 'mimetype': 'text/plain', 'filetype': 'text', 'pretty_type': 'pretty text', 'user': '*my private user_id*', 'editable': True, 'size': 18145, 'mode': 'snippet', 'is_external': False, 'external_type': '', 'is_public': False, 'public_url_shared': False, 'display_as_bot': False, 'username': '', 'url_private': '*private url_link*', 'url_private_download': '*private url_link*', 'permalink': '*private url_link*', 'permalink_public': '*private url_link*', 'edit_link': '*private url_link*', 'preview': "*somedata*", 'preview_highlight': '<div class="CodeMirror cm-s-default CodeMirrorServer" oncopy="if(event.clipboardData){event.clipboardData.setData(\'text/plain\',window.getSelection().toString().replace(/\\u200b/g,\'\'));event.preventDefault();event.stopPropagation();}">\n<div class="CodeMirror-code">\n<div><pre>*somedata*</pre></div>\n<div><pre></pre></div>\n<div><pre>*************************************</pre></div>\n<div><pre></pre></div>\n</div>\n</div>\n', 'lines': 131, 'lines_more': 126, 'preview_is_truncated': True, 'comments_count': 0, 'is_starred': False, 'shares': {}, 'channels': [], 'groups': [], 'ims': [], 'has_rich_preview': False}}
values inside ** are replaced due to privacy.
But I'm not getting a response from my app - I have enabled right permissions and I can send normal text messages.
files:write, channels:history, channels:read, chat:write, groups:history
BTW. I'm trying to send a file to user, not channel

How to send a local image instead of URL to Microsoft Cognitive Vision API(analyze an image) using Python?

Am trying to play with Vision API(analyze an image) of Microsoft Cognitive Services. Am wondering how to send a local image through rest API calls to Vision API and request for the results from it using Python. Can anyone help me with this please?
The Testing opting provided by Microsoft on their site only takes URL, I Tried to convert my local path to URL and give it as input but that doesn't work.
You can see the full code here: https://github.com/miparnisari/Cognitive-Vision-Python/blob/master/Jupyter%20Notebook/Computer%20Vision%20API%20Example.ipynb
But the gist of it:
import requests # pip3 install requests
region = "YOUR-API-REGION" #For example, "westus"
api_key = "YOUR-API-KEY"
path_to_file = "C:/Users/mparnisari/Desktop/test.jpg"
# Read file
with open(path_to_file, 'rb') as f:
data = f.read()
# Set request headers
headers = dict()
headers['Ocp-Apim-Subscription-Key'] = api_key
headers['Content-Type'] = 'application/octet-stream'
# Set request querystring parameters
params = {'visualFeatures': 'Color,Categories,Tags,Description,ImageType,Faces,Adult'}
# Make request and process response
response = requests.request('post', "https://{}.api.cognitive.microsoft.com/vision/v1.0/analyze".format(region), data=data, headers=headers, params=params)
if response.status_code == 200 or response.status_code == 201:
if 'content-length' in response.headers and int(response.headers['content-length']) == 0:
result = None
elif 'content-type' in response.headers and isinstance(response.headers['content-type'], str):
if 'application/json' in response.headers['content-type'].lower():
result = response.json() if response.content else None
elif 'image' in response.headers['content-type'].lower():
result = response.content
print(result)
else:
print("Error code: %d" % response.status_code)
print("Message: %s" % response.json())
This will print something like this:
{
'categories': [{
'name': 'others_',
'score': 0.0078125
}, {
'name': 'outdoor_',
'score': 0.0078125
}, {
'name': 'people_',
'score': 0.4140625
}],
'adult': {
'isAdultContent': False,
'isRacyContent': False,
'adultScore': 0.022686801850795746,
'racyScore': 0.016844550147652626
},
'tags': [{
'name': 'outdoor',
'confidence': 0.9997920393943787
}, {
'name': 'sky',
'confidence': 0.9985970854759216
}, {
'name': 'person',
'confidence': 0.997259259223938
}, {
'name': 'woman',
'confidence': 0.944902777671814
}, {
'name': 'posing',
'confidence': 0.8417303562164307
}, {
'name': 'day',
'confidence': 0.2061375379562378
}],
'description': {
'tags': ['outdoor', 'person', 'woman', 'snow', 'posing', 'standing', 'skiing', 'holding', 'lady', 'photo', 'smiling', 'top', 'wearing', 'girl', 'mountain', 'sitting', 'young', 'people', 'sun', 'slope', 'hill', 'man', 'covered', 'umbrella', 'red', 'white'],
'captions': [{
'text': 'a woman posing for a picture',
'confidence': 0.9654204679303702
}]
},
'metadata': {
'width': 3264,
'height': 1836,
'format': 'Jpeg'
},
'faces': [{
'age': 26,
'gender': 'Female',
'faceRectangle': {
'left': 597,
'top': 2151,
'width': 780,
'height': 780
}
}],
'color': {
'dominantColorForeground': 'White',
'dominantColorBackground': 'White',
'dominantColors': ['White', 'Grey'],
'accentColor': '486E83',
'isBWImg': False
},
'imageType': {
'clipArtType': 0,
'lineDrawingType': 0
}
}

Categories