# Channel

The Channel class provides a wrapper for interacting with RabbitMQ implementing the methods and behaviors for an AMQP Channel.

## Channel

class pika.channel.Channel(connection: Connection, channel_number: int, on_open_callback: _OnOpenCallback | None)

  A Channel is the primary communication method for interacting with RabbitMQ. It is recommended that you do not directly invoke the creation of a channel object in your application code but rather construct a channel by calling the active connection’s channel() method.

  add_callback(callback: Callable[..., Any], replies: Sequence[Type[amqp_object.Method]], one_shot: bool = True) → None

    Pass in a callback handler and a list replies from the RabbitMQ broker which you’d like the callback notified of. Callbacks should allow for the frame parameter to be passed in.

    Parameters:

      - callback (callable) – The callback to call

      - replies (list) – The replies to get a callback for

      - one_shot (bool) – Only handle the first type callback

  add_on_cancel_callback(callback: Callable[[Method[Cancel]], Any]) → None

    Pass a callback function that will be called when the basic_cancel is sent by the server. The callback function should receive a frame parameter.

    Parameters:

      callback (callable) – The callback to call on Basic.Cancel from broker

  add_on_close_callback(callback: Callable[[Channel, Exception], None]) → None

    Pass a callback function that will be called when the channel is closed. The callback function will receive the channel and an exception describing why the channel was closed.

    If the channel is closed by broker via Channel.Close, the callback will receive ChannelClosedByBroker as the reason.

    If graceful user-initiated channel closing completes successfully ( either directly of indirectly by closing a connection containing the channel) and closing concludes gracefully without Channel.Close from the broker and without loss of connection, the callback will receive ChannelClosedByClient exception as reason.

    If channel was closed due to loss of connection, the callback will receive another exception type describing the failure.

    Parameters:

      callback (callable) – The callback, having the signature: callback(Channel, Exception reason)

  add_on_flow_callback(callback: Callable[[bool], None]) → None

    Pass a callback function that will be called when Channel.Flow is called by the remote server. Note that newer versions of RabbitMQ will not issue this but instead use TCP backpressure

    Parameters:

      callback (callable) – The callback function

  add_on_return_callback(callback: Callable[[Channel, Return, BasicProperties, bytes], None]) → None

    Pass a callback function that will be called when basic_publish is sent a message that has been rejected and returned by the server.

    Parameters:

      callback (callable) – The function to call, having the signature callback(channel, method, properties, body) where - channel: pika.channel.Channel - method: pika.spec.Basic.Return - properties: pika.spec.BasicProperties - body: bytes

  basic_ack(delivery_tag: int = 0, multiple: bool = False) → None

    Acknowledge one or more messages. When sent by the client, this method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more messages published with the Publish method on a channel in confirm mode. The acknowledgement can be for a single message or a set of messages up to and including a specific message.

    Parameters:

      - delivery_tag (integer) – int/long The server-assigned delivery tag

      - multiple (bool) – If set to True, the delivery tag is treated as “up to and including”, so that multiple messages can be acknowledged with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is 1, and the delivery tag is zero, this indicates acknowledgement of all outstanding messages.

  basic_cancel(consumer_tag: str = '', callback: Callable[[Method[CancelOk]], None] | None = None) → None

    This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an arbitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. It may also be sent from the server to the client in the event of the consumer being unexpectedly cancelled (i.e. cancelled for any reason other than the server receiving the corresponding basic.cancel from the client). This allows clients to be notified of the loss of consumers due to events such as queue deletion.

    Parameters:

      - consumer_tag (str) – Identifier for the consumer

      - callback (callable) – callback(pika.frame.Method) for method Basic.CancelOk. If None, do not expect a Basic.CancelOk response, otherwise, callback must be callable

    Raises:

      ValueError –

  basic_consume(queue: str, on_message_callback: Callable[[Channel, Deliver, BasicProperties, bytes], None], auto_ack: bool = False, exclusive: bool = False, consumer_tag: str | None = None, arguments: Dict[str, Any] | None = None, callback: Callable[[Method[ConsumeOk]], None] | None = None) → str

    Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds messages for the consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be automatically generated for you. Returns the consumer tag.

    For more information on basic_consume, see: Tutorial 2 at https://www.rabbitmq.com/getstarted.html https://www.rabbitmq.com/confirms.html https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

    Parameters:

      - queue (str) – The queue to consume from. Use the empty string to specify the most recent server-named queue for this channel

      - on_message_callback (callable) – The function to call when consuming with the signature on_message_callback(channel, method, properties, body), where - channel: pika.channel.Channel - method: pika.spec.Basic.Deliver - properties: pika.spec.BasicProperties - body: bytes

      - auto_ack (bool) – if set to True, automatic acknowledgement mode will be used (see https://www.rabbitmq.com/confirms.html). This corresponds with the ‘no_ack’ parameter in the basic.consume AMQP 0.9.1 method

      - exclusive (bool) – Don’t allow other consumers on the queue

      - consumer_tag (str) – Specify your own consumer tag

      - arguments (dict) – Custom key/value pair arguments for the consumer

      - callback (callable) – callback(pika.frame.Method) for method Basic.ConsumeOk.

    Returns:

      Consumer tag which may be used to cancel the consumer.

    Return type:

      str

    Raises:

      ValueError –

  basic_get(queue: str, callback: Callable[[Channel, GetOk, BasicProperties, bytes], None], auto_ack: bool = False) → None

    Get a single message from the AMQP broker. If you want to be notified of Basic.GetEmpty, use the Channel.add_callback method adding your Basic.GetEmpty callback which should expect only one parameter, frame. Due to implementation details, this cannot be called a second time until the callback is executed. For more information on basic_get and its parameters, see:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get

    Parameters:

      - queue (str) – The queue from which to get a message. Use the empty string to specify the most recent server-named queue for this channel

      - callback (callable) – The callback to call with a message that has the signature callback(channel, method, properties, body), where: - channel: pika.channel.Channel - method: pika.spec.Basic.GetOk - properties: pika.spec.BasicProperties - body: bytes

      - auto_ack (bool) – Tell the broker to not expect a reply

    Raises:

      ValueError –

  basic_nack(delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) → None

    This method allows a client to reject one or more incoming messages. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue.

    Parameters:

      - delivery_tag (integer) – int/long The server-assigned delivery tag

      - multiple (bool) – If set to True, the delivery tag is treated as “up to and including”, so that multiple messages can be acknowledged with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is 1, and the delivery tag is zero, this indicates acknowledgement of all outstanding messages.

      - requeue (bool) – If requeue is true, the server will attempt to requeue the message. If requeue is false or the requeue attempt fails the messages are discarded or dead-lettered.

  basic_publish(exchange: str, routing_key: str, body: bytes, properties: BasicProperties | None = None, mandatory: bool = False) → None

    Publish to the channel with the given exchange, routing key and body. For more information on basic_publish and what the parameters do, see:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish

    Parameters:

      - exchange (str) – The exchange to publish to

      - routing_key (str) – The routing key to bind on

      - body (bytes) – The message body

      - properties (pika.spec.BasicProperties) – Basic.properties

      - mandatory (bool) – The mandatory flag

  basic_qos(prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False, callback: Callable[[Method[QosOk]], None] | None = None) → None

    Specify quality of service. This method requests a specific quality of service. The client can request that messages be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. The QoS can be applied separately to each new consumer on channel or shared across all consumers on the channel. Prefetching gives a performance improvement.

    Parameters:

      - prefetch_size (int) – This field specifies the prefetch window size. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls into other prefetch limits). May be set to zero, meaning “no specific limit”, although other prefetch limits may still apply. The prefetch-size is ignored by consumers who have enabled the no-ack option.

      - prefetch_count (int) – Specifies a prefetch window in terms of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch-count is ignored by consumers who have enabled the no-ack option.

      - global_qos (bool) – Should the QoS be shared across all consumers on the channel.

      - callback (callable) – The callback to call for Basic.QosOk response

    Returns:

      `None`. Method frame from the Basic.Qos-ok response is delivered to `callback` when provided.

    Raises:

      ValueError –

  basic_reject(delivery_tag: int = 0, requeue: bool = True) → None

    Reject an incoming message. This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue.

    Parameters:

      - delivery_tag (integer) – int/long The server-assigned delivery tag

      - requeue (bool) – If requeue is true, the server will attempt to requeue the message. If requeue is false or the requeue attempt fails the messages are discarded or dead-lettered.

    Raises:

      TypeError

  basic_recover(requeue: bool = False, callback: Callable[[Method[RecoverOk]], None] | None = None) → None

    This method asks the server to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered. This method replaces the asynchronous Recover.

    Parameters:

      - requeue (bool) – If False, the message will be redelivered to the original recipient. If True, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber.

      - callback (callable) – callback(pika.frame.Method) for method Basic.RecoverOk

    Returns:

      `None`. Method frame from the Basic.Recover-ok response is delivered to `callback` when provided.

    Raises:

      ValueError –

  close(reply_code: int = 0, reply_text: str = 'Normal shutdown') → None

    Invoke a graceful shutdown of the channel with the AMQP Broker.

    If channel is OPENING, transition to CLOSING and suppress the incoming Channel.OpenOk, if any.

    Parameters:

      - reply_code (int) – The reason code to send to broker

      - reply_text (str) – The reason text to send to broker

    Raises:

      ChannelWrongStateError – if channel is closed or closing

  confirm_delivery(ack_nack_callback: Callable[[Method[Ack | Nack]], None], callback: Callable[[Method[SelectOk]], None] | None = None) → None

    Turn on Confirm mode in the channel. Pass in a callback to be notified by the Broker when a message has been confirmed as received or rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.

    For more information see:

      https://www.rabbitmq.com/confirms.html

    Parameters:

      - ack_nack_callback (callable) – Required callback for delivery confirmations that has the following signature: callback(pika.frame.Method), where method_frame contains either method spec.Basic.Ack or spec.Basic.Nack.

      - callback (callable) – callback(pika.frame.Method) for method Confirm.SelectOk

    Raises:

      ValueError –

  property consumer_tags: List[str]

    Property method that returns a list of currently active consumers

    Return type:

      list

  exchange_bind(destination: str, source: str, routing_key: str = '', arguments: Dict[str, Any] | None = None, callback: Callable[[Method[BindOk]], None] | None = None) → None

    Bind an exchange to another exchange.

    Parameters:

      - destination (str) – The destination exchange to bind

      - source (str) – The source exchange to bind to

      - routing_key (str) – The routing key to bind on

      - arguments (dict) – Custom key/value pair arguments for the binding

      - callback (callable) – callback(pika.frame.Method) for method Exchange.BindOk

    Returns:

      `None`. Method frame from the Exchange.Bind-ok response is delivered to `callback` when synchronous (no ok frame in nowait mode).

    Raises:

      ValueError –

  exchange_declare(exchange: str, exchange_type: str = ExchangeType.direct, passive: bool = False, durable: bool = False, auto_delete: bool = False, internal: bool = False, arguments: Dict[str, Any] | None = None, callback: Callable[[Method[DeclareOk]], None] | None = None) → None

    This method creates an exchange if it does not already exist, and if the exchange exists, verifies that it is of the correct and expected class.

    If passive set, the server will reply with Declare-Ok if the exchange already exists with the same name, and raise an error if not and if the exchange does not already exist, the server MUST raise a channel exception with reply code 404 (not found).

    Parameters:

      - exchange (str) – The exchange name consists of a non-empty sequence of these characters: letters, digits, hyphen, underscore, period, or colon

      - exchange_type (str) – The exchange type to use

      - passive (bool) – Perform a declare or just check to see if it exists

      - durable (bool) – Survive a reboot of RabbitMQ

      - auto_delete (bool) – Remove when no more queues are bound to it

      - internal (bool) – Can only be published to by other exchanges

      - arguments (dict) – Custom key/value pair arguments for the exchange

      - callback (callable) – callback(pika.frame.Method) for method Exchange.DeclareOk

    Returns:

      `None`. Method frame from the Exchange.Declare-ok response is delivered to `callback` when synchronous (no ok frame in nowait mode).

    Raises:

      ValueError –

  exchange_delete(exchange: str | None = None, if_unused: bool = False, callback: Callable[[Method[DeleteOk]], None] | None = None) → None

    Delete the exchange.

    Parameters:

      - exchange (str) – The exchange name

      - if_unused (bool) – only delete if the exchange is unused

      - callback (callable) – callback(pika.frame.Method) for method Exchange.DeleteOk

    Returns:

      `None`. Method frame from the Exchange.Delete-ok response is delivered to `callback` when synchronous (no ok frame in nowait mode).

    Raises:

      ValueError –

  exchange_unbind(destination: str | None = None, source: str | None = None, routing_key: str = '', arguments: Dict[str, Any] | None = None, callback: Callable[[Method[UnbindOk]], None] | None = None) → None

    Unbind an exchange from another exchange.

    Parameters:

      - destination (str) – The destination exchange to unbind

      - source (str) – The source exchange to unbind from

      - routing_key (str) – The routing key to unbind

      - arguments (dict) – Custom key/value pair arguments for the binding

      - callback (callable) – callback(pika.frame.Method) for method Exchange.UnbindOk

    Returns:

      `None`. Method frame from the Exchange.Unbind-ok response is delivered to `callback` when synchronous (no ok frame in nowait mode).

    Raises:

      ValueError –

  flow(active: bool, callback: Callable[[bool], None] | None = None) → None

    Turn Channel flow control off and on. Pass a callback to be notified of the response from the server. active is a bool. Callback should expect a bool in response indicating channel flow state. For more information, please reference:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow

    Parameters:

      - active (bool) – Turn flow on or off

      - callback (callable) – callback(bool) upon completion

    Raises:

      ValueError –

  property is_closed: bool

    Returns True if the channel is closed.

    Return type:

      bool

  property is_closing: bool

    Returns True if client-initiated closing of the channel is in progress.

    Return type:

      bool

  property is_open: bool

    Returns True if the channel is open.

    Return type:

      bool

  property is_opening: bool

    Returns True if the channel is opening.

    Return type:

      bool

  open() → None

    Open the channel

  queue_bind(queue: str, exchange: str, routing_key: str | None = None, arguments: Dict[str, Any] | None = None, callback: Callable[[Method[BindOk]], None] | None = None) → None

    Bind the queue to the specified exchange

    Parameters:

      - queue (str) – The queue to bind to the exchange

      - exchange (str) – The source exchange to bind to

      - routing_key (str) – The routing key to bind on

      - arguments (dict) – Custom key/value pair arguments for the binding

      - callback (callable) – callback(pika.frame.Method) for method Queue.BindOk

    Returns:

      `None`. Method frame from the Queue.Bind-ok response is delivered to `callback` when synchronous (no ok frame in nowait mode).

    Raises:

      ValueError –

  queue_declare(queue: str, passive: bool = False, durable: bool = False, exclusive: bool = False, auto_delete: bool = False, arguments: Dict[str, Any] | None = None, callback: Callable[[Method[DeclareOk]], None] | None = None) → None

    Declare queue, create if needed. This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue.

    Use an empty string as the queue name for the broker to auto-generate one

    Parameters:

      - queue (str) – The queue name; if empty string, the broker will create a unique queue name

      - passive (bool) – Only check to see if the queue exists

      - durable (bool) – Survive reboots of the broker

      - exclusive (bool) – Only allow access by the current connection

      - auto_delete (bool) – Delete after consumer cancels or disconnects

      - arguments (dict) – Custom key/value arguments for the queue

      - callback (callable) – callback(pika.frame.Method) for method Queue.DeclareOk

    Returns:

      `None`. Method frame from the Queue.Declare-ok response is delivered to `callback` when synchronous (no ok frame in nowait mode).

    Raises:

      ValueError –

  queue_delete(queue: str, if_unused: bool = False, if_empty: bool = False, callback: Callable[[Method[DeleteOk]], None] | None = None) → None

    Delete a queue from the broker.

    Parameters:

      - queue (str) – The queue to delete

      - if_unused (bool) – only delete if it’s unused

      - if_empty (bool) – only delete if the queue is empty

      - callback (callable) – callback(pika.frame.Method) for method Queue.DeleteOk

    Returns:

      `None`. Method frame from the Queue.Delete-ok response is delivered to `callback` when synchronous (no ok frame in nowait mode).

    Raises:

      ValueError –

  queue_purge(queue: str, callback: Callable[[Method[PurgeOk]], None] | None = None) → None

    Purge all of the messages from the specified queue

    Parameters:

      - queue (str) – The queue to purge

      - callback (callable) – callback(pika.frame.Method) for method Queue.PurgeOk

    Returns:

      `None`. Method frame from the Queue.Purge-ok response is delivered to `callback` when synchronous (no ok frame in nowait mode).

    Raises:

      ValueError –

  queue_unbind(queue: str, exchange: str | None = None, routing_key: str | None = None, arguments: Dict[str, Any] | None = None, callback: Callable[[Method[UnbindOk]], None] | None = None) → None

    Unbind a queue from an exchange.

    Parameters:

      - queue (str) – The queue to unbind from the exchange

      - exchange (str) – The source exchange to bind from

      - routing_key (str) – The routing key to unbind

      - arguments (dict) – Custom key/value pair arguments for the binding

      - callback (callable) – callback(pika.frame.Method) for method Queue.UnbindOk

    Returns:

      `None`. Method frame from the Queue.Unbind-ok response is delivered to `callback` when provided.

    Raises:

      ValueError –

  tx_commit(callback: Callable[[CommitOk], None] | None = None) → None

    Commit a transaction

    Parameters:

      callback (callable) – callback(pika.frame.Method) for method Tx.CommitOk

    Returns:

      `None`. Method frame from the Tx.Commit-ok response is delivered to `callback` when provided.

    Raises:

      ValueError –

  tx_rollback(callback: Callable[[RollbackOk], None] | None = None) → None

    Rollback a transaction.

    Parameters:

      callback (callable) – callback(pika.frame.Method) for method Tx.RollbackOk

    Returns:

      `None`. Method frame from the Tx.Rollback-ok response is delivered to `callback` when provided.

    Raises:

      ValueError –

  tx_select(callback: Callable[[SelectOk], None] | None = None) → None

    Select standard transaction mode. This method sets the channel to use standard transactions. The client must use this method at least once on a channel before using the Commit or Rollback methods.

    Parameters:

      callback (callable) – callback(pika.frame.Method) for method Tx.SelectOk

    Returns:

      `None`. Method frame from the Tx.Select-ok response is delivered to `callback` when provided.

    Raises:

      ValueError –