You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Telegram多Chat ID消息发送报错求助

问题描述

原本可正常向单个Chat ID发送消息的Telethon代码如下:

import telebot
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser, InputPeerChannel
from telethon import TelegramClient, sync, events

api_id = 00000000
api_hash = 'xxxxxxxxxxxxxxx'
token = 'xxxxxxxxxxxxxxxxxxxxxxx'
my_channel_id = -100000000000 #destination

message = "TEST LTDSH 0-0 Alerts\n\n" + match + "\n" + flagscode + " " + tournamentsts + "\n\U0001F55B Elapsed Time: " + resultlive3 + "\n\u26bd Score: " + resultlive1

phone = '+000000000'

client = TelegramClient('session', api_id, api_hash)

client.connect()

if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

try:
    client.send_message(my_channel_id, message, parse_mode='html')
except Exception as e:
    print(e);

client.disconnect()

尝试将目标Chat ID改为列表形式:

my_channel_id = [-100000000, -10000001] #destination

运行时触发错误:Cannot cast list to any kind of Peer.,需解决该问题。

解决办法

client.send_message()方法仅接受单个Peer对象或单个Chat ID作为目标参数,不支持直接传入列表。要实现批量发送,需遍历列表中的每个Chat ID,逐个调用发送方法:

修改核心逻辑

将原有的单个ID发送逻辑替换为遍历列表的循环:

# 定义目标Chat ID列表
my_channel_ids = [-100000000, -10000001]

try:
    # 遍历每个ID发送消息
    for chat_id in my_channel_ids:
        client.send_message(chat_id, message, parse_mode='html')
except Exception as e:
    print(e)

完整修改后的代码

import telebot
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser, InputPeerChannel
from telethon import TelegramClient, sync, events

api_id = 00000000
api_hash = 'xxxxxxxxxxxxxxx'
token = 'xxxxxxxxxxxxxxxxxxxxxxx'
# 改用列表存储多个目标Chat ID
my_channel_ids = [-100000000, -10000001] #destination

message = "TEST LTDSH 0-0 Alerts\n\n" + match + "\n" + flagscode + " " + tournamentsts + "\n\U0001F55B Elapsed Time: " + resultlive3 + "\n\u26bd Score: " + resultlive1

phone = '+000000000'

client = TelegramClient('session', api_id, api_hash)

client.connect()

if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

try:
    # 遍历列表逐个发送消息
    for chat_id in my_channel_ids:
        client.send_message(chat_id, message, parse_mode='html')
except Exception as e:
    print(e)

client.disconnect()

内容的提问来源于stack exchange,提问作者Marcello Gabrielli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 19:50:03