You can add Status History Comment for the given order programmatically in Magento 2.
You need to use interface, Magento\Sales\Api\OrderStatusHistoryRepositoryInterface to add a comment. You can also set order status for the comment.
You can check to add sales order status history data programmatically in Magento 2.
You have to Retrieve the Order id to add comment, load order object by the id, add status history comment for the given sales order with some code snippet,
<?php namespace Jesadiya\StatusHistoryComment\Model; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Api\Data\OrderStatusHistoryInterface; use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface; use Psr\Log\LoggerInterface; class Comment { /** @var LoggerInterface */ private $logger; /** @var OrderStatusHistoryRepositoryInterface */ private $orderStatusRepository; /** @var OrderRepositoryInterface */ private $orderRepository; public function __construct( OrderStatusHistoryRepositoryInterface $orderStatusRepository, OrderRepositoryInterface $orderRepository, LoggerInterface $logger ) { $this->orderStatusRepository = $orderStatusRepository; $this->orderRepository = $orderRepository; $this->logger = $logger; } /** * add comment to the order history * * @param int $orderId * @return OrderStatusHistoryInterface|null */ public function addCommentToOrder(int $orderId) { $order = null; try { $order = $this->orderRepository->get($orderId); } catch (NoSuchEntityException $exception) { $this->logger->error($exception->getMessage()); } $orderHistory = null; if ($order) { $comment = $order->addStatusHistoryComment( 'Comment for the order' ); try { $orderHistory = $this->orderStatusRepository->save($comment); } catch (\Exception $exception) { $this->logger->critical($exception->getMessage()); } } return $orderHistory; } }
You can pass order status for the comment if you want using the second parameter in addStatusHistoryComment($message, $status) method.
Call method with a required parameter,
$orderId = 5; $statusHistoryComment = $this->addCommentToOrder($orderId);
Output:

\Magento\Sales\Api\Data\OrderStatusHistoryInterface Order status history interface