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

PHP Telegram Bot实现特定用户消息复制功能的技术方案

How to Implement a Toggleable Copy Mode for Specific Users

Got it, let's break this down step by step. The core challenge here is tracking the user's current state—your bot needs to remember which user has requested copy mode, is waiting to confirm, or is actively copying messages. Here's a practical implementation:

1. First, Add a State Tracking Variable

You'll need a way to store the current mode for each user (since multiple users might interact with your bot at once). For a simple setup, use an associative array where the key is the user's chatid and the value is their current state:

// Initialize this outside your message handler (so it persists between requests)
$userStates = [];

2. Update Your Message Handling Logic

Modify your existing code to check the user's state first, then respond accordingly:

// Assume $chatid is the current user's chat ID, $message is their incoming text

// Check if the user is already in copy mode
if (isset($userStates[$chatid]) && $userStates[$chatid] === 'copying') {
    if ($message === 'stop') {
        // Exit copy mode
        sendMessage($chatid, "Copy mode stopped!");
        unset($userStates[$chatid]);
    } else {
        // Copy the user's message back
        sendMessage($chatid, $message);
    }
} 
// Check if we're waiting for the user to confirm with "yes"
else if (isset($userStates[$chatid]) && $userStates[$chatid] === 'waiting_yes') {
    if (strtolower($message) === 'yes') {
        // Switch to copy mode
        sendMessage($chatid, "Got it! I'll copy your messages until you send 'stop'.");
        $userStates[$chatid] = 'copying';
    } else {
        // Cancel the request
        sendMessage($chatid, "Copy request canceled.");
        unset($userStates[$chatid]);
    }
}
// Handle the initial "Bot copy me" trigger
else if ($message === "Bot copy me") {
    sendMessage($chatid, "Sure?");
    $userStates[$chatid] = 'waiting_yes';
}
// Add other bot commands/handlers here
else {
    // Your existing non-copy related logic goes here
}

Key Notes

  • Case Insensitivity: I added strtolower() for the "yes" check so users can send "Yes", "YES", etc.—makes the bot more user-friendly.
  • State Persistence: If your bot runs on a server that resets variables between requests (like most web-based bots), you'll need to use a persistent storage (like a database, Redis, or even a file) instead of a plain array. For example, save $userStates to a JSON file or a MySQL table and load it on each request.
  • Edge Cases: This code handles users sending random messages while in waiting_yes state by canceling the request—you can adjust that if you want to prompt them again instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:42:52