I am trying to create a Telegram bot from scratch using python. I've done all the initial steps and got the bot token, and now what I want to do is, for easy manipulation of the data it sends me (Like getting the first_name of the person from getupdates method) I want the data neatly arranged into a python dictionary.
When I try /getme, I get this:
b'{"ok":true,"result":{"id":999999999,"first_name":"telebotsrock","username":"sample_bot"}}'
Since the b' at the beginning and ' at the end causes an error when I do json.loads(data) (Where data is the thing given above converted to a string).
So I do data[2:-1] to remove the b' and ' and json.loads() works just fine, but when I change the /getme to /getupdates, a bunch of new errors pop up.
All in all, it's a mess. Can someone give me a clean way to get data from the bot and sort it into a python dictionary? Please do not tell me to use a different language or just copy an existing bot framework.
My current code:
from urllib.request import urlopen
import json
token="999999999:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
site="https://api.telegram.org/bot"+token
content=str(urlopen(site+"/getme").read())
#content=str(urlopen(site+"/getupdates").read())
data=content[2:-1]
print(data)
info=json.loads(data)
print(info)
This code correctly coverts the output of /getme to a python dictionary, but gives errors when I try /getupdates instead.
Output of /getupdates before I slice it is:
b'{"ok":true,"result":[{"update_id":66666666,\n"message":{"message_id":1,"from":{"id":777777777,"first_name":"Aswin","last_name":"G","username":"MatrixHunter"},"chat":{"id":777777777,"first_name":"Aswin","last_name":"G","username":"MatrixHunter","type":"private"},"date":1459932293,"text":"\\/start"}},{"update_id":88888888,\n"message":{"message_id":2,"from":{"id":777777777,"first_name":"Aswin","last_name":"G","username":"MatrixHunter"},"chat":{"id":777777777,"first_name":"Aswin","last_name":"G","username":"MatrixHunter","type":"private"},"date":1459932298,"text":"Oy"}}]}'
This should work for you. You can use the .decode('utf-8') to get rid of the byte prefix.
token = "999999999:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
url="https://api.telegram.org/bot" +token + "/getme"
req = Request(url)
response = urlopen(req)
data = response.read().decode('utf-8')
json_data = json.loads(data)
print(str(data['ok'])) #should print True
Related
For example, there is a JSON object written in Dart and Python
final jsonData = {'access_key':'i-want-to-authorized','param1': 'parameter1'};
jsonData = {'access_key':'i-want-to-authorized','param1': 'parameter1'}
and if I stringify these variables like this
import 'dart:convert';
final jsonData = {'access_key':'i-want-to-be-authorized','param1': 'parameter1'};
final dumpedJson = json.encode(jsonData);
print(dumpedJson);
import json
jsonData = {'access_key':'i-want-to-be-authorized','param1': 'parameter1'}
dumped_json = json.dumps(jsonData)
print(dumped_json)
When I execute the codes above, I get the following results.
In Dart, {"access_key":"i-want-to-be-authorized","param1":"parameter1"}
In Python, {"access_key": "i-want-to-be-authorized", "param1": "parameter1"}
As you can see, the JSON library in Python puts space after every colon and comma, which makes the total different result when it's encrypted in anyways.
Though I believe that when they're all decrypted and decoded, they will be taken the same on the server-side but is it probable that this difference makes the server not able to comprehend the request?
I'm trying to get url from object data, but it isn't right. This program has stopped on line 4. Code is under.
My code:
import requests
gifs = str(requests.get("https://api.giphy.com/v1/gifs/random?
api_key=APIKEY"))
dump = json.dumps(gifs)
json.loads(dump['data']['url'])
Your description is not clear enough. You expect to read a json and select a field that brings you something?
I recommend you check this section of requests quickstart guide this i suspect you want to read the data to json and extract from some fields.
Maybe something like this might help:
r = requests.get('http://whatever.com')
url = r.json()['url']
When sending data through python-requests a GET request, I have a need to specifically add something at the beginning of the query string. I have tried passing the data in through dicts and json strings with no luck.
The request as it appears when produced by requests:
/apply/.../explain?%7B%22......
The request as it appears when produced by their interactive API documentation (Swagger):
/apply/.../explain?record=%7B%22....
Where the key-value pairs of my data follow the excerpt above.
Ultimately, I think the missing piece is the record= that gets produced by their documentation. It is the only piece that is different from what is produced by Requests.
At the moment I've got it set up something like this:
import requests
s = requests.Session()
s.auth = requests.auth.HTTPBasicAuth(username,password)
s.verify = certificate_path
# with data below being a dictionary of the values I need to pass.
r = s.get(url,data=data)
I am trying to include an image of the documentation below, but don't yet have enough reputation to do so:
apply/model/explain documentation
'GET' requests don't have data, that's for 'POST' and friends.
You can send the query string arguments using params kwarg instead:
>>> params = {'record': '{"'}
>>> response = requests.get('http://www.example.com/explain', params=params)
>>> response.request.url
'http://www.example.com/explain?record=%7B%22'
From the comments i felt the need to explain this.
http://example.com/sth?key=value&anotherkey=anothervalue
Let's assume you have a url like the above in order to call with python requests you only have to write
response = requests.get('http://example.com/sth', params={
'key':'value',
'anotherkey':'anothervalue'
})
Have in mind that if your value or your keys have any special character in them they will be escaped thats the reason for the %7B%2 part of url in your question.
I'm trying to get IP location and other stuff from ipinfodb.com, but I'm stuck.
I want to split all of the values into new strings that I can format how I want later. What I wrote so far is:
resp = urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?key=mykey&ip=someip').read()
out = resp.replace(";", " ")
print out
Before I replaced the string into new one the output was:
OK;;someip;somecountry;somecountrycode;somecity;somecity;-;42.1975;23.3342;+05:00
So I made it show only
OK someip somecountry somecountrycode somecity somecity - 42.1975;23.3342 +05:00
But the problem is that this is pretty stupid, because I want to use them not in one string, but in more, because what I do now is print out and it outputs this, I want to change it like print country, print city and it outputs the country,city etc. I tried checking in their site, there's some class for that but it's for different api version so I can't use it (v2, mine is v3). Does anyone have an idea how to do that?
PS. Sorry if the answer is obvious or I'm mistaken, I'm new with Python :s
You need to split the resp text by ;:
out = resp.split(';')
Now out is a list of values instead, use indexes to access various items:
print 'Country: {}'.format(out[3])
Alternatively, add format=json to your query string and receive a JSON response from that API:
import json
resp = urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?format=json&key=mykey&ip=someip')
data = json.load(resp)
print data['countryName']
I'm trying to figure out what's the correct URL format for the Intersango API (which is poorly documented). I'm programming my client in C#, but I'm looking at the Python example and I'm a little confused as to what is actually being placed in the body of the request:
def make_request(self,call_name,params):
params.append(('api_key',self.api_key)) // <-- How does this get serialized?
body = urllib.urlencode(params)
self.connect()
try:
self.connection.putrequest('POST','/api/authenticated/v'+self.version+'/'+call_name+'.php')
self.connection.putheader('Connection','Keep-Alive')
self.connection.putheader('Keep-Alive','30')
self.connection.putheader('Content-type','application/x-www-form-urlencoded')
self.connection.putheader('Content-length',len(body))
self.connection.endheaders()
self.connection.send(body)
response = self.connection.getresponse()
return json.load(response)
//...
I can't figure out this piece of code: params.append(('api_key',self.api_key))
Is it some kind of a dictionary, something that gets serialized to JSON, comma delimited, or exactly how does it get serialized? What would the body look like when the parameters are encoded and assigned to it?
P.S. I don't have anything that I can run the code with so I can debug it, but I'm just hoping that this is simple enough to understand for somebody that knows Python and they would be able to tell me what's happening on that line of code.
params is a list of 2-element lists. The list would look like ((key1, value1), (key2, value2), ...)
params.append(('api_key',self.api_key)) adds another 2-element list to the existing params list.
Finally, urllib.urlencode takes this list and converts it into a propert urlencoded string. In this case, it will return a string key1=value1&key2=value2&api_key=23423. If there are any special characters in your keys or values, urlencode will %encode them. See documentation for urlencode
I tried to get the C# code working, and it kept failing with exception {"The remote server returned an error: (417) Expectation Failed."}. I finally found what the problem is. You could read about it in depth here
In short, the way to make C# access Intersango API is to add following code:
System.Net.ServicePointManager.Expect100Continue = false;
This code needs to only run once. This is a global setting, so it affects your full application, so beware that something else could break as a result.
Here's a sample code:
System.Net.ServicePointManager.Expect100Continue = false;
var address = "https://intersango.com/api/authenticated/v0.1/listAccounts.php";
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var postBytes = Encoding.UTF8.GetBytes("api_key=aa75***************fd65785");
request.ContentLength = postBytes.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(postBytes, 0, postBytes.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Piece of cake
instead of params.append(('api_key',self.api_key))
just write:
params['api_key']=self.api_key