我试图用python从头开始创建一个电报机器人。我已经完成了所有的初始步骤并获得了bot令牌,现在我想做的是,为了方便地操作它发送给我的数据(比如从getupdates
方法中获取此人的first_name
),我希望数据整齐地排列到python字典中。在
当我尝试/getme
时,我得到的是:
b'{"ok":true,"result":{"id":999999999,"first_name":"telebotsrock","username":"sample_bot"}}'
因为开始的b'
和结尾的{json.loads(data)
(其中数据是上面给出的转换成字符串的东西)时会导致错误。在
所以我做了data[2:-1]
来删除b'
和{/getme
改为/getupdates
时,就会出现一堆新的错误。在
总而言之,这里一团糟。有人能给我一个干净的方法从机器人获取数据并将其分类到python字典中吗?请不要告诉我使用其他语言或只是复制现有的bot框架。在
我的当前代码:
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)
这段代码正确地将/getme
的输出转换为python字典,但是当我改为尝试/getupdates
时会出现错误。在
在我切片之前,/getupdates
的输出是:
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"}}]}'
这应该对你有用。您可以使用
.decode('utf-8')
删除字节前缀。在相关问题 更多 >
编程相关推荐