by @rosdiie · javascript
export async function translate(text, fromLang = 'auto', toLang = 'en') {
const baseUrl = 'https://translate.google.com/translate_a/single';
const url = `${baseUrl}?client=at&dt=t&dt=rm&dj=1`;
const params = new URLSearchParams({
sl: fromLang,
tl: toLang,
q: text
});
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'User-Agent': 'Mozilla/5.0'
};
try {
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: params.toString()
});
if (response.status === 429) {
throw new Error('Rate limit exceeded');
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const raw = await response.json();
const sentences = raw.sentences || [];
const translatedText = sentences
.filter(s => s.trans)
.map(s => s.trans)
.join('');
return translatedText;
} catch (error) {
throw new Error(error.message);
}
}