Bitcoin Forum
September 23, 2026, 08:40:01 AM *
News: Latest Bitcoin Core release: 31.1 [Torrent]
 
   Home   Help Search Login Register More  
Pages: « 1 [2]  All
  Print  
Author Topic: [Userscript] Automatically translate Non-English text to English while posting  (Read 632 times)
BitBakerr1
Hero Member
*****
Offline

Activity: 644
Merit: 545



View Profile
September 17, 2026, 11:13:12 AM
Merited by vapourminer (1)
 #21

I don't think the guy understood what he said. None native English Speakers use more than 12 years to learn English and that is 6 years in Primary school and 6 years in Secondary School or College and in University or higher degree again. The major problem for the third world countries in English is the structure (syntax).
All these procedures are for persons that want to learn it as a profession.
Not actually true, we learn English in primary school, secondary and no matter the course you want to study in the university in Nigeria the first year you are going to learn English and it’s all compulsory.
In fact if you fail English in your secondary school final exam (WAEC) no university will offer you admission in Nigeria, this shows how important it is.
In my country which is Nigeria which I believe you are also from Nigeria, we go through all this process not because we want to use it as our profession but because we want to be perfect in speaking English.

The only people that take English as profession in my country are those that go to the university to study only English and linguistic.


 
█▄
R


▀▀██████▄▄
████████████████
▀█████▀▀▀█████
████████▌███▐████
▄█████▄▄▄█████
████████████████
▄▄██████▀▀
LLBIT▀█ 
  TH#1 SOLANA CASINO  
████████████▄
▀▀██████▀▀███
██▄▄▀▀▄▄████
████████████
██████████
███▀████████
▄▄█████████
████████████
████████████
████████████
████████████
█████████████
████████████▀
████████████▄
▀▀▀▀▀▀▀██████
████████████
███████████
██▄█████████
████▄███████
████████████
█░▀▀████████
▀▀██████████
█████▄█████
████▀▄▀████
▄▄▄▄▄▄▄██████
████████████▀
........5,000+........
GAMES
 
......INSTANT......
WITHDRAWALS
..........HUGE..........
REWARDS
 
............VIP............
PROGRAM
 .
   PLAY NOW    
MisFoxie
Full Member
***
Offline

Activity: 322
Merit: 133



View Profile
September 17, 2026, 05:15:27 PM
 #22

-snip-
I installed your tool using your provided method but nothing is happening when I paste a local language.

Don't know if the problem is on my side or in your code. Please test the uploaded code using your own device if it works or not.

Did you transfer this codes using Telegram? Whenever I transfer codes in telegram it doesn't work on received device anymore maybe this problem happened with your code as well.

Sterlino (OP)
Jr. Member
*
Offline

Activity: 45
Merit: 16


View Profile
September 18, 2026, 02:34:10 AM
 #23

-snip-
I installed your tool using your provided method but nothing is happening when I paste a local language.

Don't know if the problem is on my side or in your code. Please test the uploaded code using your own device if it works or not.

Did you transfer this codes using Telegram? Whenever I transfer codes in telegram it doesn't work on received device anymore maybe this problem happened with your code as well.
This script has nothing to do with Telegram and is not necessary.
And if you have trouble copying the code, you can download it from the GitHub . I have tried now with multiple languages ​​and it works.

And as you mentioned  device do you mean your phone or PC? If you try Chrome on the phone, it will not work. Because the language detector and translator used here are suitable for Chrome desktop . And for the first time, it takes some time to initialize the language, although it is very short which may not cause any problems.


MisFoxie
Full Member
***
Offline

Activity: 322
Merit: 133



View Profile
September 18, 2026, 01:37:31 PM
 #24

I installed your tool using your provided method but nothing is happening when I paste a local language.

Don't know if the problem is on my side or in your code. Please test the uploaded code using your own device if it works or not.

Did you transfer this codes using Telegram? Whenever I transfer codes in telegram it doesn't work on received device anymore maybe this problem happened with your code as well.
This script has nothing to do with Telegram and is not necessary.
And if you have trouble copying the code, you can download it from the GitHub . I have tried now with multiple languages ​​and it works.

And as you mentioned  device do you mean your phone or PC? If you try Chrome on the phone, it will not work. Because the language detector and translator used here are suitable for Chrome desktop . And for the first time, it takes some time to initialize the language, although it is very short which may not cause any problems.
I am using chrome on my desktop. I try to install the codes by copying directly from your github repository but still it doesn't work. I tried a local language and waited for 10 minutes but nothing happened.

Did you delete your previous script from tampermonkey and try resinstalling from github? I think there may be a problem with your code. I tried it on two devices and it didn't work on either one.

You didn't understand the telegram issue properly. I said that if you write the code and then transfer that code from first device to second device using telegram and upload it to github from the second device then that code will not work. I am saying this from my own experience because I also faced the same problem.

Sterlino (OP)
Jr. Member
*
Offline

Activity: 45
Merit: 16


View Profile
September 18, 2026, 02:52:22 PM
 #25

I am using chrome on my desktop. I try to install the codes by copying directly from your github repository but still it doesn't work. I tried a local language and waited for 10 minutes but nothing happened.

Did you delete your previous script from tampermonkey and try resinstalling from github? I think there may be a problem with your code. I tried it on two devices and it didn't work on either one.

You didn't understand the telegram issue properly. I said that if you write the code and then transfer that code from first device to second device using telegram and upload it to github from the second device then that code will not work. I am saying this from my own experience because I also faced the same problem.
I don't have any problem with coding. But if your local language is not among the languages ​​below, then it won't work. Outside these languages, Chrome language detector and translator don't really work. Now please tell me whether your local language is among this list or not. If it's not on this list, I'll update the thread and add some obstacle.

Code:
Arabic
Bulgarian
Bengali
Czech
Danish
German
Greek
English
Spanish
Finnish
French
Hebrew
Hindi
Croatian
Hungarian
Indonesian
Italian
Japanese
Kannada
Korean
Lithuanian
Marathi
Dutch
Norwegian
Polish
Portuguese
Romanian
Russian
Slovak
Slovenian
Swedish
Tamil
Telugu
Thai
Turkish
Ukrainian
Vietnamese
Chinese
Chinese (Traditional)
DYING_S0UL
Legendary
*
Offline

Activity: 1162
Merit: 1244


The Alliance Of Bitcointalk Translator - AOBT


View Profile WWW
September 18, 2026, 06:12:38 PM
Merited by Sterlino (1)
 #26

I am using chrome on my desktop. I try to install the codes by copying directly from your github repository but still it doesn't work. I tried a local language and waited for 10 minutes but nothing happened.
I don't have any problem with coding. But if your local language is not among the languages ​​below, then it won't work. Outside these languages, Chrome language detector and translator don't really work. Now please tell me whether your local language is among this list or not. If it's not on this list, I'll update the thread and add some obstacle.
Code:
Bengali

I was kinda curious and wanted to know whether it actually works, so I tried your userscript. And, the result was, unlike MisFoxie, my language doesn't work either (even though it's listed among your supported languages).

Now I don't understand the exact process of how it works (yes I read OP and saw the GIF). But afaik, I followed everything correctly and technically it should have been worked! but it didn't...(I also waited).

See? Everything is ON & properly installed, and I'm on Brave. Smiley

A question: Is it supposed to work when I modify/edit a post?





▄▄███████████████████▄▄
▄███████████████████████▄
████████████████████████
█████████████████████████
████████████████████████
████████████▀██████▀████
████████████████████████
█████████▄▄▄▄███████████
██████████▄▄▄████████████
████████████████████████
████████████████▀▀███████
▀███████████████████████▀
▀▀███████████████████▀▀
 
 EARNBET 
██
██
██
██
██
██
██
██
██
██
██
██
██
███████▄▄███████████
████▄██████████████████
██▀▀███████████████▀▀███
▄████████████████████████
▄▄████████▀▀▀▀▀████████▄▄██
███████████████████████████
█████████▌██▀████████████
███████████████████████████
▀▀███████▄▄▄▄▄█████████▀▀██
▀█████████████████████▀██
██▄▄███████████████▄▄███
████▀██████████████████
███████▀▀███████████
██
██
██
██
██
██
██
██
██
██
██
██
██


▄▄▄
▄▄▄███████▐███▌███████▄▄▄
█████████████████████████
▀████▄▄▄███████▄▄▄████▀
█████████████████████
▐███████████████████▌
███████████████████
███████████████████
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀

 King of The Castle 
 $200,000 in prizes
██
██
██
██
██
██
██
██
██
██
██
██
██

 62.5% 

 
RAKEBACK
BONUS
Sterlino (OP)
Jr. Member
*
Offline

Activity: 45
Merit: 16


View Profile
September 19, 2026, 02:53:08 PM
 #27

I am using chrome on my desktop. I try to install the codes by copying directly from your github repository but still it doesn't work. I tried a local language and waited for 10 minutes but nothing happened.
I don't have any problem with coding. But if your local language is not among the languages ​​below, then it won't work. Outside these languages, Chrome language detector and translator don't really work. Now please tell me whether your local language is among this list or not. If it's not on this list, I'll update the thread and add some obstacle.
Code:
Bengali

I was kinda curious and wanted to know whether it actually works, so I tried your userscript. And, the result was, unlike MisFoxie, my language doesn't work either (even though it's listed among your supported languages).

Now I don't understand the exact process of how it works (yes I read OP and saw the GIF). But afaik, I followed everything correctly and technically it should have been worked! but it didn't...(I also waited).

See? Everything is ON & properly installed, and I'm on Brave. Smiley

A question: Is it supposed to work when I modify/edit a post?






Most use  Firefox and Chrome, so I just mentioned that it won't work on Firefox but it can be used on Chrome. But I should have clearly mentioned that it is only suitable for Chrome. I apologize for this. I'm also updating this in thread  as what  kinds of limitations are here. And thank you for your trying to run it  though just for curiosity  Huh

Quote
How it will work.

Chrome's built-in language detector and translator API have been used. As a drawback, it cannot be used in firefox. Because the built-in free translator API as cannot be used directly in firefox. It will support all languages available in Chrome Translator API.
MisFoxie
Full Member
***
Offline

Activity: 322
Merit: 133



View Profile
September 19, 2026, 03:25:25 PM
 #28

I was kinda curious and wanted to know whether it actually works, so I tried your userscript. And, the result was, unlike MisFoxie, my language doesn't work either (even though it's listed among your supported languages).
I also used listed language - Spanish and Turkish but didn't work. I'm sure it's problem related to code I also give him suggestion to reinstall the script from github to see if it actually work for him but OP just ignoring me.

Most use  Firefox and Chrome, so I just mentioned that it won't work on Firefox but it can be used on Chrome. But I should have clearly mentioned that it is only suitable for Chrome. I apologize for this. I'm also updating this in thread  as what  kinds of limitations are here. And thank you for your trying to run it  though just for curiosity  Huh
Actually I run your script in tampermonkey + desktop Chrome + supported language (Spanish) still nothing happened. What could be the problem? Has anyone other than @DYING_S0UL tested this script?

AVE5
Sr. Member
****
Offline

Activity: 1036
Merit: 370


Winning & Loosing is the option. Take a decision


View Profile
September 19, 2026, 04:23:37 PM
 #29

I believe this tool will lead to a lot of posts will be flagged as AI. Google Translate uses LLMs too and when we use any AI detector, the results will be more of positrive for AI content, so it is better not to use translator tools to post.
Anyone who uses something like this should include in the post that it was translated with AI.
Imagine including in almost every of your post in the general board that it was done with Ai translator, a lot of persons wouldn't take you seriously because they think your post isn't natural. English is not that hard to learn in a short time of intense devotion to learning it. And It doesn't also has to be perfect just as Findingnemo rightly said, it just has to be able to communicate the message to the receiver/reader and it's okay.
I have always maintained it that as long as English isn't your native language you don't have to be a perfectionist at it to feel comfortable communicating with it.

I'm sure we're coming to the point of time where this approved uses of the AI is ruining the system. Just because it's said that we can still use the AI to post but must make sure it's indicated that it was AI generated some of the user fans had seem so relaxed  on using it.
This privilege has really made some user's been lazy that instead of brainstorming on the specific aspect, they finds it stressing on using their brain because the AI had been made available to do it easier. No wonder Op actually said it that the use of the AI would made the program easier for him which is exactly one of the point.
Probably most of the users of this AI in the forum aren't aware that no matter how professional the AI generated posts might be, as long as it's indicated that it was generated by AI it looses quality of the post.
Let's not also forget that almost all the discussion here on the forum such as the questions and answers can be obtained in the internet or google precisely but for the sake of checking member's knowledge ability and capacities is why it's preferred we brainstorms.

Curious T
Full Member
***
Offline

Activity: 504
Merit: 113



View Profile
September 19, 2026, 04:49:15 PM
 #30

English is not that hard to learn in a short time of intense devotion to learning it. And It doesn't also has to be perfect just as Findingnemo rightly said, it just has to be able to communicate the message to the receiver/reader and it's okay.
Are you for real? Did you just say English is not that hard to learn?  Grin. You have no idea. It's because you know how to speak it, that is why you think it's easy. English is not easy, it's hard. Even people who have English as their native language still struggle with it.

I think I have read a rule on the forum before that said we should not use translators to make post. If you can't speak the language then don't post there. Or am I wrong?

Findingnemo
Legendary
*
Offline

Activity: 3192
Merit: 1142


Leading Crypto Sports Betting & Casino Platform


View Profile
September 19, 2026, 05:08:37 PM
 #31

English is not that hard to learn in a short time of intense devotion to learning it. And It doesn't also has to be perfect just as Findingnemo rightly said, it just has to be able to communicate the message to the receiver/reader and it's okay.
Are you for real? Did you just say English is not that hard to learn?  Grin. You have no idea. It's because you know how to speak it, that is why you think it's easy. English is not easy, it's hard. Even people who have English as their native language still struggle with it.

I think I have read a rule on the forum before that said we should not use translators to make post. If you can't speak the language then don't post there. Or am I wrong?

I don't know why we keep having this conversation, but to state the fact, English is one of the easier languages to learn compared to other languages, if you ask which one is difficult then it might be Chinese (Mandarin). Grin

But anyone who uses devices might have a basic english understanding level and that might be good enough to read and even write that can be broken, but over time they can get better, I mean in a matter of months.

Forum moderation tolerates any kind of English until it is not even readable and if you are in that kind then better stick with local boards.

..Stake.com..   ▄████████████████████████████████████▄
   ██ ▄▄▄▄▄▄▄▄▄▄            ▄▄▄▄▄▄▄▄▄▄ ██  ▄████▄
   ██ ▀▀▀▀▀▀▀▀▀▀ ██████████ ▀▀▀▀▀▀▀▀▀▀ ██  ██████
   ██ ██████████ ██      ██ ██████████ ██   ▀██▀
   ██ ██      ██ ██████  ██ ██      ██ ██    ██
   ██ ██████  ██ █████  ███ ██████  ██ ████▄ ██
   ██ █████  ███ ████  ████ █████  ███ ████████
   ██ ████  ████ ██████████ ████  ████ ████▀
   ██ ██████████ ▄▄▄▄▄▄▄▄▄▄ ██████████ ██
   ██            ▀▀▀▀▀▀▀▀▀▀            ██ 
   ▀█████████▀ ▄████████████▄ ▀█████████▀
  ▄▄▄▄▄▄▄▄▄▄▄▄███  ██  ██  ███▄▄▄▄▄▄▄▄▄▄▄▄
 ██████████████████████████████████████████
▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▄
█  ▄▀▄             █▀▀█▀▄▄
█  █▀█             █  ▐  ▐▌
█       ▄██▄       █  ▌  █
█     ▄██████▄     █  ▌ ▐▌
█    ██████████    █ ▐  █
█   ▐██████████▌   █ ▐ ▐▌
█    ▀▀██████▀▀    █ ▌ █
█     ▄▄▄██▄▄▄     █ ▌▐▌
█                  █▐ █
█                  █▐▐▌
█                  █▐█
▀▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▀█
▄▄█████████▄▄
▄██▀▀▀▀█████▀▀▀▀██▄
▄█▀       ▐█▌       ▀█▄
██         ▐█▌         ██
████▄     ▄█████▄     ▄████
████████▄███████████▄████████
███▀    █████████████    ▀███
██       ███████████       ██
▀█▄       █████████       ▄█▀
▀█▄    ▄██▀▀▀▀▀▀▀██▄  ▄▄▄█▀
▀███████         ███████▀
▀█████▄       ▄█████▀
▀▀▀███▄▄▄███▀▀▀
..PLAY NOW..
DYING_S0UL
Legendary
*
Offline

Activity: 1162
Merit: 1244


The Alliance Of Bitcointalk Translator - AOBT


View Profile WWW
September 19, 2026, 07:31:00 PM
 #32

Most use  Firefox and Chrome, so I just mentioned that it won't work on Firefox but it can be used on Chrome. But I should have clearly mentioned that it is only suitable for Chrome. I apologize for this. I'm also updating this in thread  as what  kinds of limitations are here. And thank you for your trying to run it  though just for curiosity  Huh

I'm not on firefox mate! I'm using Brave browser, which is based on Chromium web browser engine! So technically it should have worked the first time!

I'm not a big fan of Chrome, but i'll test it on chrome (download in progress) and let you know the results! 


Are you for real? Did you just say English is not that hard to learn?  Grin. You have no idea. It's because you know how to speak it, that is why you think it's easy. English is not easy, it's hard. Even people who have English as their native language still struggle with it.

I think I have read a rule on the forum before that said we should not use translators to make post. If you can't speak the language then don't post there. Or am I wrong?

Nobody is asking you for Cambridge or band 9 level English anyway! You only need to know the basics, and that'll be enough to help you get by with the daily conversation with the users' here. That's all. Also, learning English is not that hard mate! If you thought it's hard, then you weren't trying hard enough.

As for using translators it's better to not use any but....

You should not copy/paste text written by an AI into a post, with these exceptions:
<...>
 - If you have the AI do almost a direct translation of something you wrote, then that's OK. For example, you can tell the AI to "Directly translate this text into Spanish: <something you wrote>" or "Output the following text exactly as-is, except with any clear spelling or grammar mistakes fixed: <something you wrote>". It's not OK to tell an AI, "Improve this text: <something you wrote>", since then it will mostly rewrite it, and it risks becoming AI slop in the process.

▄▄███████████████████▄▄
▄███████████████████████▄
████████████████████████
█████████████████████████
████████████████████████
████████████▀██████▀████
████████████████████████
█████████▄▄▄▄███████████
██████████▄▄▄████████████
████████████████████████
████████████████▀▀███████
▀███████████████████████▀
▀▀███████████████████▀▀
 
 EARNBET 
██
██
██
██
██
██
██
██
██
██
██
██
██
███████▄▄███████████
████▄██████████████████
██▀▀███████████████▀▀███
▄████████████████████████
▄▄████████▀▀▀▀▀████████▄▄██
███████████████████████████
█████████▌██▀████████████
███████████████████████████
▀▀███████▄▄▄▄▄█████████▀▀██
▀█████████████████████▀██
██▄▄███████████████▄▄███
████▀██████████████████
███████▀▀███████████
██
██
██
██
██
██
██
██
██
██
██
██
██


▄▄▄
▄▄▄███████▐███▌███████▄▄▄
█████████████████████████
▀████▄▄▄███████▄▄▄████▀
█████████████████████
▐███████████████████▌
███████████████████
███████████████████
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀

 King of The Castle 
 $200,000 in prizes
██
██
██
██
██
██
██
██
██
██
██
██
██

 62.5% 

 
RAKEBACK
BONUS
Sterlino (OP)
Jr. Member
*
Offline

Activity: 45
Merit: 16


View Profile
September 20, 2026, 03:36:00 AM
 #33

I also used listed language - Spanish and Turkish but didn't work. I'm sure it's problem related to code I also give him suggestion to reinstall the script from github to see if it actually work for him but OP just ignoring me.

Bro I reinstalled. And tried it in your two languages ​​specifically. And it works. I re-downloaded it from GitHub as a user would run it.



Previously as you said its not working then I tried every language  at that list to check and that was working  .
So I said to you to check your local language is in this list or not. I didnt ignore you.
Supreme Donvic
Sr. Member
****
Offline

Activity: 378
Merit: 254



View Profile
September 20, 2026, 01:36:43 PM
 #34

English is not that hard to learn in a short time of intense devotion to learning it. And It doesn't also has to be perfect just as Findingnemo rightly said, it just has to be able to communicate the message to the receiver/reader and it's okay.
Are you for real? Did you just say English is not that hard to learn?  Grin. You have no idea. It's because you know how to speak it, that is why you think it's easy. English is not easy, it's hard. Even people who have English as their native language still struggle with it.
I think the reason why he's saying it is not hard is because he speaks English, when you are speaking a particular language that is being spoken in your country and you grew up speaking the language you won't know how difficult it is, even my local language that I speak is very easy for me because I grew up speaking it but it is actually very difficult for other people from other tribe to learn and speak it so it is natural to always feel that the language you speak is easy and not that hard.

███████████████████████
███████████████████████
███████████████████████
██████████████████████
█████████████████████
██████████████████████
██████████████████████
███████████████████
██████████████████████
███████████████████████
███████████████████████
███████████████████████
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
🗲
███    ███████████████████████████████████████

CRYPTO'S MOST REWARDING CASINO

███████████████████████████████████████    ███
██████▄██████▄▄
███▄██████████████▄▄
▄███████████████████
█████████████████████
▀███████
████████████████▄
█████████████████████████
███▀███████████████████▀
█████████████████████▀▀
██████▀███████████▀▀
███████████████▀▀
█████████▀█▀▀


█▀▀






█▄▄


▀▀███
██
██
██
██
██
██
▄▄███
█████




███▄▄▄▄███
████████████
███████████▀
████████▄
█████████▄
█████▀█████▄
▀██████▀█████
██████████▀██▀
Curious T
Full Member
***
Offline

Activity: 504
Merit: 113



View Profile
September 20, 2026, 05:18:11 PM
 #35

Nobody is asking you for Cambridge or band 9 level English anyway! You only need to know the basics, and that'll be enough to help you get by with the daily conversation with the users' here. That's all. Also, learning English is not that hard mate! If you thought it's hard, then you weren't trying hard enough.
I never said Cambridge English is required. I only said English is not easy to learn. It seems easy for you because you understand and speak it. Learning a new language that is not spoken in your country and you're not around people who speak it is hard. It's not a matter of not trying enough. It's easy for a Spanish speaker to say "Spanish is easy". The only thing that makes English relatively easy, in my opinion, is that it's very popular. It's not difficult to see English speakers. It's everywhere. Otherwise, for a person who is not from a country where they speak any English, it's difficult to learn.

DYING_S0UL
Legendary
*
Offline

Activity: 1162
Merit: 1244


The Alliance Of Bitcointalk Translator - AOBT


View Profile WWW
September 20, 2026, 05:35:42 PM
Last edit: September 20, 2026, 05:46:22 PM by DYING_S0UL
 #36

-snip-

Hey I went on and tested it on Chrome, but still not working. Now I'm not sure what I did wrong.

Went to the github, copied raw code, installed the userscript inside tampermonkey - this is what I did.

Btw, I can see a few error inside tampermonkey when I paste in the codes.

1. inject-into is not a valid header
2. "languageDetector" is not not defined
3. "Translator" is not defined



Nobody is asking you for Cambridge or band 9 level English anyway! You only need to know the basics, and that'll be enough to help you get by with the daily conversation with the users' here. That's all. Also, learning English is not that hard mate! If you thought it's hard, then you weren't trying hard enough.
I never said Cambridge English is required. I only said English is not easy to learn. It seems easy for you because you understand and speak it. Learning a new language that is not spoken in your country and you're not around people who speak it is hard. It's not a matter of not trying enough. It's easy for a Spanish speaker to say "Spanish is easy". The only thing that makes English relatively easy, in my opinion, is that it's very popular. It's not difficult to see English speakers. It's everywhere. Otherwise, for a person who is not from a country where they speak any English, it's difficult to learn.

Well my friend, I'm not!  Smiley

I don't belong to a country where English is spoken all over the places or widely spoken. Furthermore, there aren't any people around me who speaks English! You see, I watch a lot of English content, and everything I know today, is through that. And honestly speaking I don't see why you think it's that hard...! I would suggest you to watch English content, I believe visual memory is the best memory. When you watch things, you can easily learn from them, remember them. At least that's how I learned it.

Now you might be wondering, since I'm writing in English without any help, I might know a lot of English grammar! But I must confess, I know none! LOL, I'm just writing what I learned everyday through movies/series.  Tongue

▄▄███████████████████▄▄
▄███████████████████████▄
████████████████████████
█████████████████████████
████████████████████████
████████████▀██████▀████
████████████████████████
█████████▄▄▄▄███████████
██████████▄▄▄████████████
████████████████████████
████████████████▀▀███████
▀███████████████████████▀
▀▀███████████████████▀▀
 
 EARNBET 
██
██
██
██
██
██
██
██
██
██
██
██
██
███████▄▄███████████
████▄██████████████████
██▀▀███████████████▀▀███
▄████████████████████████
▄▄████████▀▀▀▀▀████████▄▄██
███████████████████████████
█████████▌██▀████████████
███████████████████████████
▀▀███████▄▄▄▄▄█████████▀▀██
▀█████████████████████▀██
██▄▄███████████████▄▄███
████▀██████████████████
███████▀▀███████████
██
██
██
██
██
██
██
██
██
██
██
██
██


▄▄▄
▄▄▄███████▐███▌███████▄▄▄
█████████████████████████
▀████▄▄▄███████▄▄▄████▀
█████████████████████
▐███████████████████▌
███████████████████
███████████████████
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀

 King of The Castle 
 $200,000 in prizes
██
██
██
██
██
██
██
██
██
██
██
██
██

 62.5% 

 
RAKEBACK
BONUS
Sterlino (OP)
Jr. Member
*
Offline

Activity: 45
Merit: 16


View Profile
September 21, 2026, 06:28:47 PM
 #37

Hey I went on and tested it on Chrome, but still not working. Now I'm not sure what I did wrong.

Went to the github, copied raw code, installed the userscript inside tampermonkey - this is what I did.

Btw, I can see a few error inside tampermonkey when I paste in the codes.

1. inject-into is not a valid header
2. "languageDetector" is not not defined
3. "Translator" is not defined


Although there is very few user interaction, but you are testing it motivates me. I have tried with long time today to actually fix the problem.  Cry I also tried setting up Tampermonkey from another PC. It worked there too, I did not face any issue.
But particularly because of the main problems you have highlighted in your testing, I removed the valid header part.
 
I can see that LanguageDetector and Translator are functional.  Huh



 If you have time, please try the modified script below.
And let me know the feed back  Smiley

Code:
// ==UserScript==
// @name         Bitcointalk Auto English
// @namespace    Sterlino
// @version      1.0.1-testing
// @description  Automatically translates supported non-English text to English while writing on Bitcointalk.
// @author       Sterlino
// @match        *://bitcointalk.org/*
// @match        *://www.bitcointalk.org/*
// @run-at       document-idle
// @grant        none
// ==/UserScript==

(function () {
    "use strict";

    const MESSAGE_BOX_SELECTOR = 'textarea[name="message"]';
    const TARGET_LANGUAGE = "en";
    const TYPING_DELAY = 450;
    const SENTENCE_TERMINAL = /\p{Sentence_Terminal}/u;

    let messageBox = null;
    let detectorPromise = null;
    let typingTimer = null;
    let composing = false;
    let internalChange = false;
    let processing = false;

    const translatorPromises = new Map();
    const jobs = [];

    function getLanguageDetectorApi() {
        return globalThis["LanguageDetector"];
    }

    function getTranslatorApi() {
        return globalThis["Translator"];
    }

    function hasBuiltInApis() {
        return Boolean(getLanguageDetectorApi() && getTranslatorApi());
    }

    function hasUserActivation() {
        return Boolean(navigator.userActivation && navigator.userActivation.isActive);
    }

    function createDetectorNow() {
        const api = getLanguageDetectorApi();

        if (!API) {
            return Promise.resolve(null);
        }

        if (!detectorPromise) {
            DetectorPromise = API.create({
                monitor(monitor) {
                    monitor.addEventListener("downloadprogress", function (event) {
                        console.debug("Bitcointalk Auto English: language detector download", Math.round(event.loaded * 100) + "%");
                    });
                }
            }).catch(function (error) {
                console.debug("Bitcointalk Auto English: language detector could not start", error);
                detectorPromise = null;
                return null;
            });
        }

        return detectorPromise;
    }

    async function getDetector() {
        if (detectorPromise) {
            return detectorPromise;
        }

        const api = getLanguageDetectorApi();

        if (!API) {
            return null;
        }

        if (hasUserActivation()) {
            return createDetectorNow();
        }

        try {
            const status = await api.availability();

            if (status === "available") {
                return createDetectorNow();
            }
        } catch (error) {
            console.debug("Bitcointalk Auto English: detector availability check failed", error);
        }

        return null;
    }

    function createTranslatorNow(sourceLanguage) {
        const api = getTranslatorApi();

        if (!API || !sourceLanguage || sourceLanguage === TARGET_LANGUAGE) {
            return Promise.resolve(null);
        }

        if (!translatorPromises.has(sourceLanguage)) {
            const promise = api.create({
                sourceLanguage: sourceLanguage,
                targetLanguage: TARGET_LANGUAGE,
                monitor(monitor) {
                    monitor.addEventListener("downloadprogress", function (event) {
                        console.debug(
                            "Bitcointalk Auto English: translation model download",
                            sourceLanguage,
                            Math.round(event.loaded * 100) + "%"
                        );
                    });
                }
            }).catch(function (error) {
                console.debug("Bitcointalk Auto English: translator could not start", sourceLanguage, error);
                translatorPromises.delete(sourceLanguage);
                return null;
            });

            translatorPromises.set(sourceLanguage, promise);
        }

        return translatorPromises.get(sourceLanguage);
    }

    async function getTranslator(sourceLanguage) {
        if (!sourceLanguage || sourceLanguage === TARGET_LANGUAGE) {
            return null;
        }

        if (translatorPromises.has(sourceLanguage)) {
            return translatorPromises.get(sourceLanguage);
        }

        const api = getTranslatorApi();

        if (!API) {
            return null;
        }

        if (hasUserActivation()) {
            return createTranslatorNow(sourceLanguage);
        }

        try {
            const status = await api.availability({
                sourceLanguage: sourceLanguage,
                targetLanguage: TARGET_LANGUAGE
            });

            if (status === "available") {
                return createTranslatorNow(sourceLanguage);
            }
        } catch (error) {
            console.debug("Bitcointalk Auto English: translator availability check failed", error);
        }

        return null;
    }

    function primeFromUserAction() {
        if (!Hasbuiltinapis() || !hasUserActivation()) {
            return;
        }

        createDetectorNow();

        const languages = new Set();

        for (const job of jobs) {
            If (job.sourceLanguage && job.sourceLanguage !== TARGET_LANGUAGE) {
                languages.Add(job.sourceLanguage);
            }
        }

        for (const language of languages) {
            createTranslatorNow(language).then(function () {
                processJobs();
            });
        }
    }

    async function detectSourceLanguage(text) {
        const detector = await getDetector();

        if (!detector) {
            return null;
        }

        let results;

        try {
            results = await detector.detect(text);
        } catch (error) {
            console.debug("Bitcointalk Auto English: language detection failed", error);
            return null;
        }

        if (!Array.isArray(results) || results.length === 0) {
            return null;
        }

        const top = results[0];

        if (top && top.detectedLanguage === TARGET_LANGUAGE && top.confidence >= 0.5) {
            return TARGET_LANGUAGE;
        }

        const translator api = goat translator api();
        const candidates = results
            .filter(function (item) {
                return item && item.detectedLanguage && item.detectedLanguage !== "and";
            })
            .slice(0, 8);

        for (const candidate of candidates) {
            const code = candidate.detectedLanguage;

            if (code === TARGET_LANGUAGE) {
                continue;
            }

            try {
                const status = await translatorApi.availability({
                    sourceLanguage: code,
                    targetLanguage: TARGET_LANGUAGE
                });

                if (status !== "unavailable") {
                    return code;
                }
            } catch (error) {
                continue;
            }
        }

        if (top && top.detectedLanguage === TARGET_LANGUAGE) {
            return TARGET_LANGUAGE;
        }

        return null;
    }

    function findClosestText(value, text, preferredStart) {
        if (value.slice(preferredStart, preferredStart + text.length) === text) {
            return preferredStart;
        }

        let bestPosition = -1;
        let bestDistance = Infinity;
        let position = value.indexOf(text);

        while (position !== -1) {
            const distance = Math.abs(position - preferredStart);

            if (distance < bestDistance) {
                bestPosition = position;
                bestDistance = distance;
            }

            position = value.indexOf(text, position + 1);
        }

        return bestPosition;
    }

    function adjustPosition(position, start, oldLength, newLength) {
        const end = start + oldLength;
        const delta = newLength - oldLength;

        if (position <= start) {
            return position;
        }

        if (position >= end) {
            return position + delta;
        }

        return start + newLength;
    }

    function replaceJobText(job, translatedText) {
        if (!messageBox || !document.contains(messageBox)) {
            return false;
        }

        const currentValue = messageBox.value;
        const start = findClosestText(currentValue, job.text, job.start);

        if (start < 0) {
            return false;
        }

        const end = start + job.text.length;
        const selectionStart = messageBox.selectionStart;
        const selectionEnd = messageBox.selectionEnd;
        const replacement = translatedText;
        const delta = replacement.length - job.text.length;

        internalChange = true;

        messageBox.value =
            currentValue.slice(0, start) +
            replacement +
            currentValue.Slice(END);

        const newSelectionStart = adjustPosition(
            selectionStart,
            Start,
            job.text.length,
            replacement.length
        );

        const newSelectionEnd = adjustPosition(
            selectionEnd,
            Start,
            Job.text.length,
            replacement.length
        );

        messageBox.setSelectionRange(newSelectionStart, newSelectionEnd);
        messageBox.dispatchEvent(new Event("input", { bubbles: true }));

        internalChange = false;

        for (const queuedJob of jobs) {
            If (Queuedjob !== Job && queuedjob.start > start) {
                Queuedjob.start + = delta;
            }
        }

        return true;
    }

    function prepareJobLanguage(job) {
        if (Job.sourceLanguage) {
            return Promise.resolve(job.sourceLanguage);
        }

        if (!job.languagePromise) {
            job.languagePromise = detectSourceLanguage(job.text).then(function (language) {
                job.sourceLanguage = language;
                Job.languagePromise = null;
                return language;
            });
        }

        return Job.languagePromise;
    }

    async function processJobs() {
        if (processing || jobs.length === 0 || !hasbuiltinapis()) {
            return;
        }

        processing = true;

        try {
            while (jobs.length > 0) {
                const job = jobs[0];

                if (!Job.sourceLanguage) {
                    Job.sourceLanguage = await prepareJobLanguage(job);
                }

                if (!job.sourceLanguage) {
                    break;
                }

                If (Job.sourceLanguage === TARGET_LANGUAGE) {
                    jobs.Shift();
                    continue;
                }

                const translator = await getTranslator(Job.sourceLanguage);

                if (!translator) {
                    break;
                }

                let translatedText;

                try {
                    translatedText = await translator.translate(Job.text);
                } catch (error) {
                    console.debug("Bitcointalk Auto English: translation failed", error);
                    Jobs.Shift();
                    continue;
                }

                if (typeof translatedText === "string" && translatedText.trim()) {
                    replaceJobText(job, translatedText);
                }

                Jobs.Shift();
            }
        } finally {
            processing = false;
        }
    }

    function isDuplicateJob(text, start) {
        return Jobs.some(function (job) {
            return job.start === start && job.text === text;
        });
    }

    function addJob(text, start) {
        if (!text || !text.trim() || isDuplicateJob(text, start)) {
            return;
        }

        Jobs.push({{
            text: text,
            start: start,
            sourceLanguage: null,
            languagePromise: null
        });
    }

    function addTrimmedJob(text, baseStart) {
        const leading = text.match(/^\s*/)[0].length;
        const trailing = text.match(/\s*$/)[0].length;
        const end = text.length - trailing;

        if (end <= leading) {
            return;
        }

        addJob(text.slice(leading, end), baseStart + leading);
    }

    function addPastedJobs(text, baseStart) {
        let segmentStart = 0;

        for (let index = 0; index < text.length; index += 1) {
            const character = text.charAt(index);

            if (SENTENCE_TERMINAL.test(character)) {
                addTrimmedJob(text.Slice(segment start, index + 1), base start + segment start);
                segmentStart = index + 1;
                continue;
            }

            if (character === "\n") {
                addTrimmedJob(text.slice(segmentStart, index), baseStart + segmentStart);
                segmentStart = index + 1;
            }
        }

        if (segmentStart < text.length) {
            addTrimmedJob(text.Slice(segment start), base start + segment start);
        }

        processJobs();
    }

    function insertPastedText(event) {
        if (!messageBox || composing) {
            return;
        }

        const clipboard = event.clipboardData;

        if (!clipboard) {
            return;
        }

        const pastedText = clipboard.getData("text/plain");

        if (!pastedText) {
            return;
        }

        primeFromUserAction();
        event.preventDefault();

        const start = messageBox.selectionStart;
        const end = messageBox.selectionEnd;
        const before = messageBox.value.slice(0, start);
        const after = messageBox.value.Slice(END);
        const caret = start + pastedText.length;

        internalChange = true;
        messageBox.value = before + pastedText + after;
        messageBox.setSelectionRange(caret, caret);
        messageBox.dispatchEvent(new Event("input", { bubbles: true }));
        internalChange = false;

        addPastedJobs(pastedText, start);
    }

    function findCompletedSentence() {
        if (!messageBox) {
            return null;
        }

        const caret = messageBox.selectionStart;

        if (caret <= 0 || messageBox.selectionStart !== messageBox.selectionEnd) {
            return null;
        }

        const value = messageBox.value;
        let end = caret;
        let terminalIndex = end - 1;

        while (terminalIndex >= 0 && /\s/.Test(value.charAt(terminalIndex))) {
            terminalIndex -= 1;
        }

        if (terminalIndex < 0) {
            return null;
        }

        const terminalCharacter = value.charAt(terminalIndex);

        if (!SENTENCE_TERMINAL.test(terminalCharacter)) {
            return null;
        }

        let start = terminalIndex;

        while (start > 0) {
            const previousCharacter = value.charAt(start - 1);

            if (previousCharacter === "\n" || SENTENCE_TERMINAL.test(previousCharacter)) {
                break;
            }

            start -= 1;
        }

        while (start < terminalIndex && /[ \t\r\n]/.Test(value.charAt(start))) {
            start += 1;
        }

        end = terminalIndex + 1;

        const text = value.slice(start, end);

        if (!text.trim()) {
            return null;
        }

        return { text: text, start: start };
    }

    function queueCompletedSentence() {
        if (composing || internalChange) {
            return;
        }

        const sentence = findCompletedSentence();

        if (sentence) {
            addJob(sentence.text, sentence.start);
            processJobs();
        }
    }

    function scheduleTypedSentence() {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(queueCompletedSentence, TYPING_DELAY);
    }

    function handleInput() {
        if (internalChange || composing) {
            return;
        }

        const sentence = findCompletedSentence();

        if (sentence) {
            clearTimeout(typingTimer);
            addJob(sentence.text, sentence.start);
            processJobs();
            return;
        }

        scheduleTypeDentence();
    }

    function handleUserAction() {
        primeFromUserAction();
        processJobs();
    }

    function attachToMessageBox(box) {
        if (!box || box.dataset.autoEnglishAttached === "1") {
            return;
        }

        messageBox = box;
        messageBox.dataset.autoEnglishAttached = "1";

        messageBox.addEventListener("keydown", handleUserAction, true);
        messageBox.addEventListener("mousedown", handleUserAction, true);
        messageBox.addEventListener("paste", insertPastedText, true);

        messageBox.addEventListener("compositionstart", function () {
            composing = true;
            clearTimeout(typingTimer);
        });

        messageBox.addEventListener("compositionend", function () {
            composing = false;
            handleInput();
        });

        messageBox.addEventListener("input", handleInput);
    }

    function initialize() {
        if (!hasbuiltinapis()) {
            console.debug("Bitcointalk Auto English: Chrome LanguageDetector or Translator API is not available.");
        }

        const box = document.querySelector(MESSAGE_BOX_SELECTOR);

        if (box) {
            AttachoMessageBox(Box);
            return true;
        }

        return false;
    }

    if (!initialize()) {
        const observer = new MutationObserver(function () {
            if (initialize()) {
                observer.disconnect();
            }
        });

        observer.observe(document.documentElement, {
            childList: true,
            subtree: true
        });
    }
})();
MisFoxie
Full Member
***
Offline

Activity: 322
Merit: 133



View Profile
September 21, 2026, 07:13:30 PM
Merited by Sterlino (1)
 #38

-snip-
I'm really sad to say this again but the uploaded script isn't working for me this time as well...

I try to solve it on my own to see if it could be possible to make it work.
Code:
// ==UserScript==
// @name         Bitcointalk Auto English Translator
// @namespace    https://github.com/SterlinoBTT
// @version      1.3.0
// @description  Automatically translates non-English text to English when pasting into Bitcointalk reply boxes.
// @author       Sterlino
// @match        *://bitcointalk.org/*
// @match        *://www.bitcointalk.org/*
// @match        *://*.bitcointalk.org/*
// @include      *://bitcointalk.org/*
// @include      *://www.bitcointalk.org/*
// @include      *://*.bitcointalk.org/*
// @include      https://bitcointalk.org/*
// @include      https://www.bitcointalk.org/*
// @connect      clients5.google.com
// @connect      translate.googleapis.com
// @connect      translate.google.com
// @grant        GM_xmlhttpRequest
// @grant        GM.xmlHttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// @run-at       document-idle
// ==/UserScript==

(function () {
    "use strict";

    console.log("[Auto-English] Bitcointalk Auto English Translator v1.3.0 active");

    const STORAGE_AUTO_PASTE_KEY = "btt_auto_translate_paste";

    let displayNames = null;
    try {
        displayNames = new Intl.DisplayNames(["en"], { type: "language" });
    } catch (e) {
        displayNames = null;
    }

    function getLanguageName(code) {
        if (!code || code === "auto") return "Detected Language";
        if (displayNames) {
            try {
                return displayNames.of(code) || code;
            } catch (e) {
                return code;
            }
        }
        return code;
    }

    function isAutoPasteEnabled() {
        if (typeof GM_getValue === "function") {
            return GM_getValue(STORAGE_AUTO_PASTE_KEY, true);
        }
        const val = localStorage.getItem(STORAGE_AUTO_PASTE_KEY);
        return val === null ? true : val === "true";
    }

    function setAutoPasteEnabled(enabled) {
        if (typeof GM_setValue === "function") {
            GM_setValue(STORAGE_AUTO_PASTE_KEY, enabled);
        }
        try {
            localStorage.setItem(STORAGE_AUTO_PASTE_KEY, enabled ? "true" : "false");
        } catch (e) {}
    }

    function normalizeLineBreaks(str) {
        return str ? str.replace(/\r\n/g, "\n").replace(/\r/g, "\n") : "";
    }

    function nativeFetch(url, postBody = null) {
        const options = {};
        if (postBody) {
            options.method = "POST";
            options.headers = {
                "Content-Type": "application/x-www-form-urlencoded",
            };
            options.body = postBody;
        }
        return fetch(url, options).then(async (res) => {
            if (!res.ok) {
                throw new Error("HTTP " + res.status);
            }
            return await res.text();
        });
    }

    function requestText(url, postBody = null) {
        return new Promise((resolve, reject) => {
            const method = postBody ? "POST" : "GET";
            const gm =
                typeof GM_xmlhttpRequest === "function"
                    ? GM_xmlhttpRequest
                    : typeof GM !== "undefined" && typeof GM.xmlHttpRequest === "function"
                    ? GM.xmlHttpRequest
                    : null;

            if (gm) {
                try {
                    const reqObj = {
                        method: method,
                        url: url,
                        timeout: 10000,
                        onload: (res) => {
                            if (res.status >= 200 && res.status < 400) {
                                resolve(res.responseText);
                            } else {
                                nativeFetch(url, postBody).then(resolve).catch(reject);
                            }
                        },
                        onerror: () => nativeFetch(url, postBody).then(resolve).catch(reject),
                        ontimeout: () => nativeFetch(url, postBody).then(resolve).catch(reject),
                    };
                    if (postBody) {
                        reqObj.data = postBody;
                        reqObj.headers = {
                            "Content-Type": "application/x-www-form-urlencoded",
                        };
                    }
                    gm(reqObj);
                    return;
                } catch (e) {
                    // Fall back to native fetch
                }
            }

            nativeFetch(url, postBody).then(resolve).catch(reject);
        });
    }

    function protectTokens(text) {
        const tokens = [];
        const pattern = /(\[\/?[a-z0-9_]+(?::[a-z0-9_]+)?(?:=[^\]]+)?\]|https?:\/\/[^\s<>"'{}|\\^`]+)/gi;
        const protectedText = text.replace(pattern, (match) => {
            const id = tokens.length;
            tokens.push(match);
            return `___BTT_TOK_${id}___`;
        });
        return { protectedText, tokens };
    }

    function restoreTokens(translatedText, tokens) {
        let result = translatedText;
        for (let i = 0; i < tokens.length; i++) {
            const regex = new RegExp(`___\\s*BTT_TOK_${i}\\s*___`, "gi");
            result = result.replace(regex, tokens[i]);
        }
        return result;
    }

    async function translateViaGoogleDict(text) {
        const baseUrl = "https://clients5.google.com/translate_a/t?client=dict-chrome-ex";
        const query = `sl=auto&tl=en&q=${encodeURIComponent(text)}`;
        let raw;
        if (query.length > 1500) {
            raw = await requestText(baseUrl, query);
        } else {
            raw = await requestText(`${baseUrl}&${query}`);
        }
        const data = JSON.parse(raw);

        if (Array.isArray(data)) {
            if (Array.isArray(data[0])) {
                const translated = data.map((item) => (Array.isArray(item) ? item[0] : item)).join("");
                const lang = data[0][1] || "auto";
                return { text: translated, lang: lang };
            } else if (typeof data[0] === "string") {
                return { text: data[0], lang: data[1] || "auto" };
            }
        }
        throw new Error("Unexpected response structure from translation service");
    }

    async function translateViaGoogleGtx(text) {
        const baseUrl = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t";
        const query = `q=${encodeURIComponent(text)}`;
        let raw;
        if (query.length > 1500) {
            raw = await requestText(baseUrl, query);
        } else {
            raw = await requestText(`${baseUrl}&${query}`);
        }
        const data = JSON.parse(raw);

        if (Array.isArray(data) && Array.isArray(data[0])) {
            const translated = data[0]
                .map((item) => (Array.isArray(item) ? item[0] : ""))
                .filter(Boolean)
                .join("");
            const lang = data[2] || "auto";
            return { text: translated, lang: lang };
        }
        throw new Error("Unexpected GTX response structure");
    }

    async function translateToEnglish(text) {
        if (!text || !text.trim()) {
            return null;
        }

        const { protectedText, tokens } = protectTokens(text);

        let result = null;
        try {
            result = await translateViaGoogleDict(protectedText);
        } catch (err1) {
            console.warn("[Auto-English] Dict API failed, trying GTX fallback...", err1);
            try {
                result = await translateViaGoogleGtx(protectedText);
            } catch (err2) {
                console.error("[Auto-English] All translation services failed:", err1, err2);
                throw new Error("Translation network request failed");
            }
        }

        if (!result || typeof result.text !== "string") {
            return null;
        }

        const restored = restoreTokens(result.text, tokens);
        const sourceLang = result.lang || "auto";
        const isEnglish = sourceLang.toLowerCase().startsWith("en") || restored.trim().toLowerCase() === text.trim().toLowerCase();

        return {
            translatedText: restored,
            sourceLanguage: sourceLang,
            sourceLanguageName: getLanguageName(sourceLang),
            isEnglish: isEnglish,
        };
    }

    function findClosestText(fullText, searchText, preferredPos) {
        if (fullText.slice(preferredPos, preferredPos + searchText.length) === searchText) {
            return { index: preferredPos, length: searchText.length };
        }

        let bestIndex = -1;
        let bestDistance = Infinity;
        let pos = fullText.indexOf(searchText);

        while (pos !== -1) {
            const dist = Math.abs(pos - preferredPos);
            if (dist < bestDistance) {
                bestIndex = pos;
                bestDistance = dist;
            }
            pos = fullText.indexOf(searchText, pos + 1);
        }

        if (bestIndex !== -1) {
            return { index: bestIndex, length: searchText.length };
        }

        const trimmed = searchText.trim();
        if (trimmed && trimmed.length > 10) {
            let trimIndex = fullText.indexOf(trimmed);
            let bestTrimIndex = -1;
            let bestTrimDist = Infinity;
            while (trimIndex !== -1) {
                const dist = Math.abs(trimIndex - preferredPos);
                if (dist < bestTrimDist) {
                    bestTrimIndex = trimIndex;
                    bestTrimDist = dist;
                }
                trimIndex = fullText.indexOf(trimmed, trimIndex + 1);
            }
            if (bestTrimIndex !== -1) {
                return { index: bestTrimIndex, length: trimmed.length };
            }
        }

        return null;
    }

    const statusBars = new WeakMap();

    function getOrCreateStatusBar(textarea) {
        if (statusBars.has(textarea)) {
            return statusBars.get(textarea);
        }

        const bar = document.createElement("div");
        bar.className = "btt-auto-english-bar";
        bar.style.cssText = `
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #eef2f5;
            border: 1px solid #b4c0cc;
            border-bottom: none;
            padding: 4px 8px;
            font-family: Verdana, Arial, sans-serif;
            font-size: 11px;
            color: #333;
            border-radius: 4px 4px 0 0;
            box-sizing: border-box;
            user-select: none;
            margin-top: 6px;
            width: 100%;
        `;

        const leftSide = document.createElement("div");
        leftSide.style.cssText = "display: flex; align-items: center; gap: 8px; flex-wrap: wrap;";

        const title = document.createElement("span");
        title.innerHTML = "<strong>\u{1F310} Auto-English</strong>";
        title.style.cssText = "color: #38566b; cursor: default;";

        const autoCheckbox = document.createElement("input");
        autoCheckbox.type = "checkbox";
        autoCheckbox.id = "btt-auto-translate-chk-" + Math.random().toString(36).slice(2, 7);
        autoCheckbox.checked = isAutoPasteEnabled();
        autoCheckbox.style.cssText = "cursor: pointer; margin: 0;";

        const autoLabel = document.createElement("label");
        autoLabel.htmlFor = autoCheckbox.id;
        autoLabel.textContent = "Translate on paste";
        autoLabel.style.cssText = "cursor: pointer; font-size: 11px;";

        autoCheckbox.addEventListener("change", () => {
            setAutoPasteEnabled(autoCheckbox.checked);
            updateStatus("Auto-translate paste: " + (autoCheckbox.checked ? "ON" : "OFF"), "normal", 2000);
        });

        const translateAllBtn = document.createElement("button");
        translateAllBtn.type = "button";
        translateAllBtn.textContent = "Translate Box to English";
        translateAllBtn.style.cssText = `
            cursor: pointer;
            background: #fff;
            border: 1px solid #99aebb;
            border-radius: 3px;
            font-size: 11px;
            padding: 2px 6px;
            color: #114466;
            margin-left: 4px;
        `;
        translateAllBtn.addEventListener("click", () => handleTranslateAll(textarea));

        leftSide.appendChild(title);
        leftSide.appendChild(autoCheckbox);
        leftSide.appendChild(autoLabel);
        leftSide.appendChild(translateAllBtn);

        const statusMsg = document.createElement("div");
        statusMsg.className = "btt-status-msg";
        statusMsg.style.cssText = "font-weight: normal; color: #555; display: flex; align-items: center; gap: 6px; font-size: 11px;";
        statusMsg.textContent = "Ready";

        bar.appendChild(leftSide);
        bar.appendChild(statusMsg);

        if (textarea.parentNode) {
            textarea.parentNode.insertBefore(bar, textarea);
        }

        let clearTimer = null;

        function updateStatus(htmlContent, type = "normal", autoClearMs = 0) {
            clearTimeout(clearTimer);
            statusMsg.innerHTML = htmlContent;
            if (type === "loading") {
                statusMsg.style.color = "#0055aa";
            } else if (type === "success") {
                statusMsg.style.color = "#157030";
            } else if (type === "error") {
                statusMsg.style.color = "#b02020";
            } else {
                statusMsg.style.color = "#555";
            }

            if (autoClearMs > 0) {
                clearTimer = setTimeout(() => {
                    statusMsg.textContent = "Ready";
                    statusMsg.style.color = "#555";
                }, autoClearMs);
            }
        }

        const api = { bar, updateStatus, autoCheckbox };
        statusBars.set(textarea, api);
        return api;
    }

    function handlePaste(event, textarea) {
        if (!isAutoPasteEnabled()) {
            return;
        }

        const clipboard = event.clipboardData || window.clipboardData;
        if (!clipboard) {
            return;
        }

        const rawPasted = clipboard.getData("text/plain");
        if (!rawPasted || !rawPasted.trim()) {
            return;
        }

        // Normalize line breaks to LF (\n) to match textarea DOM normalization
        const pastedText = normalizeLineBreaks(rawPasted);

        console.log("[Auto-English] Paste detected, length:", pastedText.length);

        const ui = getOrCreateStatusBar(textarea);
        const startPos = typeof textarea.selectionStart === "number" ? textarea.selectionStart : 0;

        setTimeout(async () => {
            ui.updateStatus("\u{1F504} Translating pasted text to English...", "loading");

            try {
                const result = await translateToEnglish(pastedText);
                console.log("[Auto-English] Translation result:", result);

                if (!result) {
                    ui.updateStatus("Ready", "normal");
                    return;
                }

                if (result.isEnglish) {
                    ui.updateStatus(`✓ English text detected (${result.sourceLanguage})`, "normal", 2500);
                    return;
                }

                const currentVal = textarea.value;
                const match = findClosestText(currentVal, pastedText, startPos);

                if (!match) {
                    console.warn("[Auto-English] Could not find pasted segment in textarea");
                    ui.updateStatus("⚠️ Text changed before translation completed", "error", 3500);
                    return;
                }

                const targetPos = match.index;
                const matchLen = match.length;
                const translated = result.translatedText;

                if (typeof textarea.setRangeText === "function") {
                    textarea.setRangeText(translated, targetPos, targetPos + matchLen, "end");
                } else {
                    textarea.value = currentVal.substring(0, targetPos) + translated + currentVal.substring(targetPos + matchLen);
                }
                textarea.dispatchEvent(new Event("input", { bubbles: true }));
                textarea.dispatchEvent(new Event("change", { bubbles: true }));

                const undoId = "btt-undo-" + Date.now();
                ui.updateStatus(
                    `✓ Translated from <strong>${result.sourceLanguageName}</strong> <a href="#" id="${undoId}" style="color: #0066cc; text-decoration: underline; margin-left: 5px; font-weight: bold;">Undo</a>`,
                    "success"
                );

                const undoLink = document.getElementById(undoId);
                if (undoLink) {
                    undoLink.addEventListener("click", (e) => {
                        e.preventDefault();
                        const nowVal = textarea.value;
                        const undoMatch = findClosestText(nowVal, translated, targetPos);
                        if (undoMatch) {
                            if (typeof textarea.setRangeText === "function") {
                                textarea.setRangeText(pastedText, undoMatch.index, undoMatch.index + undoMatch.length, "end");
                            } else {
                                textarea.value = nowVal.substring(0, undoMatch.index) + pastedText + nowVal.substring(undoMatch.index + undoMatch.length);
                            }
                            textarea.dispatchEvent(new Event("input", { bubbles: true }));
                            textarea.dispatchEvent(new Event("change", { bubbles: true }));
                            ui.updateStatus("Reverted to original text", "normal", 2500);
                        } else {
                            ui.updateStatus("⚠️ Could not revert text", "error", 2500);
                        }
                    });
                }
            } catch (err) {
                console.error("[Auto-English] Translation error:", err);
                ui.updateStatus("⚠️ " + (err.message || "Translation failed"), "error", 4000);
            }
        }, 30);
    }

    async function handleTranslateAll(textarea) {
        const text = textarea.value;
        if (!text || !text.trim()) {
            alert("Please enter or paste text into the reply box first.");
            return;
        }

        const ui = getOrCreateStatusBar(textarea);
        ui.updateStatus("\u{1F504} Translating entire message to English...", "loading");

        const originalText = text;
        try {
            const result = await translateToEnglish(originalText);
            console.log("[Auto-English] Box translation result:", result);

            if (!result || result.isEnglish) {
                ui.updateStatus("✓ Message is already in English", "normal", 3000);
                return;
            }

            textarea.value = result.translatedText;
            textarea.dispatchEvent(new Event("input", { bubbles: true }));
            textarea.dispatchEvent(new Event("change", { bubbles: true }));

            const undoId = "btt-undo-all-" + Date.now();
            ui.updateStatus(
                `✓ Whole box translated from <strong>${result.sourceLanguageName}</strong> <a href="#" id="${undoId}" style="color: #0066cc; text-decoration: underline; margin-left: 5px; font-weight: bold;">Undo</a>`,
                "success"
            );

            const undoLink = document.getElementById(undoId);
            if (undoLink) {
                undoLink.addEventListener("click", (e) => {
                    e.preventDefault();
                    textarea.value = originalText;
                    textarea.dispatchEvent(new Event("input", { bubbles: true }));
                    textarea.dispatchEvent(new Event("change", { bubbles: true }));
                    ui.updateStatus("Reverted to original text", "normal", 2500);
                });
            }
        } catch (err) {
            console.error("[Auto-English] Translation failed:", err);
            ui.updateStatus("⚠️ " + (err.message || "Translation error"), "error", 4000);
        }
    }

    function isReplyBox(el) {
        return el && el.tagName === "TEXTAREA";
    }

    function attachTextarea(textarea) {
        if (!textarea || textarea.dataset.bttAutoEnglishReady === "1") {
            return;
        }
        textarea.dataset.bttAutoEnglishReady = "1";
        getOrCreateStatusBar(textarea);

        textarea.addEventListener("paste", (e) => {
            handlePaste(e, textarea);
        });

        console.log("[Auto-English] Attached to textarea element", textarea);
    }

    function scanAndAttach() {
        const textareas = document.querySelectorAll("textarea");
        textareas.forEach(attachTextarea);
    }

    document.addEventListener(
        "paste",
        function (e) {
            let el = e.target;
            if (!isReplyBox(el) && isReplyBox(document.activeElement)) {
                el = document.activeElement;
            }
            if (isReplyBox(el)) {
                attachTextarea(el);
                handlePaste(e, el);
            }
        },
        true
    );

    document.addEventListener(
        "focusin",
        function (e) {
            if (isReplyBox(e.target)) {
                attachTextarea(e.target);
            }
        },
        true
    );

    scanAndAttach();

    const observer = new MutationObserver(() => {
        scanAndAttach();
    });

    observer.observe(document.body || document.documentElement, {
        childList: true,
        subtree: true,
    });
})();

DYING_S0UL can you check if this one work for you or not..

I'm not taking any credit,, All credit goes to OP, I just wanted to test things.

Pages: « 1 [2]  All
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!