Skip to content

Instantly share code, notes, and snippets.

@snowkidind
Created August 5, 2025 15:35
Show Gist options
  • Select an option

  • Save snowkidind/5270bf5f4ed230c56b3af4c121a390c5 to your computer and use it in GitHub Desktop.

Select an option

Save snowkidind/5270bf5f4ed230c56b3af4c121a390c5 to your computer and use it in GitHub Desktop.
const axios = require('axios')
module.exports = {
translate: async (text) => {
try {
const lang = checkLang(text)
if (lang === 'en') {
return text
}
else if (lang === 'zh') {
return await request(text, 'zh', 'en')
} else if (lang === 'ru') {
return await request(text, 'ru', 'en')
}
} catch (error) {
console.log(error)
return text
}
}
}
const checkLang = (words) => {
if (containsChinese(words)) {
return 'zh'
} else if (containsRussian(words)) {
return 'ru'
} else {
return 'en'
}
}
const containsChinese = (words) => {
const chineseRegex = /[\u4E00-\u9FFF]/
return chineseRegex.test(words)
}
function containsRussian(words) {
const russianRegex = /[\u0400-\u04FF]/
return russianRegex.test(words)
}
const request = async (message, from, to) => {
const options = {
method: 'POST',
url: 'https://ai-translate.p.rapidapi.com/translate',
headers: {
'content-type': 'application/json',
'X-RapidAPI-Key': process.env.XRapidAPIKey,
'X-RapidAPI-Host': process.env.XRapidAPIHost
},
data: {
texts: [
message
],
sl: from,
tl: to
}
}
try {
const response = await axios.request(options);
if (response.data.code === 200) {
return response.data.texts
}
} catch (error) {
console.error(error);
}
}
const TelegramBot = require('node-telegram-bot-api')
const bot = new TelegramBot(process.env.TELEGRAM_API_KEY, { polling: true })
const room = process.env.TELEGRAM_ROOM
const { translate } = require('./languageApi.js')
bot.on('message', async (msg, match) => {
try {
// if the response does not equal the text send a translation
const text = await translate(msg.text)
if (text !== msg.text && typeof text !== 'undefined') {
await bot.sendMessage(room, msg.from.first_name + ': ' + text)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment