【问题标题】:How to get telegram chat id如何获取电报聊天ID
【发布时间】:2023-12-02 18:03:02
【问题描述】:

所以我有这个 python 代码,它可以计算出频道聊天 ID,以便为给定列表中的多个频道发送消息。

我只有频道邀请链接

我仍然不知道如何仅通过名称获取频道 ID。

import os
import telebot
API_KEY = os.environ['API_KEY']
bot = telebot.TeleBot(API_KEY)
a=input("edit msg.txt to send the msg if done press enter")
message=open("message.txt","a+")
bot.send_message(chat_id,message)

【问题讨论】:

    标签: telegram-bot


    【解决方案1】:

    您可以使用getChat 方法将频道用户名解析为聊天ID。您也可以使用用户名发送消息 - 请参阅sendMessage 的文档,例如this answer.

    【讨论】:

    • 我只有频道邀请链接
    • AFAIK 没有办法做到这一点,至少不能使用纯 bot api。
    【解决方案2】:

    如果您更喜欢将 Telegram API 与 javascriptaxios 库一起使用,那么您可以考虑以下几点:

    const method = 'get'
    
    const headers: any = {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
      timestamp: +new Date(),
    }
    
    const options = { headers: { ...headers } }
    
    const urlTelegramBase =
      'https://api.telegram.org/bot123456:ABCDEF'
    
    const urlGetUpdates = `${urlTelegramBase}/getUpdates`
    const username = 'user_name'
    
    const {
      data: { result: messages },
    } = await axios[method](urlGetUpdates, options)
    
    const chat_id = messages.find(
      messageBlock => messageBlock.message.chat.username === username
    ).message.chat.id
    
    console.info('chat_id': chat_id)
    

    【讨论】: