我认为使用按钮发送消息是更好的方式。
会是这样的:
- 用户发送 /start 命令
- 用户发送任何消息
- Bot 使用按钮回复用户的消息
- 用户选择一个按钮
- 机器人将消息复制到选定的聊天室
- Bot 以成功或失败回答用户
使用此代码:
# Configuration that you need to fill
# Bot token obtained from @BotFather
define('BOT_TOKEN', 'Put your bot token here');
# Chat IDs Or Usernames that messages will be copied to
$chats =
[
# Username/ID => 'Chat title'
'@MyOwnGroup' => 'The bot creator group',
'1265170068' => 'My own account'
];
# Function to call any Bot API method
function bot(string $method, array $data = [])
{
$api_url = 'https://api.telegram.org/bot' . BOT_TOKEN . "/$method";
if (count(data) > 0)
{
$api_url .= '?'.http_build_url($data, '', '&');
}
return file_get_contents($api_url);
}
# The update data, Received from Telegram
$update = json_decode(file_get_contents('php://input'));
# Handle if new message received
if (property_exists($update, 'message') && $update->message->text !== '/start')
{
$message = $update->message;
$buttons = ['inline_keyboard' => []];
foreach ($chats as $chat_id => $chat_title)
{
array_push($buttons['inline_keyboard'], [['text' => $chat_title, 'callback_query' => $chat_id]]);
}
# Sending message with buttons to get which group the user wants
bot('sendMessage', [
'chat_id' => $message->chat->id,
'text' => 'Select which group you want to send the message..',
'reply_to_message_id' => $message->message_id,
'reply_markup' => json_encode($buttons)
]);
}
# Handle if one of buttons was pressed
if (property_exists($update, 'callback_query'))
{
$callback_query = $update->callback_query;
# Copy the message
$result = bot('copyMessage', [
'from_chat_id' => $callback_query->message->chat->id,
'message_id' => $callback_query->message->message_id,
'chat_id' => $callback_query->data
]);
if ($result->ok == true)
{
bot('answerCallbackQuery', [
'callback_query_id' => $callback_query->id,
'text' => 'Message was sent successfully!'
]);
}
else
{
bot('answerCallbackQuery', [
'callback_query_id' => $callback_query->id,
'text' => 'Message sending failed!',
'show_alert' => true
]);
}
}