public static Newtonsoft.Json.Linq.JToken Request(BotInstance BotInstance, string URL, string Method = "GET", string PostData = null) { try { WebRequest Req = WebRequest.Create(URL); Req.Method = Method; Req.Headers.Add("Client-ID", BotInstance.LoginConfig["Twitch"]["API"]["ClientId"].ToString()); Req.Headers.Add("Authorization", "OAuth " + GetAuthToken(BotInstance).Token); if (PostData != null) { Byte[] BytePostData = Encoding.UTF8.GetBytes(PostData); Req.ContentLength = BytePostData.Length; Req.ContentType = "application/x-www-form-urlencoded"; Stream PostStream = Req.GetRequestStream(); PostStream.Write(BytePostData, 0, BytePostData.Length); PostStream.Flush(); PostStream.Close(); } WebResponse Res = Req.GetResponse(); string D = new StreamReader(Res.GetResponseStream()).ReadToEnd(); Newtonsoft.Json.Linq.JObject JD = Newtonsoft.Json.Linq.JObject.Parse(D); return(JD); } catch (WebException E) { Console.WriteLine(new StreamReader(E.Response.GetResponseStream()).ReadToEnd()); return(null); } }
/// <summary> /// Handle a bot kill command to kill the bots /// </summary> /// <param name="sender">Sending object</param> /// <param name="listEvent"></param> internal void HandleBotKillEvent(object sender, BotKillEvent listEvent) { // Send the response message to the bot BotInstance sourceBot = (sender as BotInstance); // Make sure the bot is not a public arena bot if ((sourceBot.Settings.SessionSettings.InitialArena.Length > 0) || (listEvent.Message.Equals("!forcekill"))) { // close the bot sourceBot.Close(); // Create a fresh new bot instance BotInstance newBot = new BotInstance(sourceBot.Settings); newBot.CoreEventManager += (new BotEvent(HandleCoreEvents)); // Add the bot to the available list m_availableBots.Add(newBot.Settings.SessionSettings.UserName.ToUpper(), newBot); // Remove the bot from the active list m_activeBots.Remove(sourceBot.Settings.SessionSettings.UserName.ToUpper()); } else { // Create the chat response packet ChatEvent response = new ChatEvent(); // Set the player Identifier to reply to response.PlayerId = listEvent.PlayerId; response.ChatType = ChatTypes.Private; response.Message = "ERROR: unable to !kill bots in public arena!"; sourceBot.SendGameEvent(response); } }
public static bool IsLive(BotInstance BotInstance) { if (((TimeSpan)(DateTime.Now - LastLiveCheck)).TotalSeconds < 15) { return(Islive); } try { Newtonsoft.Json.Linq.JToken JD = GetStreamHelix(BotInstance); if (JD["data"].Count() != 0) { if (JD["data"][0]["type"].ToString() == "live") { Islive = true; return(true); } } LastLiveCheck = DateTime.Now; Islive = false; return(false); } catch (Exception E) { Console.WriteLine(E); return(false); } }
public static StandardisedUser FromDiscordMention(string MessageSegment, BotInstance BotInstance) { StandardisedUser U = new StandardisedUser(); U.ID = MessageSegment.Replace("<@", "").Replace(">", "").Replace("!", ""); return(U); }
public static Newtonsoft.Json.Linq.JToken GenericExecute(BotInstance BotInstance, string URL, string Data, string Method) { WebRequest Req = WebRequest.Create(URL); Req.Method = Method; Req.Headers.Add("Authorization", "Bearer " + GetAuthToken(BotInstance).Token); Req.ContentType = "application/x-www-form-urlencoded"; if (Data != "") { byte[] PostData = Encoding.UTF8.GetBytes(Data); Req.ContentLength = PostData.Length; Stream PostStream = Req.GetRequestStream(); PostStream.Write(PostData, 0, PostData.Length); PostStream.Flush(); PostStream.Close(); } try { WebResponse Res = Req.GetResponse(); string D = new StreamReader(Res.GetResponseStream()).ReadToEnd(); Newtonsoft.Json.Linq.JObject JD = Newtonsoft.Json.Linq.JObject.Parse(D); return(JD); } catch (WebException E) { return(Newtonsoft.Json.Linq.JToken.Parse(new StreamReader(E.Response.GetResponseStream()).ReadToEnd())); } }
/// <summary> /// Method that can be called from a SignalR connection on the front-end to establish /// a connection with Twitch using the provided credentials. /// </summary> /// <param name="botName">The name of the bot.</param> /// <param name="botAccessToken">The access (oauth) token for the bot account.</param> /// <param name="channelName">The name of the Twitch channel the bot should join.</param> public void ConnectToTwitch(string botName, string botAccessToken, string channelName) { if (BotInstance != null) { BotInstance.Connect(botName, botAccessToken, channelName); } }
public static Viewer FromTwitchDiscord(Bots.MessageType e, BotInstance BotInstance, string ID, ref bool CreatedViewer) { List <KeyValuePair <string, string> > Headers = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("CurrencyID", BotInstance.Currency.ID.ToString()) }; if (e == Bots.MessageType.Twitch) { Headers.Add(new KeyValuePair <string, string>("TwitchID", ID)); } if (e == Bots.MessageType.Discord) { Headers.Add(new KeyValuePair <string, string>("DiscordID", ID)); } ResponseObject RObj = WebRequests.PostRequest("viewer", Headers, true); CreatedViewer = RObj.Code == 200; RObj = WebRequests.GetRequest("viewer", Headers); if (RObj.Code == 200) { Viewer B = FromJson(RObj.Data); return(B); } return(null); }
public Fisherman(StandardisedMessageRequest e,BotInstance BotInstance) { this.e = e; this.BotInstance = BotInstance; int MinTime = int.Parse(BotInstance.CommandConfig["CommandSetup"]["Fish"]["MinTime"].ToString()), MaxTime = int.Parse(BotInstance.CommandConfig["CommandSetup"]["Fish"]["MaxTime"].ToString()); SecondsToFish = Init.Rnd.Next(MinTime, MaxTime); }
public static Newtonsoft.Json.Linq.JToken GetViewers(BotInstance BotInstance) { WebRequest Req = WebRequest.Create("https://tmi.twitch.tv/group/user/" + BotInstance.CommandConfig["ChannelName"] + "/chatters"); WebResponse Res = Req.GetResponse(); string D = new StreamReader(Res.GetResponseStream()).ReadToEnd(); Newtonsoft.Json.Linq.JObject JD = Newtonsoft.Json.Linq.JObject.Parse(D); return(JD); }
/// <summary> /// Handle a bot list command to list all bots /// </summary> /// <param name="sender">Sending object</param> /// <param name="listEvent"></param> internal void HandleBotListEvent(object sender, BotListEvent listEvent) { // Send the response message to the bot BotInstance sourceBot = (sender as BotInstance); // Create the chat response packet ChatEvent response = new ChatEvent(); // Set the player Identifier to reply to response.PlayerId = listEvent.PlayerId; response.ChatType = ChatTypes.Private; response.Message = "< ================================================= >"; sourceBot.SendGameEvent(response); response.Message = "< BattleCore Configured Bots >"; sourceBot.SendGameEvent(response); response.Message = "< >"; sourceBot.SendGameEvent(response); response.Message = "< Name Arena Status >"; sourceBot.SendGameEvent(response); response.Message = "< ================================================= >"; sourceBot.SendGameEvent(response); foreach (BotInstance bot in m_activeBots.Values) { // Only list the bots configured for the same server if (bot.Settings.SessionSettings.ServerAddress == sourceBot.Settings.SessionSettings.ServerAddress) { // List the bot status as active response.Message = "< " + bot.Settings.SessionSettings.UserName.PadRight(24) + bot.Settings.SessionSettings.InitialArena.PadRight(16) + "ACTIVE >"; sourceBot.SendGameEvent(response); } } foreach (BotInstance bot in m_availableBots.Values) { // Only list the bots configured for the same server if (bot.Settings.SessionSettings.ServerAddress == sourceBot.Settings.SessionSettings.ServerAddress) { // List the bot as inactive response.Message = "< " + bot.Settings.SessionSettings.UserName.PadRight(24) + bot.Settings.SessionSettings.InitialArena.PadRight(16) + " >"; sourceBot.SendGameEvent(response); } } // Send the response message to the bot response.Message = "< ================================================= >"; sourceBot.SendGameEvent(response); }
public static Newtonsoft.Json.Linq.JToken GetSongFromPos(BotInstance BotInstance, int i) { Newtonsoft.Json.Linq.JToken CurrentQueue = GenericExecute(BotInstance, "https://api.nightbot.tv/1/song_requests/queue", "GET"); if (CurrentQueue["status"].ToString() != "200") { return(Newtonsoft.Json.Linq.JToken.Parse("{\"message\":\"Error occured\",\"status\":400}")); } if (CurrentQueue["queue"].Count() < i || i <= 0) { return(Newtonsoft.Json.Linq.JToken.Parse("{\"message\":\"Out of range!\",\"status\":400}")); } return(CurrentQueue["queue"][i - 1]); }
public static AccessToken GetAuthToken(BotInstance BotInstance) { if (BotInstance.AccessTokens.ContainsKey("Nightbot")) { if (((TimeSpan)(BotInstance.AccessTokens["Nightbot"].ExpiresAt - DateTime.Now)).TotalMinutes > 1) { return(BotInstance.AccessTokens["Nightbot"]); } } WebRequest Req = WebRequest.Create("https://api.nightbot.tv/oauth2/token"); byte[] PostData = Encoding.UTF8.GetBytes("client_id=" + BotInstance.LoginConfig["NightBot"]["ClientId"] + "&client_secret=" + BotInstance.LoginConfig["NightBot"]["ClientSecret"] + "&grant_type=refresh_token&redirect_uri=" + Init.MasterConfig["Redirect"]["WebAddress"] + "/" + Init.MasterConfig["Redirect"]["AddressPath"] + "/nightbot/" + "&refresh_token=" + BotInstance.LoginConfig["NightBot"]["RefreshToken"]); Req.Method = "POST"; Req.ContentType = "application/x-www-form-urlencoded"; Req.ContentLength = PostData.Length; Stream PostStream = Req.GetRequestStream(); PostStream.Write(PostData, 0, PostData.Length); PostStream.Flush(); PostStream.Close(); try { WebResponse Res = Req.GetResponse(); string D = new StreamReader(Res.GetResponseStream()).ReadToEnd(); Newtonsoft.Json.Linq.JObject JD = Newtonsoft.Json.Linq.JObject.Parse(D); BotInstance.LoginConfig["NightBot"]["RefreshToken"] = JD["refresh_token"]; List <KeyValuePair <string, string> > Headers = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("CurrencyID", BotInstance.Currency.ID.ToString()) }; var R = RewardCurrencyAPI.WebRequests.PostRequest("currency", Headers, true, Newtonsoft.Json.Linq.JToken.Parse("{'LoginConfig':" + BotInstance.LoginConfig.ToString() + @"}")); AccessToken Tk = new AccessToken(JD["access_token"].ToString(), int.Parse(JD["expires_in"].ToString())); if (BotInstance.AccessTokens.ContainsKey("Nightbot")) { BotInstance.AccessTokens["Nightbot"] = Tk; } else { BotInstance.AccessTokens.Add("Nightbot", Tk); } return(BotInstance.AccessTokens["Nightbot"]); } catch (WebException E) { Console.WriteLine(new StreamReader(E.Response.GetResponseStream()).ReadToEnd()); return(null); } }
public static string GetLatestTweet(BotInstance BotInstance) { try { Auth.SetUserCredentials( BotInstance.LoginConfig["Twitter"]["ConsumerKey"].ToString(), BotInstance.LoginConfig["Twitter"]["ConsumerSecret"].ToString(), BotInstance.LoginConfig["Twitter"]["AccessToken"].ToString(), BotInstance.LoginConfig["Twitter"]["AccessSecret"].ToString() ); Tweetinvi.Models.IUser TwitterUser = User.GetUserFromScreenName("TheHarbonator"); Tweetinvi.Models.ITweet UsersLatestTweet = TwitterUser.GetUserTimeline(1).Last(); return(UsersLatestTweet.Url); } catch { return("!Was Unable To Find URL!"); } }
public static string LatestVid(BotInstance BotInstance) { WebRequest Req = WebRequest.Create("https://www.googleapis.com/youtube/v3/search?key=" + BotInstance.LoginConfig["Youtube"]["AuthToken"].ToString() + "&channelId=" + BotInstance.LoginConfig["Youtube"]["ChannelID"].ToString() + "&part=snippet,id&order=date&maxResults=1"); Req.Method = "GET"; try { WebResponse Res = Req.GetResponse(); string SData = new StreamReader(Res.GetResponseStream()).ReadToEnd(); Newtonsoft.Json.Linq.JToken Resp = Newtonsoft.Json.Linq.JToken.Parse(SData); return("https://youtu.be/" + Resp["items"][0]["id"]["videoId"].ToString()); } catch { return(null); } }
public static bool MergeAccounts(Bots.StandardisedMessageRequest e, BotInstance BotInstance, string ID) { if (BotInstance.CommandConfig["Discord"]["TwitchMerging"].ToString().ToLower() == "true") { if (e.MessageType == Bots.MessageType.Discord) { if (e.Viewer.TwitchID != "") { return(false); } try { WebRequest Req = WebRequest.Create("https://discordapp.com/api/v6/users/" + ID + "/profile"); Req.Headers.Add("authorization", Init.MasterConfig["Discord"]["User"]["AuthToken"].ToString()); Req.Method = "GET"; WebResponse Res = Req.GetResponse(); string D = new StreamReader(Res.GetResponseStream()).ReadToEnd(); Newtonsoft.Json.Linq.JObject ProfileData = Newtonsoft.Json.Linq.JObject.Parse(D); foreach (Newtonsoft.Json.Linq.JObject Connection in ProfileData["connected_accounts"]) { if (Connection["type"].ToString() == "twitch") { Viewer Twitch = FromTwitchDiscord(Bots.MessageType.Twitch, BotInstance, Connection["id"].ToString()); Viewer Discord = e.Viewer; if (Twitch.DiscordID == "" && Discord.TwitchID == "") { AdjustBalance(Twitch, Twitch.Balance, "-"); AdjustBalance(Discord, Twitch.Balance, "+"); List <KeyValuePair <string, string> > Headers = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("TwitchID", Connection["id"].ToString()), new KeyValuePair <string, string>("DiscordID", ID), new KeyValuePair <string, string>("ID", Discord.ID.ToString()) }; ResponseObject RObj = WebRequests.PostRequest("viewer", Headers, true); Headers = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("ID", Twitch.ID.ToString()) }; RObj = WebRequests.PostRequest("viewer", Headers, true); } } } } catch (WebException E) { } } } return(false); }
public static StandardisedMessageRequest FromTwitch(OnMessageReceivedArgs e, BotInstance BotInstance) { StandardisedMessageRequest S = new StandardisedMessageRequest(); S.MessageBody = e.ChatMessage.Message; S.SegmentedBody = S.MessageBody.Split(" ".ToCharArray()); S.MessageType = MessageType.Twitch; S.SenderID = e.ChatMessage.UserId; S.SenderUserName = e.ChatMessage.Username; S.TwitchRaw = e; S.ChannelName = e.ChatMessage.Channel; S.User = new StandardisedUser(); S.User.ID = S.SenderID; S.User.UserName = S.SenderUserName; S.Viewer = Data.APIIntergrations.RewardCurrencyAPI.Objects.Viewer.FromTwitchDiscord(S, BotInstance, S.User.ID, ref S.IsNewUser); return(S); }
public static StandardisedMessageRequest FromDiscord(SocketMessage e, BotInstance BotInstance) { StandardisedMessageRequest S = new StandardisedMessageRequest(); S.MessageBody = e.Content; S.SegmentedBody = S.MessageBody.Split(" ".ToCharArray()); S.MessageType = MessageType.Discord; S.SenderID = e.Author.Id.ToString(); S.SenderUserName = e.Author.Username; S.DiscordRaw = e; S.ChannelID = e.Channel.Id.ToString(); S.ChannelName = e.Channel.Name; S.User = new StandardisedUser(); S.User.ID = S.SenderID; S.User.UserName = S.SenderUserName; S.Viewer = Data.APIIntergrations.RewardCurrencyAPI.Objects.Viewer.FromTwitchDiscord(S, BotInstance, S.User.ID, ref S.IsNewUser); return(S); }
/// <summary> /// Serves as the main entrypoint for the program. /// Launches the bot and then hangs until the bot is shut down. /// </summary> /// <param name="args">Command-line arguments supplied to the program.</param> public static void Main(string[] args) { BotInstance instance = new BotInstance(); instance.Init(); CoreBot coreBot = new CoreBot("CoreBot"); RoleManagerBot roleBot = new RoleManagerBot("RoleBot"); MessagePurgeBot purgeBot = new MessagePurgeBot("PurgeBot"); coreBot.AttachTo(instance); roleBot.AttachTo(instance); purgeBot.AttachTo(instance); Task.WaitAll(instance.RunAsync()); System.Console.WriteLine("Finished."); }
public static List <Viewer> FromCurrency(BotInstance BotInstance) { List <KeyValuePair <string, string> > Headers = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("CurrencyID", BotInstance.Currency.ID.ToString()) }; ResponseObject RObj = WebRequests.GetRequest("viewer", Headers); if (RObj.Code == 200) { List <Viewer> B = new List <Viewer> { }; foreach (Newtonsoft.Json.Linq.JToken Item in RObj.Data) { B.Add(Item.ToObject <Viewer>()); } return(B); } return(null); }
/// <summary> /// Handle BotGetInfoEvents and sends back info to user - used for modules /// Going to try and keep this internal only. /// </summary> /// <param name="sender">Sending object</param> /// <param name="infoEvent"></param> internal void HandleGetBotInfoEvent(object sender, BotGetInfoEvent infoEvent) { // Send the response message to the bot BotInstance sourceBot = (sender as BotInstance); // Create the chat response packet ChatEvent response = new ChatEvent(); // Get the settings for the source bot BotSettings sourceSettings = sourceBot.Settings; // Set the player Identifier to reply to response.PlayerName = sourceSettings.SessionSettings.UserName; response.ChatType = ChatTypes.Private; response.Message = "@BotInfo@:" + sourceSettings.SessionSettings.UserName + ":" + sourceSettings.SessionSettings.InitialArena; // Send the response message to the bot sourceBot.SendGameEvent(response); }
public static Newtonsoft.Json.Linq.JToken GenericExecute(BotInstance BotInstance, string URL, string Data = "", string Method = "GET", bool URLAuth = false) { if (URLAuth) { if (URL.Contains("?")) { URL += "&access_token=" + GetAuthToken(BotInstance).Token; } else { URL += "?access_token=" + GetAuthToken(BotInstance).Token; } } WebRequest Req = WebRequest.Create(URL); Req.Method = Method; Req.ContentType = "application/x-www-form-urlencoded"; //Req.Timeout = 2000; if (Data != "") { byte[] PostData = Encoding.UTF8.GetBytes(Data); Req.ContentLength = PostData.Length; Stream PostStream = Req.GetRequestStream(); PostStream.Write(PostData, 0, PostData.Length); PostStream.Flush(); PostStream.Close(); } try { WebResponse Res = Req.GetResponse(); string D = new StreamReader(Res.GetResponseStream()).ReadToEnd(); Newtonsoft.Json.Linq.JObject JD = Newtonsoft.Json.Linq.JObject.Parse(D); return(JD); } catch (WebException E) { return(Newtonsoft.Json.Linq.JToken.Parse(new StreamReader(E.Response.GetResponseStream()).ReadToEnd())); } }
public static StandardisedUser FromTwitchUsername(string MessageSegment, BotInstance BotInstance, int Depth = 0) { if (Depth == 5) { return(null); } string UserName = MessageSegment.Replace("@", ""); try { WebRequest Req = WebRequest.Create("https://api.twitch.tv/helix/users?login="******"GET"; Req.Headers.Add("Authorization", BotInstance.LoginConfig["Twitch"]["API"]["AuthToken"].ToString()); WebResponse Res = Req.GetResponse(); string StreamString = new StreamReader(Res.GetResponseStream()).ReadToEnd(); Newtonsoft.Json.Linq.JToken JData = Newtonsoft.Json.Linq.JToken.Parse(StreamString); StandardisedUser U = new StandardisedUser(); U.ID = JData["data"][0]["id"].ToString(); U.UserName = UserName; return(U); } catch { return(null); FromTwitchUsername(MessageSegment, BotInstance, Depth + 1); } return(null); }
public void Start(BotInstance BotInstance) { this.BotInstance = BotInstance; T=new Thread(async () => await TimeThread()); T.Start(); }
public static Viewer FromTwitchDiscord(Bots.MessageType e, BotInstance BotInstance, string ID) { bool Temp = false; return(FromTwitchDiscord(e, BotInstance, ID, ref Temp)); }
public static Viewer FromTwitchDiscord(Bots.StandardisedMessageRequest e, BotInstance BotInstance, string ID, ref bool CreatedViewer) { return(FromTwitchDiscord(e.MessageType, BotInstance, ID, ref CreatedViewer)); }
/// <summary> /// Initializes a new instance of the <see cref="TeamSpeakConnection"/> class. /// </summary> /// <param name="instanceBase">The instance base.</param> public TeamSpeakConnection(BotInstance instanceBase) { BotInstance = instanceBase; Settings = instanceBase.Settings; }
/// <summary> /// Initializes a new instance of the <see cref="CredentialManager"/> class. /// </summary> public CredentialManager(BotInstance botInstance) : base(botInstance) { InitCredential(); }
public Events(BotInstance BotInstance) : base(BotInstance) { }
public Instance(BotInstance BotInstance) : base(BotInstance) { StartBot(); }
public BaseObject(BotInstance BotInstance) { this.BotInstance = BotInstance; }
/// <summary> /// Initializes a new instance of the <see cref="TeamSpeakConnection"/> class. /// </summary> /// <param name="instanceBase">The instance base.</param> public TeamSpeakConnection(BotInstance instanceBase) { BotInstance = instanceBase; Settings = instanceBase.Settings; }
/// <summary> /// Initializes a new instance of the <see cref="CredentialManager"/> class. /// </summary> public CredentialManager(BotInstance botInstance) : base(botInstance) { InitCredential(); }