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

iOS端Telegram小程序window.open调用转发链接异常问题求助

Telegram机器人iOS端转发功能适配问题

问题描述

开发Telegram机器人时,实现了从小程序将指定消息转发到聊天的功能,通过window.open(url, '_blank')实现。该功能在电脑端和Android设备上运行正常,但在iPhone上点击后弹出的是分享界面而非转发界面,不符合需求,需要用户友好的解决方案。

相关代码

1) app.py

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, CallbackContext, filters
from collections import defaultdict
from credentials import BOT_TOKEN, WEBAPP_URL

# 存储用户已转发的聊天ID
user_forwarded_chats = defaultdict(set)

# 要求的转发次数
REQUIRED_FORWARDS = 5

async def start(update: Update, context: CallbackContext):
    # 启动带"分享"按钮的Web应用
    keyboard = [
        [InlineKeyboardButton("Поделиться", web_app=WebAppInfo(WEBAPP_URL))]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await update.message.reply_text(
        "Перешлите сообщение 5 раз в разные чаты и получите награду.",
        reply_markup=reply_markup
    )

async def track_forwarded_message(update: Update, context: CallbackContext):
    if update.message.forward_from_chat:
        user_id = update.message.from_user.id
        chat_id = update.message.chat.id

        # 检查该聊天是否已被转发过
        if chat_id not in user_forwarded_chats[user_id]:
            user_forwarded_chats[user_id].add(chat_id)

            await update.message.reply_text(
                f"Сообщение переслано в {len(user_forwarded_chats[user_id])} из {REQUIRED_FORWARDS} уникальных чатов."
            )

            if len(user_forwarded_chats[user_id]) >= REQUIRED_FORWARDS:
                await update.message.reply_text("Молодцы, вы выполнили условия!")
                # 完成任务后重置计数器
                user_forwarded_chats[user_id] = set()
        else:
            await update.message.reply_text(
                "Вы уже пересылали сообщение в этот чат. Перешлите его в другой чат."
            )
    else:
        await update.message.reply_text(
            "Это не пересланное сообщение из чата. Пожалуйста, пересылайте сообщения в разные чаты."
        )

if __name__ == '__main__':
    application = ApplicationBuilder().token(BOT_TOKEN).build()

    application.add_handler(CommandHandler('start', start))
    application.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, track_forwarded_message))

    print("Бот запущен!")
    application.run_polling()

2) index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Telegram Web App</title>
  <script>
    window.onload = function() {
      console.log("Page Loaded");

      // 创建"Share in Telegram"按钮
      const shareButton = document.createElement('button');
      shareButton.textContent = "Share in Telegram";
      shareButton.style.fontSize = "16px";
      shareButton.style.padding = "10px 20px";
      shareButton.style.cursor = "pointer";

      // 按钮点击事件处理
      shareButton.onclick = function() {
        console.log("Share Button Clicked");

        // 打开Telegram的"分享帖子"窗口
        const postUrl = "https://t.me/dvachannel/143325";
        const telegramShareUrl = `https://t.me/share/url?url=${encodeURIComponent(postUrl)}`;
        window.open(telegramShareUrl, '_blank');
      };

      // 将按钮添加到页面
      document.body.appendChild(shareButton);
    };
  </script>
</head>
<body>
  <h1>Hello, Telegram!</h1>
</body>
</html>

使用的转发链接为:https://t.me/dvachannel/143325,该链接在电脑和安卓端可正常实现转发。

解决方案建议

1. 使用Telegram Web App原生API(推荐)

Telegram Web App提供了专门的客户端交互API,能更好适配移动端(包括iOS),避免系统跳转带来的行为差异。

修改index.html:

  • 首先引入Telegram Web App的官方脚本:
<script src="https://telegram.org/js/telegram-web-app.js"></script>
  • 然后替换按钮的点击事件处理逻辑:
shareButton.onclick = function() {
  console.log("Share Button Clicked");
  const postUrl = "https://t.me/dvachannel/143325";
  // 使用Telegram Web App API直接在内部打开链接
  Telegram.WebApp.openTelegramLink(postUrl);
};

这个方法会直接唤起Telegram内部的转发流程,在iOS上也会显示正确的转发界面而非系统分享弹窗。

2. 调整deeplink格式

如果不想依赖Web App API,可以尝试使用Telegram的直接转发deeplink格式:

const telegramForwardUrl = `tg://forward?text=${encodeURIComponent(postUrl)}`;
window.open(telegramForwardUrl, '_blank');

不过这个方式需要用户手动选择聊天,且部分iOS版本可能需要额外处理,但相比原分享链接更贴近转发逻辑。

3. 提示用户更新Telegram客户端

部分旧版本的Telegram iOS客户端对web链接的处理存在兼容性问题,在Web App中添加提示,引导用户更新到最新版本的Telegram,可以解决部分历史版本的异常行为。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:54:50