【问题标题】:How do I get ONLY Telegram Bot's first_name using get_bot()?如何使用 get_bot() 仅获取 Telegram Bot 的名字?
【发布时间】:2022-11-10 23:26:12
【问题描述】:

我正在使用 Telebot 创建一个 Telegram Bot。

bot.get_me()

get_me() 与 Telegram Bot Api 中的 getme() 相同。 我需要得到机器人的名字。

上面的代码给了我:

{
   "id":5519834543,
   "is_bot":true,
   "first_name":"BOTtle",
   "username":"SomethingnotsurewhatBot",
   "last_name":"None",
   "language_code":"None",
   "can_join_groups":true,
   "can_read_all_group_messages":false,
   "supports_inline_queries":false
}

在 Telegram Bot Api 的文档中,它说 getme() 返回一个 JSON 对象:https://core.telegram.org/bots/api#available-types

我如何要求它只返回first_name 或username?

【问题讨论】:

  • 有什么理由不能从该字典中按键获取 first_name 吗?
  • 你不能,只是解析 JSON 来获取你需要的数据/

标签: telegram telebot


【解决方案1】:

显然你可以使用正则表达式

import re
import telebot


bot=telebot.TeleBot(token="ur token")
resp=str(bot.get_me())
match=re.findall("'first_name': '(.*)', 'user",resp)
print(match[0])

在这里,我使用的是 Telebot,因此正则表达式可能会根据您的 json 响应有所不同,应该是这样的

match=re.findall(r'"first_name":"(.*)"',resp)
您可以参考此正则表达式备忘单以获取详细的正则表达式信息here

【讨论】:

    猜你喜欢
    • 2017-04-20
    • 2018-11-04
    • 1970-01-01
    • 2018-04-10
    • 2016-02-23
    • 2018-12-14
    • 2019-10-01
    • 2015-12-02
    • 1970-01-01
    相关资源
    最近更新 更多