python - 使用 Telegram API 时将关键字作为属性

标签 python telegram telegram-bot python-telegram-bot

在 Telegram 中,当用户按下按钮时,机器人会收到 JSON 格式的信息:

'update':
{
    'callback_query':
    {
        'from':
        {
            'id':420220883
        }
    }
}

此 JSON 对象中有更多信息,但我只对 id 部分感兴趣。

现在,当我想像 update.callback_query.from.id 一样访问它时,它显然会给出 SyntaxError 错误,因为 from 是Python 关键字。

所以我的问题是; 我该如何使用这些信息?

请注意,我尝试像字典一样使用它update['callback_query']['from']['id'],但它给出了一个奇怪的错误。

enter image description here

最佳答案

您发布的数据结构不是有效的 JSON 也不是有效的字典。将其转换为有效的字典后,您可以轻松获取“id”

data = {'update':
    {
        'callback_query':
            {
                'from':
                    {
                        'id': 420220883
                    }
            }
    }}

print(data['update']['callback_query']['from']['id'])

输出

420220883

关于python - 使用 Telegram API 时将关键字作为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54958218/

相关文章:

python - Flask 应用程序在确认 Flask 安装后,elasticbeanstalk 中没有名为 Flask 的模块错误

python - 跳过字典中的一个字母

python - 命名与通配符导入为何/如何影响参数?

python - 在 Tkinter 中如何不断获取 slider 值

telegram - Telegram bot API 可以播放来自在线音频流 URL 的声音吗?

markdown - 有没有办法验证 Telegram bot api Markdown 语法?

php - 如何在与 api.ai 集成的 Telegram 机器人中显示键盘按钮?

python - 如何将python输出发送到 Telegram channel 而不是组和gmail电子邮件组

video - 哪种视频格式适合 Telegram Bot API 中的 `sendVideo` 方法

xpath - 使用 xpath 和 Telegram 即时 View 提取、创建和附加