You need to enable JavaScript to run this app. 如何用laravel-notification-channels/telegram实现TelegramBot加用户入频道
优惠活动
大模型
产品
解决方案
定价
更多

如何用laravel-notification-channels/telegram实现TelegramBot加用户入频道

实现方案

直接调用Telegram Bot原生的addChatMember接口即可,laravel-notification-channels/telegram底层依赖的Bot SDK已经封装了该方法,不需要额外安装扩展。

具体代码修改

  1. 预先定义你的频道chat ID(格式一般为-100xxxxxxxx,可通过转发频道消息给@userinfobot获取)
  2. 在toTelegram方法中加入添加成员的逻辑,建议加异常捕获避免接口报错影响欢迎通知的发送:
// 替换为你自己的频道chat ID
protected $channelChatId = '-100xxxxxxxx';

public function toTelegram($notifiable)
{
  // 先向Bot发送消息以对应用户身份
  TelegramMessage::create()
    ->to('MY_BOT_ID');

  // 新增添加用户到频道逻辑
  try {
    \Telegram::addChatMember([
      'chat_id' => $this->channelChatId,
      'user_id' => $this->telegram_id,
      // 可选:配置用户在频道内的权限,按需调整
      'can_send_messages' => true,
      'can_send_media_messages' => true,
    ]);
  } catch (\Exception $e) {
    // 捕获异常场景:用户拒绝被添加、已在频道内、权限不足等,记录日志即可
    \Log::error('Telegram用户加入频道失败', [
      'telegram_id' => $this->telegram_id,
      'error' => $e->getMessage()
    ]);
  }

  // 再由Bot向用户发送消息
  return TelegramFile::create()
    ->to($this->telegram_id)
    ->content("Hello");
}

注意事项

  • 若接口返回400错误,一般是用户未主动和Bot对话过,或是用户隐私设置禁止被添加到群/频道,该限制为Telegram平台规则,无法绕过,可改为给用户发送频道邀请链接手动加入。
  • 若返回403错误,需确认Bot的管理员权限已开启「添加成员」选项。
  • 若用户曾经主动退出过该频道,Bot无法直接添加,仅能发送邀请链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 12:06:07