static void Main(string[] args) { //Initilize the client var _client = new DiscordClient(); StreamReader apifile = File.OpenText("api.txt"); SteamConnection.Connect(); Console.WriteLine("Connected to steam."); _client.MessageReceived += (s, e) => { if (e.Message.IsMentioningMe()) { ClientMentioned(s, e); } Command.CommandController(_client, e.Channel, e.Message.RawText, e.User.Id.ToString(), e.User); if (e.Channel.IsPrivate) { if (e.User.Name != "engi_valk") { Console.WriteLine(e.User.Name + ": " + e.Message.RawText); } } }; _client.ExecuteAndWait(async() => { await _client.Connect(apifile.ReadToEnd(), TokenType.Bot); } ); }
public override IConnection connectToFriend(Friend other) { var conn = new SteamConnection(other); conns.Add(other.id, conn); return(conn); }
private static void onP2PSessionRequest(P2PSessionRequest_t req) { CSteamID other = req.m_steamIDRemote; Log.info("Got a P2P session request: " + req.m_steamIDRemote); Friend match = null; foreach (Friend friend in IPlatform.instance.getFriends()) { if (friend.id == other.m_SteamID) { match = friend; break; } } if (match == null) { match = getFriendFromId(other); } if (IPlatform.instance.onFriendConnected != null) { PlatformConnection conn = new SteamConnection(match, true); conns.Add(other.m_SteamID, conn); IPlatform.instance.onFriendConnected(match, conn); } }
public bool QueueEntityMessage(ulong sendTo, int msgCode, NetworkEntity entity, params object[] args) { SteamConnection c = GetConnection(sendTo); if (c != null) { if (c.messageQueue.Count < maxMessagesQueued) { NetworkMessage msg = new NetworkMessage(msgCode, args); msg.entity = entity; msg.isEntityMsg = true; c.messageQueue.Add(msg); entity.queuedMessage[sendTo] = msg; //straight overwrites, so make sure you handle this interally if it's not null return(true); } else { return(false); } } else { return(false); } }
public GameObject SpawnPrefabInternal(int prefabId, int networkId, int owner, int controller) { Debug.Log("SpawnPrefabInternal : " + prefabId + " :" + networkId + " : " + owner + " : " + controller); if (GetConnection(owner) == null) { Debug.Log("SpawnPrefabInternal:: No connection with index: " + owner + ". Ignoring this SpawnPrefabInternal call"); } GameObject prefab = GetPrefab(prefabId); NetworkGameObject ngo = null; if (prefab != null) { GameObject g = GameObject.Instantiate(prefab); ngo = g.GetComponent <NetworkGameObject>(); ngo.prefabId = prefabId; ngo.networkId = networkId; ngo.owner = owner; ngo.controller = controller; ngo.OnSpawn(); } //add it to the owners entity list if (ngo != null) { SteamConnection c = GetConnection(owner); c.entities[networkId] = ngo; } return(ngo.gameObject); }
public static void Process(ulong sender, params object[] args) { Debug.Log("EntityControlRequest.Process"); //Core.net.OnConnectRequestResponse(sender, (int)args[0], (int)args[1]); int prefabId = (int)args[0]; int networkId = (int)args[1]; int owner = (int)args[2]; int controller = (int)args[3]; NetworkEntity e = Core.net.GetEntity(owner, networkId); SteamConnection c = Core.net.GetConnection(sender); if (e != null && c != null && e.controller == Core.net.me.connectionIndex) //we can only give control if we are the controller { e.controller = c.connectionIndex; //could do some custom logic here to decide whether to return true or false to allow //the take control. In most cases I just want to accept anyways. Core.net.QueueMessage(sender, Core.net.GetMessageCode("EntityControlResponse"), prefabId, networkId, owner, e.controller, true); } else { //no, they can't take control Core.net.QueueMessage(sender, Core.net.GetMessageCode("EntityControlResponse"), prefabId, networkId, owner, e.controller, false); } }
public static void Process(ulong sender, params object[] args) { //Debug.Log("On Rec Connect Req Response"); //Core.net.OnConnectRequestResponse(sender, (int)args[0], (int)args[1]); int prefabId = (int)args[0]; int networkId = (int)args[1]; int owner = (int)args[2]; int controller = (int)args[3]; bool approved = (bool)args[4]; NetworkEntity e = Core.net.GetEntity(owner, networkId); SteamConnection c = Core.net.GetConnection(sender); //you have control now according to the old controller if (e != null && c != null && approved) { e.isPredictingControl = false; e.controller = controller; } else { e.isPredictingControl = false; } //if(e != null) { // e.ControlChanged(); //} Debug.Log("EntityControlResponse::Success: " + approved); }
//connection stuff below public void RegisterMyConnection(ulong steamID) { SteamConnection c = new SteamConnection(); c.steamID = steamID; c.connectionIndex = 0; me = c; }
//connection stuff below public void RegisterMyConnection(ulong steamID) { Debug.Log("Register my connection"); SteamConnection c = new SteamConnection(); c.steamID = steamID; c.connectionIndex = 0; me = c; }
//includes me public SteamConnection GetConnection(int connectionIndex) { if (me.connectionIndex == connectionIndex) { return(me); } SteamConnection c = connections.Values.Where(s => s.connectionIndex == connectionIndex).FirstOrDefault(); return(c); }
public void RegisterConnection(ulong steamID, int playerNum) { SteamConnection c = new SteamConnection(); c.steamID = steamID; c.connectionIndex = playerNum; c.connectionEstablishedTime = Time.realtimeSinceStartup; connections.Add(c.steamID, c); Debug.Log("Registred incoming connection as: " + playerNum); }
public static void Process(ulong sender, params object[] args) { SteamConnection c = Core.net.GetConnection(sender); if (c != null) { c.zone = (int)args[0]; c.lastPosition.x = (float)args[1]; c.lastPosition.y = (float)args[2]; c.lastPosition.z = (float)args[3]; } }
public void QueueEntityMessage(ulong sendTo, int msgCode, NetworkGameObject entity, params object[] args) { SteamConnection c = GetConnection(sendTo); if (c != null) { NetworkMessage msg = new NetworkMessage(msgCode, args); msg.entity = entity; msg.isEntityMsg = true; c.messageQueue.Add(msg); } }
public NetworkGameObject GetEntity(int owner, int networkId) { SteamConnection c = GetConnection(owner); if (c != null) { return(c.entities[networkId]); } else { return(null); } }
public void RegisterConnection(ulong steamID, int playerNum = -1) { if (connections.ContainsKey(steamID)) { return; //already in the list } SteamConnection c = new SteamConnection(); c.steamID = steamID; c.connectionIndex = playerNum; c.connectionEstablishedTime = Time.realtimeSinceStartup; connections.Add(c.steamID, c); }
public void QueueMessage(ulong sendTo, int msgCode, params object[] args) { //Debug.Log("[SEND] " + MessageCodes[msgCode]); //int dataSize = 0; //byte[] data = PackMessage(out dataSize, sendTo, msgCode, args); //SendP2PData(sendTo, data, dataSize, Networking.SendType.ReliableWithBuffering); //SendP2PData(sendTo, data, data.Length); SteamConnection c = GetConnection(sendTo); if (c != null) { NetworkMessage msg = new NetworkMessage(msgCode, args); c.messageQueue.Add(msg); } }
//Update just handles checking the session state of all current connections, and if anyone has timed out/disconnected //remove them from the connection list and do a bit of cleaup public void FixedUpdate() { _networkSimulationTimer -= Time.fixedDeltaTime; foreach (var kvp in connections) { kvp.Value.timeSinceLastMsg += Time.fixedDeltaTime; } //network loop if (_networkSimulationTimer <= 0f) { _networkSimulationTimer = networkSimulationTimer; List <ulong> disconnects = new List <ulong>(); foreach (var kvp in connections) { SteamConnection c = kvp.Value; if (me.HasAuthOver(c)) //only send keepalives if you're the responsible one in this relationship { if (c.timeSinceLastMsg >= keepAliveTimer) //15 seconds? { c.Ping(); } } Facepunch.Steamworks.Client.Instance.Networking.GetSessionState(c.steamID, out c.connectionState); if (c.connectionState.ConnectionActive == 0 && c.connectionState.Connecting == 0) { disconnects.Add(c.steamID); } } for (int i = 0; i < disconnects.Count; i++) { Disconnect(disconnects[i]); } NetworkSend(); } }
internal static void CommandList(string _command, Channel _channel, DiscordClient _client, User _user, string _parameter = "100") { Random rnd = new Random(); switch (_command) { case "!help": //Help command. Lists all other commands. _channel.SendMessage("Command: !author: Prints my creator.\n" + "Command: !trump + parameter: Makes me post a joke about trump and his wall.\n" + "Command: !image + parameter.filetype: Uploads a reaction image to chat.\n" + "Command: !dice: Rolls a d6.\n" + "Command: !noise: Makes a random noise.\n"); break; case "!author": //Author Command. Prints who made the bot. _channel.SendMessage("My creator is @engi_valk#3982"); break; case "!trump": //Trump Command. Makes a wall joke. _channel.SendMessage("We should build a wall and make " + _parameter + " pay for it!"); break; case "!image": //Image Command. Posts an image. if (_parameter == "blank") { _channel.SendMessage("I need a filename and its type!"); break; } else { _channel.SendFile(_parameter); break; } case "!dice": int number = rnd.Next(0, 6); string[] numberWord = new string[6]; numberWord[0] = "one"; numberWord[1] = "two"; numberWord[2] = "three"; numberWord[3] = "four"; numberWord[4] = "five"; numberWord[5] = "six"; _channel.SendMessage(":" + numberWord[number] + ":"); break; case "!noise": int counter = 0; string line; System.IO.StreamReader noiseMaker = new System.IO.StreamReader("noise.txt"); int lineNumber = rnd.Next(1, 8); while ((line = noiseMaker.ReadLine()) != null) { counter++; if (lineNumber == counter) { line = line.Replace("{{NAME}}", _user.Name); line = line.Replace("{{NICK}}", _user.Nickname); _channel.SendMessage(line); } } noiseMaker.Close(); break; case "!teststeam": SteamConnection.testFunction(_parameter, _channel, _client, _user); break; case "!rollLoot": int lootRoll = rnd.Next(1, 1000); userRoll.Add(new Tuple <string, int>(_user.Name, lootRoll)); _channel.SendMessage(_user.Name + " rolled a: " + lootRoll + ". Their result has been added to the list of potential winners!"); break; case "!printWinner": userRoll = userRoll.OrderByDescending(x => x.Item2).ToList(); for (int i = 0; i < userRoll.Count; i++) { var tupleFromList = userRoll[i]; if (i == 0) { _channel.SendMessage($"{tupleFromList.Item1} rolled {tupleFromList.Item2} and is our big winner!"); } else { _channel.SendMessage($"{tupleFromList.Item1} rolled {tupleFromList.Item2}!"); } } break; } }
private async Task MainAsync() { var startupStr = string.Format("Bot starting up. ({0} by Michael Flaherty)", Program.VERSION); await Log(new LogMessage(LogSeverity.Info, "Startup", startupStr)); var socketConfig = new DiscordSocketConfig { WebSocketProvider = WS4NetProvider.Instance, LogLevel = LogSeverity.Verbose }; client = new DiscordSocketClient(socketConfig); commands = new CommandService(); services = new ServiceCollection().BuildServiceProvider(); messageHist = new Dictionary <ulong, List <MsgInfo> >(); triggerMap = new Dictionary <ulong, string>(); markov = new MarkovHandler(); facts = new FactHandler(); random = new Random(); client.Log += Log; client.GuildAvailable += OnGuildAvailable; client.MessageReceived += HandleCommand; await commands.AddModulesAsync(Assembly.GetEntryAssembly()); await client.LoginAsync(TokenType.Bot, config.DiscordBotToken); await client.StartAsync(); // Connect to steam and pump callbacks connection = new SteamConnection(config.SteamUsername, config.SteamPassword); connection.Connect(); if (config.GitHubUpdateRepository.Length != 0 && config.GitHubAuthToken.Length != 0) { ghClient = new GitHubClient(new ProductHeaderValue(Program.config.GitHubUpdateRepository)); ghClient.Credentials = new Credentials(config.GitHubAuthToken); } // Handle Jobs manager = new JobManager(config.JobInterval); // time in seconds to run each job if (config.SelfUpdateListener && config.GitHubAuthToken.Length != 0) { manager.AddJob(new SelfUpdateListener()); } if (config.SteamCheckJob) { manager.AddJob(new SteamCheckJob(connection)); } if (config.AlliedModdersThreadJob) { manager.AddJob(new AlliedModdersThreadJob("https://forums.alliedmods.net/external.php?newpost=true&forumids=108", "sourcemod")); } foreach (uint appid in config.AppIDList) { manager.AddJob(new UpdateJob(appid)); } manager.StartJobs(); await Task.Delay(-1); }
private async Task MainAsync() { try { Config.Load(); } catch (Exception) { Console.WriteLine("Failed to load config from file. Loading default config."); Config.Default(); Console.WriteLine("Please configure Settings.xml! Exiting program..."); Environment.Exit(0); Console.ReadKey(); } Config.Instance.Save(); Console.WriteLine("Using token: " + Config.Instance.DiscordBotToken); client = new DiscordSocketClient(); commands = new CommandService(); client.Log += Log; services = new ServiceCollection().BuildServiceProvider(); await InstallCommands(); await client.LoginAsync(TokenType.Bot, Config.Instance.DiscordBotToken); await client.StartAsync(); // Connect to steam and pump callbacks connection = new SteamConnection(Config.Instance.SteamUsername, Config.Instance.SteamPassword); new Thread(new ThreadStart(() => { connection.Connect(); })).Start(); // Handle Jobs new Thread(new ThreadStart(() => { var manager = new JobManager(25); // seconds to run each job manager.AddJob(new SteamCheckJob(connection)); // job to check steam connection manager.AddJob(new GithubUpdateJob("https://github.com/alliedmodders/sourcemod/commits/master.atom", "sourcemod")); manager.AddJob(new GithubUpdateJob("https://github.com/alliedmodders/ambuild/commits/master.atom", "sourcemod")); manager.AddJob(new GithubUpdateJob("https://github.com/alliedmodders/metamod-source/commits/master.atom", "sourcemod")); manager.AddJob(new GithubUpdateJob("https://github.com/alliedmodders/hl2sdk/commits/sdk2013.atom", "sourcemod")); manager.AddJob(new AlliedModdersThreadJob("", "sourcemod")); // add appids foreach (uint app in Config.Instance.AppIDList) { manager.AddJob(new UpdateJob(app)); } manager.StartJobs(); })).Start(); await Task.Delay(-1); }
//Update just handles checking the session state of all current connections, and if anyone has timed out/disconnected //remove them from the connection list and do a bit of cleaup public void FixedUpdate() { _networkSimulationTimer -= Time.fixedDeltaTime; foreach (var kvp in connections) { kvp.Value.timeSinceLastMsg += Time.fixedDeltaTime; } _sendConnectionMetadataTimer -= Time.deltaTime; if (_sendConnectionMetadataTimer <= 0f) { _sendConnectionMetadataTimer = SendConnectionMetadataTimer; Core.net.me.BroadcastMetadata(); } //network loop if (_networkSimulationTimer <= 0f) { _networkSimulationTimer = networkSimulationTimer; List <ulong> disconnects = new List <ulong>(); foreach (var kvp in connections) { SteamConnection c = kvp.Value; if (me.HasAuthOver(c)) //only send keepalives if you're the responsible one in this relationship { if (c.timeSinceLastMsg >= keepAliveTimer) //15 seconds? { c.Ping(); } } Facepunch.Steamworks.Client.Instance.Networking.GetSessionState(c.steamID, out c.connectionState); if (c.connectionState.ConnectionActive == 0 && c.connectionState.Connecting == 0) { disconnects.Add(c.steamID); } } for (int i = 0; i < disconnects.Count; i++) { Disconnect(disconnects[i]); } NetworkSend(); } //measuring bits in and bits out int bIn = 0; for (int i = 0; i < bitsInBuffer.Count; i++) { bitsInBuffer[i].timeInBuffer += Time.deltaTime; if (bitsInBuffer[i].timeInBuffer >= bandwidthBuffer) { bitsInBuffer.RemoveAt(i); i--; } else { bIn += bitsInBuffer[i].bits; } } int bOut = 0; for (int i = 0; i < bitsOutBuffer.Count; i++) { bitsOutBuffer[i].timeInBuffer += Time.deltaTime; if (bitsOutBuffer[i].timeInBuffer >= bandwidthBuffer) { bitsOutBuffer.RemoveAt(i); i--; } else { bOut += bitsOutBuffer[i].bits; } } bytesInPerSecond = (int)((float)bIn / (8f * bandwidthBuffer)); bytesOutPerSecond = (int)((float)bOut / (8f * bandwidthBuffer)); if (Input.GetKeyDown(KeyCode.L)) { Core.net.LoadScene(2); } if (Input.GetKeyDown(KeyCode.K)) { Core.net.LoadScene(3); } }
//Highest Auth is the player with the lowest connectionIndex. The host will have connectionIndex of 0 //using an index instead of a bool here so I can have multiple authorities for seperated areas in the same game. //So that you find connected players in your area (map/region) and whoever has the highest auth sends state updates //to everyone else in the area. Similar to Destiny 2's physics hosts. public bool IsHighestAuth(SteamConnection sc) { int a = sc.connectionIndex; return(connections.Any(s => s.Value.connectionIndex < a)); }
public SteamCheckJob(SteamConnection connection) { this.connection = connection; }
//Returns true if you have higher auth than c, this means you're responisible for sending data to them //like state data or keep alives or whatever public bool HasAuthOver(SteamConnection c) { return(connectionIndex < c.connectionIndex); }
public bool inSameZone(SteamConnection c) { return(zone == c.zone); }