如何在 Python 中的电报发送消息机器人中使用解析模式

问题描述

我对制作机器人很陌生,所以我有几个问题要问:

  1. 我正在使用机器人发送消息

     def send_message(chat_id,msg):
     url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}"
     requests.get(url)
     send_message(chat_id,msg)
    

通过这个,我可以发送消息,我想通过使用 parse_mode 来美化结果,但我不知道在哪里放入 url 以使其工作。

  1. 我不使用 Telethon。我可以使用它通过用户名和群组邀请链接向个人和群组发送消息,但是当我尝试通过以下方式将其发送到频道时:

    client.send_message(entity='我的频道名称',message=message)

当我尝试运行它时,它返回找不到与“测试通道”对应的任何实体。

我也试试

destination_channel_username='test_ali3'
entity=client.get_entity(destination_channel_username)
client.send_message(entity=entity,message="Hi")

但是它需要我的频道 access_hash,怎么才能得到它,或者有没有其他方法可以向频道发送消息。

  1. 我知道 Telegram bot API 具有像 sendMessage 或 bot.sendMessage 这样的功能也可以完成这项工作,但不知何故我无法调用它,我应该安装和/或导入哪些包。

非常感谢!

解决方法

  1. 这应该可以解决问题:
def send_message(chat_id,msg,parse_mode):
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}&parse_mode={parse_mode}"
    requests.get(url)
  1. TBH 我对 Telethon 不太熟悉,但该库主要用于所谓的用户机器人。这意味着它使用了 Telegram 应用程序也使用的 API,因此,它通常比普通的机器人 API 更复杂。

  2. 要在 Python 中使用 Bot API,我可以推荐包 python-telegram-bot,请参阅 https://python-telegram-bot.org。免责声明:我目前是该软件包的维护者。 bot api还有其他python包,请参见例如https://core.telegram.org/bots/samples#python