How to get Invoice comments list programmatically in Magento 2?

Magento gets all the comments for invoices by its Id to track for a given order payment stuff.

Invoice comments will be added by the Store admin representative from the backend for the invoice query.

Comments can be notified by customer email and also display in the frontend invoice section if the checkbox is checked by the admin when creating any new comments from the backend.

The class responsible for the fetch list of comments from the invoice, Magento\Sales\Api\InvoiceManagementInterface

<?php
namespace Jesadiya\Comments\Model;

use Exception;
use Magento\Sales\Api\InvoiceManagementInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Api\Data\InvoiceCommentSearchResultInterface;

class Comments
{
    /**
     * @var InvoiceManagementInterface
     */
    private $invoiceService;

    public function __construct(
        InvoiceManagementInterface $invoiceService
    ) {
        $this->invoiceService = $invoiceService;
    }

    /**
     * @param int $invoiceId
     * @return InvoiceCommentSearchResultInterface|null
     * @throws Exception
     */
    public function getComments($invoiceId): ?InvoiceCommentSearchResultInterface
    {
        $invoiceComments = null;
        
        try {
            $invoiceComments = $this->invoiceService->getCommentsList($invoiceId);
        } catch (NoSuchEntityException $exception) {
            throw new Exception($exception->getMessage());
        }
        
        return $invoiceComments;
    }
}

Call method with a required parameter, Be careful to assign the Invoice Id, not the order id. Verify Invoice has Comments available or not by the getTotalCount().

$invoiceId = 1; // Invoice id
$invoiceComments = $this->getComments($invoiceId);
if ($invoiceComments->getTotalCount()) {
	foreach($invoiceComment as $comment) {
        echo "<pre>";print_r($comment->debug());
    }
}

Output: Magento\Sales\Api\Data\InvoiceCommentSearchResultInterface

If the Invoice contains the Comments, the response will be an array of comments otherwise the value will be null.

You might be interested in the article, Capture Invoice Programmatically.