Created
November 22, 2016 07:37
-
-
Save DarkLotus/23d6674cbc715455b2892bdbe203370e to your computer and use it in GitHub Desktop.
translated chat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Server; | |
| using Server.Commands; | |
| using Server.Misc; | |
| using Server.Network; | |
| using System; | |
| using System.Collections.Generic; | |
| using System.Globalization; | |
| using System.IO; | |
| using System.Linq; | |
| using System.Net; | |
| using System.Text; | |
| using System.Text.RegularExpressions; | |
| using System.Threading.Tasks; | |
| using System.Web; | |
| using Yam.Microsoft.Translator; | |
| namespace Scripts.Mythik.Systems | |
| { | |
| public class ChatSystem | |
| { | |
| private static string headerValue; | |
| public static void Initialize() | |
| { | |
| CommandSystem.Register("chaton", AccessLevel.Player, new CommandEventHandler(EnableChat)); | |
| CommandSystem.Register("chatoff", AccessLevel.Player, new CommandEventHandler(DisableChat)); | |
| CommandSystem.Register("c", AccessLevel.Player, new CommandEventHandler(SendChatMessage)); | |
| CommandSystem.Register("ch", AccessLevel.Player, new CommandEventHandler(SendChatMessage)); | |
| CommandSystem.Register("chat", AccessLevel.Player, new CommandEventHandler(SendChatMessage)); | |
| CommandSystem.Register("s", AccessLevel.Player, new CommandEventHandler(SendChatMessage)); | |
| CommandSystem.Register("sh", AccessLevel.Player, new CommandEventHandler(SendChatMessage)); | |
| CommandSystem.Register("shout", AccessLevel.Player, new CommandEventHandler(SendChatMessage)); | |
| } | |
| [Usage("c")] | |
| [Aliases("ch", "chat", "s", "sh", "shout")] | |
| [Description("Send a chat message")] | |
| private static void SendChatMessage(CommandEventArgs e) | |
| { | |
| var msg = e.ArgString; | |
| var hue = 0x7a1; | |
| if (e.Mobile.AccessLevel > AccessLevel.Player) | |
| hue = 0x44; | |
| /*if (!(e.Mobile as MythikPlayerMobile).ChatEnabled) | |
| { | |
| e.Mobile.SendAsciiMessage("Enable Chat with .chaton"); | |
| return; | |
| }*/ | |
| List<NetState> list = NetState.Instances; | |
| for (int i = 0; i < list.Count; ++i) | |
| { | |
| if (list[i].Mobile != null) | |
| { | |
| var trans = msg; | |
| if (!e.Mobile.Language.Equals(list[i].Mobile.Language)) | |
| { | |
| trans = TranslateAzure(msg, e.Mobile.Language, list[i].Mobile.Language); | |
| } | |
| Packet p = new AsciiMessage(Serial.MinusOne, -1, MessageType.Regular, hue, 3, "System", "[" + e.Mobile.Name + "]: " + trans); | |
| p.Acquire(); | |
| list[i].Send(p); | |
| p.Release(); | |
| } | |
| } | |
| NetState.FlushAll(); | |
| } | |
| private static void AccessToken() | |
| { | |
| string clientID = ""; | |
| string clientSecret = ""; | |
| String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; | |
| String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret)); | |
| WebRequest webRequest = WebRequest.Create(strTranslatorAccessURI); | |
| webRequest.ContentType = "application/x-www-form-urlencoded"; | |
| webRequest.Method = "POST"; | |
| byte[] bytes = Encoding.ASCII.GetBytes(strRequestDetails); | |
| webRequest.ContentLength = bytes.Length; | |
| using (Stream outputStream = webRequest.GetRequestStream()) | |
| { | |
| outputStream.Write(bytes, 0, bytes.Length); | |
| } | |
| WebResponse webResponse = webRequest.GetResponse(); | |
| System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken)); | |
| //Get deserialized object from Stream | |
| AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); | |
| headerValue = "Bearer " + token.access_token; //create the string for the http header | |
| } | |
| public static string TranslateAzure(string text, string fromCulture, string toCulture) | |
| { | |
| // | |
| var from = LanguageStatistics.InternationalCodes.FirstOrDefault(e => e.Code.Equals(fromCulture)); | |
| var to = LanguageStatistics.InternationalCodes.FirstOrDefault(e => e.Code.Equals(toCulture)); | |
| var fromCultr = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.EnglishName.Contains(from.Language)); | |
| var toCultr = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.EnglishName.Contains(to.Language)); | |
| fromCulture = fromCultr.Name; | |
| toCulture = toCultr.Name; | |
| AccessToken(); //get an access token for each translation because they expire after 10 minutes. | |
| //*****BEGIN CODE TO MAKE THE CALL TO THE TRANSLATOR SERVICE TO PERFORM A TRANSLATION FROM THE USER TEXT ENTERED INCLUDES A CALL TO A SPEECH METHOD***** | |
| try | |
| { | |
| string txtToTranslate = text; | |
| string uri = string.Format("http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&to={0}", toCulture); | |
| WebRequest translationWebRequest = WebRequest.Create(uri); | |
| translationWebRequest.Headers.Add("Authorization", headerValue); //header value is the "Bearer plus the token from ADM | |
| WebResponse response = null; | |
| response = translationWebRequest.GetResponse(); | |
| Stream stream = response.GetResponseStream(); | |
| Encoding encode = Encoding.GetEncoding("utf-8"); | |
| StreamReader translatedStream = new StreamReader(stream, encode); | |
| System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument(); | |
| xTranslation.LoadXml(translatedStream.ReadToEnd()); | |
| return xTranslation.InnerText; | |
| } catch { return TranslateGoogle(text,fromCulture,toCulture); } | |
| } | |
| /// <summary> | |
| /// Translates a string into another language using Google's translate API JSON calls. | |
| /// <seealso>Class TranslationServices</seealso> | |
| /// </summary> | |
| /// <param name="Text">Text to translate. Should be a single word or sentence.</param> | |
| /// <param name="FromCulture"> | |
| /// Two letter culture (en of en-us, fr of fr-ca, de of de-ch) | |
| /// </param> | |
| /// <param name="ToCulture"> | |
| /// Two letter culture (as for FromCulture) | |
| /// </param> | |
| public static string TranslateGoogle(string text, string fromCulture, string toCulture) | |
| { | |
| /* var from = LanguageStatistics.InternationalCodes.FirstOrDefault(e => e.Code.Equals(fromCulture)); | |
| var to = LanguageStatistics.InternationalCodes.FirstOrDefault(e => e.Code.Equals(toCulture)); | |
| var fromCultr = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.EnglishName.Contains(from.Language)); | |
| var toCultr = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.EnglishName.Contains(to.Language)); | |
| fromCulture = fromCultr.Name; | |
| toCulture = toCultr.Name;*/ | |
| //TODO may need to convert UO language codes to standard cultures, need to check values. | |
| fromCulture = fromCulture.ToLower(); | |
| toCulture = toCulture.ToLower(); | |
| // normalize the culture in case something like en-us was passed | |
| // retrieve only en since Google doesn't support sub-locales | |
| string[] tokens = fromCulture.Split('-'); | |
| if (tokens.Length > 1) | |
| fromCulture = tokens[0]; | |
| // normalize ToCulture | |
| tokens = toCulture.Split('-'); | |
| if (tokens.Length > 1) | |
| toCulture = tokens[0]; | |
| string url = string.Format(@"http://translate.google.com/translate_a/t?client=j&text={0}&hl=en&sl={1}&tl={2}", | |
| HttpUtility.UrlEncode(text), fromCulture, toCulture); | |
| // Retrieve Translation with HTTP GET call | |
| string html = null; | |
| try | |
| { | |
| WebClient web = new WebClient(); | |
| // MUST add a known browser user agent or else response encoding doen't return UTF-8 (WTF Google?) | |
| web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0"); | |
| web.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8"); | |
| // Make sure we have response encoding to UTF-8 | |
| web.Encoding = Encoding.UTF8; | |
| html = web.DownloadString(url); | |
| } | |
| catch (Exception ex) | |
| { | |
| return null; | |
| } | |
| var result = html.Remove(0, 1).Replace("\"", ""); | |
| if (string.IsNullOrEmpty(result)) | |
| { | |
| return text; | |
| } | |
| return result; | |
| } | |
| [Usage("chatoff")] | |
| [Description("Disable Chat")] | |
| private static void DisableChat(CommandEventArgs e) | |
| { | |
| //((MythikPlayerMobile)e.Mobile).ChatEnabled = false; | |
| } | |
| [Usage("chaton")] | |
| [Description("Enable Chat")] | |
| private static void EnableChat(CommandEventArgs e) | |
| { | |
| //((MythikPlayerMobile)e.Mobile).ChatEnabled = true; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment