> ## Documentation Index
> Fetch the complete documentation index at: https://www.cometchat.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Message Translation

> Message Translation — CometChat documentation.

The Message Translation extension helps you translate messages into multiple languages.

## Extension settings

1. Login to [CometChat](https://app.cometchat.com/login) and select your app.
2. Go to the Extensions section and enable the Message Translation extension.

## How does it work?

The messages translation extension allows the receivers of the message to translate it in the language of their choice.

In a group of multi-lingual people, a message sent by one of the participants can be in English. However, it can be translated by other members of the group to their languages.

We support translations in the following languages:

| Language              | Language code |
| --------------------- | ------------- |
| Afrikaans             | af            |
| Albanian              | sq            |
| Amharic               | am            |
| Arabic                | ar            |
| Armenian              | hy            |
| Azerbaijani           | az            |
| Bengali               | bn            |
| Bosnian               | bs            |
| Bulgarian             | bg            |
| Catalan               | ca            |
| Chinese (Simplified)  | zh            |
| Chinese (Traditional) | zh-TW         |
| Croatian              | hr            |
| Czech                 | cs            |
| Danish                | da            |
| Dari                  | fa-AF         |
| Dutch                 | nl            |
| English               | en            |
| Estonian              | et            |
| Farsi (Persian)       | fa            |
| Filipino, Tagalog     | tl            |
| Finnish               | fi            |
| French                | fr            |
| French (Canada)       | fr-CA         |
| Georgian              | ka            |
| German                | de            |
| Greek                 | el            |
| Gujarati              | gu            |
| Haitian Creole        | ht            |
| Hausa                 | ha            |
| Hebrew                | he            |
| Hindi                 | hi            |
| Hungarian             | hu            |
| Icelandic             | is            |
| Indonesian            | id            |
| Irish                 | ga            |
| Italian               | it            |
| Japanese              | ja            |
| Kannada               | kn            |
| Kazakh                | kk            |
| Korean                | ko            |
| Latvian               | lv            |
| Lithuanian            | lt            |
| Macedonian            | mk            |
| Malay                 | ms            |
| Malayalam             | ml            |
| Maltese               | mt            |
| Marathi               | mr            |
| Mongolian             | mn            |
| Norwegian (Bokmål)    | no            |
| Pashto                | ps            |
| Polish                | pl            |
| Portuguese (Brazil)   | pt            |
| Portuguese (Portugal) | pt-PT         |
| Punjabi               | pa            |
| Romanian              | ro            |
| Russian               | ru            |
| Serbian               | sr            |
| Sinhala               | si            |
| Slovak                | sk            |
| Slovenian             | sl            |
| Somali                | so            |
| Spanish               | es            |
| Spanish (Mexico)      | es-MX         |
| Swahili               | sw            |
| Swedish               | sv            |
| Tamil                 | ta            |
| Telugu                | te            |
| Thai                  | th            |
| Turkish               | tr            |
| Ukrainian             | uk            |
| Urdu                  | ur            |
| Uzbek                 | uz            |
| Vietnamese            | vi            |
| Welsh                 | cy            |

The language is identified using identifiers from [RFC 5646](https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes) — if there is a 2-letter ISO 639-1 identifier, with a regional subtag if necessary, it uses that. Otherwise, it uses the ISO 639-2 3-letter code.

## Implementation

The extension uses the `callExtension()` method provided by CometChat SDKs.

The messages will be translated according to the languages specified by the receiver. You can specify the languages for translation as an array. If you pass in an empty array, the language will default to English.

<Tabs>
  <Tab title="JavaScript">
    ```js theme={null}
    CometChat.callExtension('message-translation', 'POST', 'v2/translate', {
      "msgId": 12,
      "text": "Hey there! How are you?",
      "languages": [ "ru", "hi", "mr" ]
    }).then( result => {
    	// Result of translations
    })
    .catch(error => {
      // Some error occured
    });
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    import org.json.simple.JSONObject;

    JSONObject body=new JSONObject();
    JSONArray languages = new JSONArray();

    languages.add("ru");
    languages.add("hi");

    body.put("msgId", 12);
    body.put("languages", languages);
    body.put("text", "Hey there! How are you?");

    CometChat.callExtension("message-translation", "POST", "/v2/translate", body,
     new CometChat.CallbackListener < JSONObject > () {
        @Override
        public void onSuccess(JSONObject jsonObject) {
            // Result of translations
        }
        @Override
        public void onError(CometChatException e) {
            // Some error occured
        }
    });
    ```
  </Tab>

  <Tab title="Swift">
    ```swift theme={null}
    CometChat.callExtension(slug: "message-translation", type: .post, endPoint: "v2/translate", body: ["msgId": 12 ,"languages": ["hi", "ru"], "text": "Hey there! How are you?"] as [String : Any], onSuccess: { (response) in
             // Result of translations
          }) { (error) in
             // Some error occured
          }
    ```
  </Tab>
</Tabs>

The result will be received in the success callback of the `callExtension()` method. It will have the following JSON structure:

<Tabs>
  <Tab title="JSON">
    ```json theme={null}
    {
      "msgId": 12,
      "translations": [
        {
          "message_translated": "Эй там! Как ты?",
          "language_translated": "ru",
          "error": null,
          "error_description": null
        },
        {
          "message_translated": "अरे वहाँ! आप कैसे हैं?",
          "language_translated": "hi",
          "error": null,
          "error_description": null
        },
        {
          "message_translated": "",
          "language_translated": "mr",
          "error": "UnsupportedLanguagePairException",
          "error_description": "Unsupported language pair: en to mr. Target language 'mr' is not supported"
        }
      ],
        "language_original": "en"
    }
    ```
  </Tab>
</Tabs>

If the source language is not supported for translation, then you will get the following error:

<Tabs>
  <Tab title="JSON">
    ```json theme={null}
    {
      "code": "ERR_NOT_SUPPORTED",
      "message": "Autodetected source language '<language_code>' is not supported"
    }
    ```
  </Tab>
</Tabs>

### Translating at the sender's end

If the languages of the end-users/receivers are known before hand, this method of implementation can be used.

That is, before your trigger `CometChat.sendMessage` method, make a call to the message translation extension as mentioned above. Since the message has not been sent yet, the `msgId` won't be available and can be skipped in that call.

Once you get the response, make an entry in your message's metadata as shown below:

<Tabs>
  <Tab title="JavaScript">
    ```js theme={null}
    const messageText = "Hey there! How are you?";

    const metadata = {
      "message-translation": {
        "ru": "Эй там! Как ты?",
        "hi": "अरे वहाँ! आप कैसे हैं?"
      },
    };

    const textMessage = new CometChat.TextMessage(receiverID, messageText, receiverType);
    textMessage.setMetadata(metadata);

    CometChat.sendMessage(textMessage).then(
      message => {
        console.log("Message sent successfully:", message);
      }, error => {
        console.log("Message sending failed with error:", error);
      }
    );
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    private String messageText = "Hey there! How are you?";

    JSONObject metadata = new JSONObject();
    JSONObject translations = new JSONObject();

    try {
    	translations.put("ru", "Эй там! Как ты?");
    	translations.put("hi", "अरे वहाँ! आप कैसे हैं?");
    	metadata.put("message-translation", translations);
    } catch (JSONException je) {
      je.printStackTrace();
    }

    TextMessage textMessage = new TextMessage(receiverID, messageText, receiverType);
    textMessage.setMetadata(metadata);

    CometChat.sendMessage(textMessage, new CometChat.CallbackListener <TextMessage> () {
     @Override
     public void onSuccess(TextMessage textMessage) {
      Log.d(TAG, "Message sent successfully: " + textMessage.toString());
     }
     @Override
     public void onError(CometChatException e) {
      Log.d(TAG, "Message sending failed with exception: " + e.getMessage());
     }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```kotlin theme={null}
    val messageText:String="Hey there! How are you?"

    val metadataObject:JSONObject=JSONObject("{
      "message-translation": {
        "ru": "Эй там! Как ты?",
        "hi": "अरे वहाँ! आप कैसे हैं?"
      },
    }")

    val textMessage = TextMessage(receiverID, messageText, receiverType)
    textMessage.metadata=metadataObject

    CometChat.sendMessage(textMessage, object : CometChat.CallbackListener<TextMessage>() {
       override fun onSuccess(p0: TextMessage?) {
          Log.d(TAG, "Message sent successfully: " + p0?.toString())               
       }

       override fun onError(p0: CometChatException?) {
          Log.d(TAG, "Message sending failed with exception: " + p0?.message)          }

    })
    ```
  </Tab>

  <Tab title="Swift">
    ```swift theme={null}
    let text = "Hey there! How are you?";

    let translations = ["ru": "Эй там! Как ты?", "hi": "अरे वहाँ! आप कैसे हैं?"];
    let metadata = ["message-translation": translations]

    let textMessage = TextMessage(receiverUid: receiverID, text: text, receiverType: .user)
    textMessage.metaData = metadata;

    CometChat.sendTextMessage(message: textMessage, onSuccess: { (message) in

      print("TextMessage sent successfully. " + message.stringValue())

    }) { (error) in

      print("TextMessage sending failed with error: " + error!.errorDescription);
    }
    ```
  </Tab>
</Tabs>

Then, at the receiver's end, based on the device/browser language, you can show the translated text message in their chats from the metadata.

### Translating at the receiver's end

If the languages of the end-users/receivers are not known before hand, this method of implementation can be used.

Simply show a translate button above every message bubble in the UI. Make a call to the extension as mentioned above. The translation can then be shown in the same message bubble.

However, unlike the translations that are saved in the metadata when translating at the sender's end, these translations are ephemeral and will be lost once the page is reloaded, the user fetches older messages and scrolls back to the latest translated messages or the user switces conversations and comes back to the conversation with translated messages.
