I am struggling so hard on the following problem:
As the title says I want to send a picture via the Telegram Bot API. This is the code everyone is suggesting:
params = {'chat_id': chatId, 'caption':"This is a caption"}
img = {'photo': open(imgpath, 'rb')}
status = requests.post(sendPhotoURL, data=params, files=img)
Unfortunately, that does not work for me.
I've found out that in requests.post data should be params in order to create/post the URL correctly. But I haven't found a solution for sending the picture via the URL.
This is the code that is working for me (so far):
params = {'chat_id': chatId, 'caption':"This is a caption"}
img = {'photo': open(imgpath, 'rb')}
status = requests.post(sendPhotoURL, params=params, files=img)
print (status.url, "responsed:\n", status.status_code, ":", status.text)
I know the picture should be sent as a multipart/form-data (see: https://core.telegram.org/bots/api#sendphoto), which should be done by setting the parameter files to img (which is a dictionary). By doing it this way, i still get 400 : {"ok":false,"error_code":400,"description":"Bad Request: there is no photo in the request"}, so apparantly the API wants me to put the image into the URL.
It's very possible that I'm misunderstanding the docs or that I'm doing something incredible stupid. It would be so nice if any geeks could help me out :D!
Thanks a lot!
PS: I'm sorry for any typos or grammar/spelling mistakes. English is not my first language :D
Related
i searched the internet (and stackoverflow :D) to find an answer for the following question - and found none that i understood.
background:
we want to use a python script to connect our companies CMDB with our AWX/Ansible infrastructure.
the CMDB has a REST API which supports a (halfway) proper export.
i'm currently stuck with the implementation of the correct API call.
i can call the API itself and authenticate, but i can't call the proper filter to get the results i need.
the filter is realized by having the following string within the URL (more in the attached code example)
Label LIKE "host*"
it seems that python has a problem with the *.
error message:
InvalidURL(f"URL can't contain control characters. {url!r} "
I found some bug reports that there is an issue within some python versions, but i'm way to new to properly understand if this affects me here :D
used python version 3.7.4
PS: let's see if i can get the markup right :D
i switched the called URL to determine where exactly the problem occurs.
it only occurs when i use the SQL like filter part.
this part is essential since i just want our "hosts" to be returned and not the whole CMDB itself.
#import the required classes and such
from http.client import HTTPConnection
import json
#create a HTTP connection client
client = HTTPConnection("cmdb.example.company")
#basic auth and some header details
headers = {'Content-Type': 'application/json',
'Authorization' : 'Basic my-auth-token'}
#working API call
client.request('GET', '/cmdb/rest/hosts?attributes=Label,Keywords,Tag,Description&limit=10', headers=headers)
#broken API call returns - InvalidURL(f"URL can't contain control characters. {url!r} "
client.request('GET', '/cmdb/rest/hosts?filter=Label LIKE "host*"&attributes=Label,Keywords,Tag,Description&limit=10', headers=headers)
#check and convert the response into a readable (JSON) format
response = client.getresponse()
data = response.read()
#debugging print - show that the returned data is bytes?!
print(data)
#convert the returned data into json
my_json = data.decode('utf8').replace("'", '"')
data = json.loads(my_json)
#only return the data part from the JSON and ignore the meta-overhead
text = json.dumps(data["data"], sort_keys=True, indent=4)
print(text)
so, i want to know how to properly call the API with the described filter and resolve the displayed error.
can you give me an example i can try or pin-point a beginners mistake i made?
am i affected by the mentioned python bug regarding the URL call with * in it?
thanks for helping me out :)
soooo i found my beginners mistake myself:
i used the URL from my browser - and my browser automaticly encodes the special characters within the URL.
i found the following piece of code within Python3 URL encoding guide and modified the string to fit my needs :)
import urllib.parse
query = ' "host*"'
urllib.parse.quote(query)
'%20%22host%2A%22'
Result: '%20%22host%2A%22'
%20 = " "
%22 = " " "
%2A = "*"
so the final code looks somewhat like this:
#broken API call returns - InvalidURL(f"URL can't contain control characters. {url!r} "
client.request('GET', '/cmdb/rest/hosts?filter=Label LIKE "host*"&attributes=Label,Keywords,Tag,Description&limit=10', headers=headers)
filter=Label LIKE "host*"
#fixed API call
client.request('GET', '/cmdb/rest/hosts?filter=Label%20LIKE%20%22host%2A%22&attributes=Label,Keywords,Tag,Description&limit=10', headers=headers)
filter=Label%20LIKE%20%22host%2A%22
I'm in the process on making a actions on google project and I am wanting to add a carousel to the action.
I understand the code end of things of how to add it to your action, but I'm a bit confused on how you get the links for your images. So for example, I seen in googles tutorial for carousel they have this following code snippet (to get it started):
const IMG_URL_AOG = 'https://developers.google.com/actions/images/badges' +
'/XPM_BADGING_GoogleAssistant_VER.png';
const IMG_URL_GOOGLE_ALLO = 'https://allo.google.com/images/allo-logo.png';
const IMG_URL_GOOGLE_HOME = 'https://lh3.googleusercontent.com' +
'/Nu3a6F80WfixUqf_ec_vgXy_c0-0r4VLJRXjVFF_X_CIilEu8B9fT35qyTEj_PEsKw';
const IMG_URL_GOOGLE_PIXEL = 'https://storage.googleapis.com/madebygoog/v1'
+
'/Pixel/Pixel_ColorPicker/Pixel_Device_Angled_Black-720w.png';
const IMG_URL_MEDIA = 'http://storage.googleapis.com/automotive-
media/album_art.jpg';
const MEDIA_SOURCE = 'http://storage.googleapis.com/automotive-
media/Jazz_In_Paris.mp3';
// Constants for selected item responses
And if you actually type these links in, you will get something like this back. The last two are other media types, but same idea.
Could someone explain how getting the images/ image links works for carousel's with actions on google? Do you have to make a html page for that image or am I just overthinking this and you can take an image link from online and it will work (given the right size of course). I might have missed something in the docs.
Thanks for the help or suggestions!
To maybe provide further context, I'm going off of this doc
I have written this small PoC for discord webhooks and i am getting error that Can not send empty string. I tried to google but couldn't find a documentation or an answer
here is my code
import requests
discord_webhook_url = 'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxxxx/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
data = {'status': 'success'}
headers = {'Content-Type': 'application/json'}
res = requests.post(discord_webhook_url, data=data, headers=headers)
print(res.content)
I'm late, but I came across this issue recently, and seeing as it has not been answered yet, I thought I document my solution to the problem.
For the most part, it is largely due to the structure of the payload being wrong.
https://birdie0.github.io/discord-webhooks-guide/discord_webhook.html provides an example of a working structure. https://discordapp.com/developers/docs/resources/channel#create-message is the official documentation.
I was also able to get a minimum test case working using: {"content": "Test"}.
If it still fails after that with the same error, the likely causes are:
If using curl, check to make sure there are no accidental escape / backslashes \
If using embeds with fields, ensure there are no empty values
When in doubt, ensure all values are populated, and not "". Through trial-and-error / the process of cancellation, you can figure out exactly what key-value pair is causing an issue, so I suggest playing with the webhook via curl before turning it into a full program.
There is an image in the telegram docs showing a
Formatted message with an image and text under,
It's from TechCrunch.
I have tried to replicate this and failed.
How can one replicate this format.
I am using Python
def reply(msg=None, img=None):
if msg:
resp = urllib2.urlopen(BASE_URL + 'sendPhoto', urllib.urlencode({
'chat_id': str(chat_id),
'caption': msg,
})).read()
In case you are talking about this image here i'm pretty sure it was done with sendPhoto() method. Text can be placed under the image by using the optional caption parameter.
Telegram Bot API sendPhoto
I'm using Youtube API, I'd like to have a search auto-complete feature, just like on YouTube, when you type into the search input box, it gives you search suggestions.
I've read the docs, but still missing, Is this possible using the API?
Ok I found this URL:
http://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q=Query
It isn't part of Youtube API, but still works, returns a JSON response.
For json just add "client" parameter:
http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&client=firefox&q=Query
Above all apis are old and give google search suggestion not youtube search suggestion
Use this:
https://clients1.google.com/complete/search?client=youtube&gs_ri=youtube&ds=yt&q=faded
Extract suggestions using following JS code:
// data is response of above api
const data = 'window.google.ac.h(["faded",[["faded",0,[433]],["faded alan walker lyrics",0,[433]],["faded remix",0,[433]],["faded 8d",0,[433]],["faded piano",0,[433]],["faded wheel free fire",0],["faded karaoke",0,[433]],["faded ringtone",0,[433]],["faded instrumental",0,[433]],["faded live",0,[433]],["faded piano tutorial",0,[433]],["faded whatsapp status",0,[433]],["faded dhol cover",0,[433]],["faded dance",0,[433]]],{"k":1,"q":"_sPyvXmmbfcsVtfP4sgjOdKQAvg"}])';
const searchSuggestions = [];
data.split('[').forEach((ele, index) => {
if (!ele.split('"')[1] || index === 1) return;
return searchSuggestions.push(ele.split('"')[1]);
});
console.log(searchSuggestions);
Check Out YouTube AutoComplete Keyword Scraper . Not really sure of the context the person asking the question wants YouTube auto complete solution for but I thought I would throw this out there.
Also you can use JSON:
url: "https://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=" + i,
dataType: "jsonp",
The official one:
https://suggestqueries-clients6.youtube.com/complete/search?client=youtube-reduced&hl=en&gs_ri=youtube-reduced&ds=yt&cp=3&gs_id=100&q=Nectar&xhr=t&xssi=t&gl=us
You can choose country too.
P.S. I searched for Nectar in country US