Advertisement
Guest User

Untitled

a guest
Jan 16th, 2016
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 44.95 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using SteamKit2;
  7. using System.IO;
  8. using System.Threading;
  9. using System.Web.Script.Serialization;
  10.  
  11.  
  12.  
  13. //FIRST thing to do - Add Steamkit2 to project
  14.  
  15. //Now that our account is logged in, we need to make it show as online in our friends list
  16. //We need to create a handler for SteamFriends (SteamLogIn()) *Create static SteamFriends steamFriends first
  17. namespace MySteamBot
  18. {
  19.     class Program
  20.     {
  21.         static SteamClient steamClient;
  22.         static CallbackManager manager;
  23.         static SteamUser steamUser;
  24.         static SteamFriends steamFriends;
  25.  
  26.         static RootObject config;
  27.  
  28.         static string user, pass;
  29.         static string authCode;
  30.         static bool isRunning = false;
  31.  
  32.         static void Main(string[] args)
  33.         {
  34.             if (!File.Exists("chat.txt"))
  35.             {
  36.                 //Create the file, then close the object.
  37.                 File.Create("chat.txt").Close();
  38.                 File.WriteAllText("chat.txt", "abc | 123"); //write this to the file so it isn't empty and providse a template.
  39.             }
  40.             if(!File.Exists("admin.txt"))
  41.             {
  42.                 File.Create("admin.txt").Close();
  43.                 File.WriteAllText("admin.txt", "76561198144194696"); //we populate it with the admin Sid64. You could mode it so you could use plain
  44.                 //SID like: STEAM_0:0:50024954 , but this is how I like it.
  45.             }
  46.  
  47.             reloadConfig(); // load the config. Now let's change up the Group and Personal chat callbacks and add a command to reload the config as well as check if the bot is allowed to speak.
  48.  
  49.             //Then create the console, add a title and some text if you want. Include instructions.
  50.             //Set the title
  51.             Console.Title = "Cakebot 1.0";
  52.             Console.WriteLine("CTRL+C to stop bot.");
  53.             //Our first order of buisness is to retrieve a username and password from the bot user so they can log in.
  54.             //Don't forget to add some string variables for user/pass
  55.             //Console.Write("U: ");
  56.             //user = Console.ReadLine();
  57.  
  58.             //Console.Write("P: ");
  59.             //pass = Console.ReadLine();
  60.             user = "jphilh3";
  61.             pass = "matrix2691";
  62.  
  63.             //We can create a function to make Logging in a bit cleaner, so let's do that.
  64.             SteamLogIn();
  65.            
  66.  
  67.         }
  68.  
  69.         static void SteamLogIn()
  70.         {
  71.             //Need to add static SteamClient() steamClient. We add this to the top of the project to make it available to entire project.
  72.             //We need to create an instance of the SteamClient() class.
  73.             steamClient = new SteamClient();
  74.  
  75.             //We need to add static CallbackManager manager for the same reason.
  76.             //And then create an instance of the CallBackManager class. We put steamClient inside the CallbackManager so we can handle the callbacks.
  77.             manager = new CallbackManager(steamClient);
  78.  
  79.             //Then, we need to create static SteamUser steamUser;, again, for the same reason.
  80.             //Basically, we set steamUser to the handler of the SteamUser class inside of SteamClient. So it becomes the handler of all Steam User related actions and callbacks.
  81.             steamUser = steamClient.GetHandler<SteamUser>();
  82.  
  83.  
  84.             //We need to create the handler for steamfriends, in order to perform
  85.             //Friends related tasks, such as messages and setting our persona state
  86.             steamFriends = steamClient.GetHandler<SteamFriends>();
  87.  
  88.  
  89.             //Now, we can't handle any callbacks without registering the Callbacks with the manager, and the fucntion that we use to handle what happens.
  90.             //First, we register the Connection Callback, so that we can perform actions when we have connected to the Steam Network. We also need to create the function that handles
  91.             new Callback<SteamClient.ConnectedCallback>(OnConnected, manager);
  92.  
  93.             //We need to create an ondisconnected callback to reconnect when the bot is disconnected
  94.             new Callback<SteamClient.DisconnectedCallback>(OnDisconnected, manager); //See OnDisconnected function
  95.  
  96.             //We register a JOB callback, a JobCallback is a callback that performs a specific purpose
  97.             new JobCallback<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth, manager);
  98.  
  99.             //Now we register the Log On callback, and create the OnLoggedOn function
  100.             new Callback<SteamUser.LoggedOnCallback>(OnLoggedOn, manager);
  101.  
  102.             //Now we register the FriendsListCallback, which will fire when the bot recieves its list of friends, (and I think whenever Steam updates it automatically)
  103.             new Callback<SteamFriends.FriendsListCallback>(OnFriendsList, manager);
  104.  
  105.             //Now we register the OnAccountInfo callback, and create its corresponding function
  106.             new Callback<SteamUser.AccountInfoCallback>(OnAccountInfo, manager);
  107.  
  108.             //Now we register the OnSteamMessage callback, and create its corresponding function
  109.             new Callback<SteamFriends.FriendMsgCallback>(OnChatMessage, manager);
  110.  
  111.             //Now we register the OnChatInvite callback, and create its corresponding function
  112.             new Callback<SteamFriends.ChatInviteCallback>(OnChatInvite, manager);
  113.  
  114.             //Now we register the OnChatEnter callback, and create its corresponding function
  115.             new Callback<SteamFriends.ChatEnterCallback>(OnChatEnter, manager);
  116.  
  117.             //Now we register the OnChatMessage callback, and create its corresponding function
  118.             //Notice that its OnChatMessage not OnFriendMessage
  119.             new Callback<SteamFriends.ChatMsgCallback>(OnGroupMessage, manager);
  120.  
  121.             //Now we create an isRunning bool variable so that we can tell a while loop that we're going to create to run the callback manager as long as isRunning is true.
  122.             isRunning = true;
  123.             //Inform the user we are attempting to connect.
  124.             Console.WriteLine("Connecting to Steam...\n");
  125.             //We tell our steamClient class to connect to steam.
  126.             steamClient.Connect();
  127.             //Begin our Callback handling loop. First, we set isRunning to true so that we can begin the loop.
  128.             isRunning = true;
  129.             while (isRunning)
  130.             {
  131.                 //Check for callbacks every second.
  132.                 manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
  133.             }
  134.             Console.ReadKey();
  135.         }
  136.  
  137.         //We give it the ConnectedCallback class, named callback. This is so that we can interact with the callback. Performing specific actions.
  138.         static void OnConnected(SteamClient.ConnectedCallback callback)
  139.         {
  140.             //we check the result of the callback to check if connection was a success or not
  141.             if (callback.Result != EResult.OK)
  142.             {
  143.                 //Inform the user of the failure to connect, and the reason why. {0} gets replaced with the callback result
  144.                 Console.WriteLine("Unable to connect to steam: {0}\n", callback.Result);
  145.                 //Since we didn't connect, we exit the loop.
  146.                 isRunning = false;
  147.                 //Quit the function.
  148.                 return;
  149.             }
  150.  
  151.             //Now we inform the user that the connection was a success. {0} gets replaced with the username the user entered.
  152.             Console.WriteLine("Connected to Steam Network. \nLogging in '{0}'...\n", user);
  153.             //We need to create an array of bytes to hold the sentry file's data
  154.             byte[] sentryHash = null;
  155.             //Now we need to check if 'sentry.bin' exists, and if so, to grab the hash of the file and send it to steam later on
  156.             if (File.Exists("sentry.bin"))
  157.             {
  158.                 //Now, we load all of the bytes into the array
  159.                 byte[] sentryFile = File.ReadAllBytes("sentry.bin");
  160.                 //Now, set sentryHash to the SHAHash of the sentry file, which is loaded into the sentryFile byte array
  161.                 sentryHash = CryptoHelper.SHAHash(sentryFile);
  162.             }
  163.             //Now we attempt to log on by passing the LogOnDetails to steamUser.LogOn
  164.             steamUser.LogOn(new SteamUser.LogOnDetails
  165.             {
  166.                 Username = user,
  167.                 Password = pass,
  168.                 //We add some new stuff, the authcode we grabbed from the user AND the hash of the sentry file
  169.                 AuthCode = authCode,
  170.  
  171.                 SentryFileHash = sentryHash,
  172.             });
  173.             //What we need to do, that is completely necessary, is to create an OnDisconnected callback to reconnect the bot when SteamGuard disconnects it
  174.             //For whatever reason
  175.  
  176.  
  177.             //Now we create a Log On callback to tell the bot what to do, like log in.
  178.         }
  179.  
  180.         //We give it the LoggedOnCallback class, named callback. This is so that we can interact with the callback. Performing specific actions.
  181.         static void OnLoggedOn(SteamUser.LoggedOnCallback callback)
  182.         {
  183.             //Now we check if our log on request was denied
  184.             if (callback.Result == EResult.AccountLogonDenied) //Quick thing, it is supposed to be '==' not '!='
  185.             {
  186.                 //Since it was denied, the account must have SteamGuard protection on.
  187.                 Console.WriteLine("This account is SteamGuard protected.");
  188.                 //We ask the user for the authentication code sent to the email when steam detects an account being accessed from something it doesn't recognize, and inform them of the EMail domain
  189.                 //Steam sent the code to
  190.                 Console.Write("Please enter the auth code sent to the email at {0}: ", callback.EmailDomain);
  191.                 //Now we create a string to hold the authcode
  192.                 //Now, what do we do when we need input from the user? Console.ReadLine()
  193.                 authCode = Console.ReadLine();
  194.                 //Exit the function
  195.                 //Create UpdateMachineAuthCallback
  196.                 return;
  197.             }
  198.             if (callback.Result != EResult.OK)
  199.             {
  200.                 //We inform the user that we couldn't logon to steam, and the reason why.
  201.                 Console.WriteLine("Unable to log in to Steam: {0}\n", callback.Result);
  202.                 //Since we couldn't log on, we exit the loop.
  203.                 isRunning = false;
  204.                 //Exit the function
  205.                 return;
  206.             }
  207.             //Now we can do things! That is the end of this tutorial, however. Next tutorial we will handle SteamGuard so we can log on into a secure account.
  208.             Console.WriteLine("{0} is connected to the Steam Network", user);
  209.         }
  210.  
  211.         //We give it the OnMachineAuth class, named callback. This is so that we can interact with the callback. Performing specific actions.
  212.         //First we need to include SystemIO
  213.         //Now, what we need to do is create the function that handles the UpdateMachineAuthCallback
  214.         static void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback, JobID jobID)
  215.         {
  216.             //inform the user we are updating the sentry file.
  217.             //The sentry file is a special file steam uses to verify whether or not you are authorized.
  218.             Console.WriteLine("Updating sentry file...");
  219.             //What we need to do is grab the hash of the data steam sends back
  220.             //This data is what Steam sends to be put into a sentry file
  221.             byte[] sentryHash = CryptoHelper.SHAHash(callback.Data);
  222.             //Now, we write all the data that Steam sent to us to our new sentry file
  223.             File.WriteAllBytes("sentry.bin", callback.Data);
  224.             //Now we need to inform Steam that we are connecting to a Steam Guard protected account, and have the correct sentry data
  225.             steamUser.SendMachineAuthResponse(new SteamUser.MachineAuthDetails
  226.             {
  227.                 JobID = jobID,
  228.                 FileName = callback.FileName,
  229.                 BytesWritten = callback.BytesToWrite,
  230.                 FileSize = callback.Data.Length,
  231.                 Offset = callback.Offset,
  232.                 Result = EResult.OK,
  233.                 LastError = 0,
  234.                 OneTimePassword = callback.OneTimePassword,
  235.                 SentryFileHash = sentryHash,
  236.             });
  237.             //Inform the user the process is complete
  238.             Console.WriteLine("Done.");
  239.             //Refer to OnConnected steamUser.Logon, adding authcode and sentry hash
  240.         }
  241.  
  242.         //Now we create an OnDisconnected function to have the bot attempt to reconnect
  243.         static void OnDisconnected(SteamClient.DisconnectedCallback callback)
  244.         {
  245.             //Inform the user that the bot was disconnected and is now attempting to reconnect
  246.             Console.WriteLine("\n{0} disconnected from Steam, reconnecting...", user);
  247.             //Sleep the program for 5 seconds
  248.             Thread.Sleep(TimeSpan.FromMilliseconds(10));
  249.             //attempt to reconnect
  250.             steamClient.Connect();
  251.         }
  252.  
  253.         //Here, we will create our OnFriendsList function, this is where we will accept friend requests automatically. We can also do other things while we are at it
  254.         //Such as display our entire friends list inside of the console.
  255.         static void OnFriendsList(SteamFriends.FriendsListCallback callback)
  256.         {
  257.             //We need to make the program sleep for a little bit so it has time to cache all the names, if you don't add this part strange things will happen.
  258.             Thread.Sleep(2500);
  259.  
  260.             //here we will create a foreach loop that will go through our callback.FriendsList and check to see if one of the friends is really someone who wants to be our friend
  261.             //and if so, to add them
  262.             //var is basically a variable declaration for something you don't know will be.
  263.             foreach(var friend in callback.FriendList)
  264.             {
  265.                 //checks our friend relationship to check if they sent a friend request and aren't just a friend already on the list.
  266.                 if(friend.Relationship == EFriendRelationship.RequestRecipient)
  267.                 {
  268.                     //Adds a friend based on their SteamID, because that is how steam friending works
  269.                     steamFriends.AddFriend(friend.SteamID);
  270.                     //Sleep half a second, not necessary but is nice.
  271.                     Thread.Sleep(500);
  272.                     //Notify the user that you are now friends to a bot.
  273.                     steamFriends.SendChatMessage(friend.SteamID, EChatEntryType.ChatMsg, "Hello, I am in alpha!");
  274.                 }
  275.             }
  276.         }
  277.  
  278.         //Now we create our OnAccountInfo function to have the bot perform a specific
  279.         //Action when steam sends it the info of the account it is logged in as
  280.         //What we're going to do is set our "Persona State" to online, this makes the bot
  281.         //Show up as online in people's friends lists
  282.         static void OnAccountInfo(SteamUser.AccountInfoCallback callback)
  283.         {
  284.             //Set our persona state to online
  285.             steamFriends.SetPersonaState(EPersonaState.Online);
  286.             Thread.Sleep(2000);
  287.            
  288.             //Now our bot will show up in our friends list
  289.             //Now, let's create a callback for steam messages so that
  290.             //we can respond to them!
  291.  
  292.         }
  293.  
  294.         //Creating this callback handler allows us to respond to a callback.Message
  295.         //We can perform specific actions based on this callback.Message
  296.         //but for now we will just stick with responding to every callback.Message
  297.         //with "hello"
  298.         static void OnChatMessage(SteamFriends.FriendMsgCallback callback)
  299.         {
  300.             //This allows us to send a callback.Message, callback.Sender is the steam ID
  301.             //of the friend who sent the callback.Message, therefore we can use it
  302.             //for the SendChatMessage function which requires a steam ID
  303.             //Then, chat entry type is set to chat callback.Message in order to
  304.             //inform steam we are sending a text based callback.Message
  305.             //and not a "x user is typing..." or something like that
  306.  
  307.             //this if statement prevents the bot from saying something every while you're typing
  308.             //because the "x user is typing..." is interperated as a steam callback.Message, so
  309.             //we need to check if it's an actual chat callback.Message
  310.  
  311.             //we're going to create a switch statement to mass-check the arguements.
  312.  
  313.             //but first we need to check if the chat callback.Message has a valid length to keep the .Remove() from crashing
  314.  
  315.             if (callback.Message.Length > 1)
  316.             {
  317.                 //we check the first character of the callback.Message for the valid command prefix
  318.                 if (callback.Message.Remove(1) == "!")
  319.                 {
  320.                     //we set a string equal to the callback.Message so we can manipulate it without screwing up the original callback.Message
  321.                     string command = callback.Message;
  322.                     //check to see if the callback.Message contains a space so we can then remove everything after it, so we can check the command. For example: !friend [sid64] becomes !friend.
  323.                     if (callback.Message.Contains(' '))
  324.                     {
  325.                         //set the string command equal to its stripped counterpart. !friend [sid64] becomes !friend for the switch statement later on
  326.                         command = callback.Message.Remove(callback.Message.IndexOf(' '));
  327.                     }
  328.  
  329.                     /*now we use a switch statement, which is basically like a cascaded if statement. Instead of writing
  330.                      * if(command == "!send")
  331.                      * { stuff; }
  332.                      *
  333.                      * else if (command == "!friend")
  334.                      * { stuff; }
  335.                      *
  336.                      * we write
  337.                      *
  338.                      * switch(command)
  339.                      * {
  340.                      * case "!send":
  341.                      * stuff;
  342.                      * break;
  343.                      *
  344.                      * case "!friend":
  345.                      * stuff;
  346.                      * break;
  347.                      * }
  348.                      *
  349.                      * Which is much clearer and easier to write
  350.                      */
  351.  
  352.                     string[] args; //set up an array string for our future args
  353.                     switch (command)
  354.                     {
  355.                         #region joinall
  356.                         case "!joinall":
  357.  
  358.                             if (!isBotAdmin(callback.Sender)) //is the person not a bot admin?
  359.                                 return;
  360.                             Console.WriteLine("!joinall" + " command received. User: " + steamFriends.GetFriendPersonaName(callback.Sender));
  361.                             steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Joining all groups...");
  362.                             steamFriends.JoinChat(110338190880299630);
  363.  
  364.                             steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Done.");
  365.                             break;
  366.                         #endregion
  367.                         #region sendmessage
  368.                         case "!send":
  369.                             //first we need to create a seperation function to seperate the args. so !friend [sid64] becomes args[0] = "!friend", args[1] = "sid64"
  370.                             //okay, now that we've got that, we need to keep people that aren't allowed to use the command from using it. See: isBotAdmin
  371.                             if (!isBotAdmin(callback.Sender)) //is the person not a bot admin?
  372.                                 return; //exit function without executing commands.
  373.                             //seperate our arguments into 3 parts using our seperate function
  374.                             args = Seperate(2, ' ', callback.Message); //args[0] = !send, args[1] = friend to send to, args[2] = callback.Message
  375.                             Console.WriteLine("!send " + args[1] + " " + args[2] + " command received. User: " + steamFriends.GetFriendPersonaName(callback.Sender));
  376.  
  377.                             if (args[0] == "-1") //see if the number of expected arguments was not received
  378.                             {
  379.                                 steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Command syntax: !send [friend] [callback.Message]");
  380.                                 return;
  381.                             }
  382.                             //probably a better way of doing this, but not that important to matter.
  383.                             //iterate through entire friends list and check to see if it matches up to args[1] which is friend name.
  384.                             for (int i = 0; i < steamFriends.GetFriendCount(); i++)
  385.                             {
  386.                                 //get SID of current friend #
  387.                                 SteamID friend = steamFriends.GetFriendByIndex(i);
  388.                                 //Change to lowercase to make matching easier, use .contains so you don't have to use the full name
  389.                                 if (steamFriends.GetFriendPersonaName(friend).ToLower().Contains(args[1].ToLower()))
  390.                                 {
  391.                                     //if it matched, send the callback.Message!
  392.                                     steamFriends.SendChatMessage(friend, EChatEntryType.ChatMsg, args[2]);
  393.                                 }
  394.                             }
  395.                             break;
  396.                         #endregion
  397.                         #region friend
  398.                         case "!friend": //in case we want to friend someone manually
  399.                             //we only have one argument, which is a SID64
  400.                             args = Seperate(1, ' ', callback.Message);
  401.  
  402.  
  403.                             if (args[0] == "-1") //check to see if the number of expected args was received
  404.                             {
  405.                                 steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Command syntax: !friend [Steam ID]");
  406.                                 return;
  407.                             }
  408.  
  409.                             try
  410.                             {
  411.                                 Console.WriteLine("!friend " + args[1] + " | " + steamFriends.GetFriendPersonaName(Convert.ToUInt64(args[1])) + " command recieved. User: " + steamFriends.GetFriendPersonaName(callback.Sender));
  412.                                 //check to see if the user is not an admin
  413.                                 if (!isBotAdmin(callback.Sender))
  414.                                     return;
  415.  
  416.                                 SteamID validSID = Convert.ToUInt64(args[1]); //set the SID = to the argument, we have to convert it to a UINT64, because it can't be a string
  417.                                 if (!validSID.IsValid)
  418.                                 {
  419.                                     steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Invalid SteamID"); //no person exists with that SID
  420.                                     break;
  421.                                 }
  422.                                 steamFriends.AddFriend(validSID.ConvertToUInt64()); //add the friend
  423.                             }
  424.                             catch (FormatException) //see the arg[1] couldn't be converted to a UINT64
  425.                             {
  426.                                 steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Invalid SteamID");
  427.                             }
  428.                             break;
  429.                         #endregion
  430.                         #region changename
  431.                         case "!changename":
  432.                             #region theusualstuff
  433.                             if (!isBotAdmin(callback.Sender))
  434.                                 return;
  435.                             args = Seperate(1, ' ', callback.Message);
  436.                             Console.WriteLine("!changename " + args[1] + " command recieved. User: " + steamFriends.GetFriendPersonaName(callback.Sender));
  437.                             if (args[0] == "-1")
  438.                             {
  439.                                 steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Syntax: !changename [name]");
  440.                                 return;
  441.                             }
  442.                             #endregion
  443.                             steamFriends.SetPersonaName(args[1]); //change name to the second argument. ie !changename bob changes the name to "bob"
  444.                             break;
  445.                         #endregion
  446.                         #region reloadconfig
  447.                         //now that we've got reloadconfig, let's add a quick command to reload the config
  448.                         case "!reloadconfig":
  449.                             if (!isBotAdmin(callback.Sender))
  450.                                 return;
  451.                             reloadConfig();
  452.                             break;
  453.                     }
  454.                     return;
  455.                     #endregion
  456.                    
  457.                 }
  458.             }
  459.             //now that we've got a config and a "Chatty" variable, let's make it so you can tell the bot to talk or not
  460.  
  461.             if (!config.Chatty)
  462.                 return;
  463.             //if the bot is not chatty, exit.
  464.  
  465.             //before we start off, go to main() and work with the chat.txt
  466.             //we'll need two string variables, one to hold the trimed version of the callback.Message, and another to hold the read line.
  467.             string rLine;
  468.             string trimmed = callback.Message; //we can just set it here for now
  469.             //we also need an array of the characters we need to trim from the callback.Message
  470.             char[] trim = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', '\\', '|', ';', ':', '"', '\'', ',', '<', '.', '>', '/', '?' };
  471.  
  472.             //now we need to create a stream reader to read the file that contains all of our chat lines
  473.             StreamReader sReader = new StreamReader("chat.txt");
  474.             //now we need to trim all weird characters from a persons response (this helps with the matching)
  475.             for (int i = 0; i < 30; i++)
  476.             {
  477.                 trimmed = trimmed.Replace(trim[i].ToString(), "");
  478.             }
  479.             //now we need to use that streamreader to read the file of our responses
  480.             while ((rLine = sReader.ReadLine()) != null)
  481.             {
  482.                 //we need to create two local variables, to hold either side of the callback.Message | response
  483.                 string text = rLine.Remove(rLine.IndexOf('|') - 1); //this will give us just 'callback.Message', the -1 removes the trailing space
  484.                 string response = rLine.Remove(0, rLine.IndexOf('|') + 2); //this will give us just 'response', the +2 is to delete the '|' and the space.
  485.                 if (callback.Message.Contains(text)) //does the callback.Message contain the appropriate text?
  486.                 {
  487.                     steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, response); //if so, respond with the response listed in chat.txt
  488.  
  489.                     sReader.Close(); //cleaning up
  490.                     return; //exit method
  491.                 }
  492.             }
  493.         }
  494.  
  495.         //this allows us to join any chat room according to an invite given by a friend
  496.         static void OnChatInvite(SteamFriends.ChatInviteCallback callback)
  497.         {
  498.             steamFriends.JoinChat(callback.ChatRoomID); //Joins a chat according to the chatID given by the callback
  499.             Console.WriteLine(steamFriends.GetFriendPersonaName(callback.PatronID) + " invited bot to " + callback.ChatRoomName + "'s group chat." + " (" + callback.ChatRoomID.ConvertToUInt64().ToString() + ")"); //PatronID = steamID of person who invited the bot
  500.             steamFriends.JoinChat(callback.ChatRoomID);
  501.         }
  502.  
  503.         //this will allow us to give the chat a greet callback.Message, or anything else you want to do
  504.         //when the bot joins a chat
  505.         static void OnChatEnter(SteamFriends.ChatEnterCallback callback)
  506.         {
  507.             //notice that we use SendChatRoomMessage not SendChatMessage
  508.             steamFriends.SendChatRoomMessage(callback.ChatID, EChatEntryType.ChatMsg, "Hello, I am a chatbot.");
  509.         }
  510.  
  511.         //now the real meat of the group chat, the ability to talk and such! This callback allows us to do so.
  512.         //copy and paste everything from OnChatMessage!
  513.         static void OnGroupMessage(SteamFriends.ChatMsgCallback callback)
  514.         {
  515.             if (callback.Message.Length > 1)
  516.             {
  517.                 if (callback.Message.Remove(1) == "!")
  518.                 {
  519.                     string command = callback.Message;
  520.                     if (callback.Message.Contains(' '))
  521.                     {
  522.                         command = callback.Message.Remove(callback.Message.IndexOf(' '));
  523.                     }
  524.  
  525.                     string[] args;
  526.                     switch (command)
  527.                     {
  528.                         case "!":
  529.                             if (!isBotAdmin(callback.ChatterID)) //replace everything that says "callback.ChatterID" with "callback.ChatterID", this is the SteamID of the person who spoke
  530.                                 return;
  531.                             steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Please enter a command.");
  532.                         break;
  533.                         #region sendmessage
  534.                         case "!send":
  535.  
  536.                             if (!isBotAdmin(callback.ChatterID)) //replace everything that says "callback.ChatterID" with "callback.ChatterID", this is the SteamID of the person who spoke
  537.                                 return;
  538.                             args = Seperate(2, ' ', callback.Message);
  539.                             Console.WriteLine("!send " + args[1] + " " + args[2] + " command received. User: " + steamFriends.GetFriendPersonaName(callback.ChatterID));
  540.  
  541.                             if (args[0] == "-1")
  542.                             {
  543.                                 steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Command syntax: !send [friend] [callback.Message]");
  544.                                 return;
  545.                             }
  546.                             for (int i = 0; i < steamFriends.GetFriendCount(); i++)
  547.                             {
  548.                                 SteamID friend = steamFriends.GetFriendByIndex(i);
  549.                                 if (steamFriends.GetFriendPersonaName(friend).ToLower().Contains(args[1].ToLower()))
  550.                                 {
  551.                                     steamFriends.SendChatMessage(friend, EChatEntryType.ChatMsg, args[2]);
  552.                                 }
  553.                             }
  554.                             break;
  555.                         #endregion
  556.                         #region friend
  557.                         case "!friend":
  558.                             args = Seperate(1, ' ', callback.Message);
  559.  
  560.  
  561.                             if (args[0] == "-1")
  562.                             {
  563.                                 steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Command syntax: !friend [Steam ID]");
  564.                                 return;
  565.                             }
  566.  
  567.                             try
  568.                             {
  569.                                 Console.WriteLine("!friend " + args[1] + " | " + steamFriends.GetFriendPersonaName(Convert.ToUInt64(args[1])) + " command recieved. User: " + steamFriends.GetFriendPersonaName(callback.ChatterID));
  570.  
  571.                                 if (!isBotAdmin(callback.ChatterID))
  572.                                     return;
  573.  
  574.                                 SteamID validSID = Convert.ToUInt64(args[1]);
  575.                                 if (!validSID.IsValid)
  576.                                 {
  577.                                     steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Invalid SteamID");
  578.                                     break;
  579.                                 }
  580.                                 steamFriends.AddFriend(validSID.ConvertToUInt64());
  581.                             }
  582.                             catch (FormatException)
  583.                             {
  584.                                 steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Invalid SteamID");
  585.                             }
  586.                             break;
  587.                         #endregion
  588.                         #region changename
  589.                         case "!changename":
  590.                             #region theusualstuff
  591.                             if (!isBotAdmin(callback.ChatterID))
  592.                                 return;
  593.                             args = Seperate(1, ' ', callback.Message);
  594.                             Console.WriteLine("!changename " + args[1] + " command recieved. User: " + steamFriends.GetFriendPersonaName(callback.ChatterID));
  595.                             if (args[0] == "-1")
  596.                             {
  597.                                 steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Syntax: !changename [name]");
  598.                                 return;
  599.                             }
  600.                             #endregion
  601.                             steamFriends.SetPersonaName(args[1]);
  602.                             break;
  603.                         #endregion
  604.                         //now, for some group-specific commands!!!
  605.                         #region kick
  606.                         case "!kick":
  607.                             if (!isBotAdmin(callback.ChatterID))
  608.                                 return;
  609.                             args = Seperate(1, ' ', callback.Message);
  610.                             if (args[0] == "-1")
  611.                             {
  612.                                 steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Syntax: !kick [NAME]");
  613.                                 return;
  614.                             }
  615.  
  616.                             //here we use this to kick the specified SID64
  617.                             try
  618.                             {
  619.                                 //pretty self-explanatory, we need to convert the string to a UInt64, because that is what SteamIDs are.
  620.                                 //steamFriends.KickChatMember(callback.ChatRoomID, Convert.ToUInt64(args[1]));
  621.                                 for (int i = 0; i < steamFriends.GetFriendCount(); i++)
  622.                                 {
  623.                                     SteamID friend = steamFriends.GetFriendByIndex(i);
  624.                                     if (steamFriends.GetFriendPersonaName(friend).ToLower().Contains(args[1].ToLower()))
  625.                                     {
  626.                                         steamFriends.SendChatMessage(friend, EChatEntryType.ChatMsg, args[2]);
  627.                                     }
  628.                                 }
  629.  
  630.  
  631.  
  632.                             }
  633.                             catch (Exception)
  634.                             {
  635.                                 steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Invalid name");
  636.                             }
  637.  
  638.                             break;
  639.                         #endregion
  640.                         //now that we've got reloadconfig, let's add a quick command to reload the config
  641.                         case "!reloadconfig":
  642.                             if (!isBotAdmin(callback.ChatterID))
  643.                                 return;
  644.                             reloadConfig();
  645.                             break;
  646.                     }
  647.                     return;
  648.                 }
  649.             }
  650.             //now, is the bot allowed to talk? If not, return.
  651.             if (!config.Chatty)
  652.                 return;
  653.  
  654.             string rLine;
  655.             string trimmed = callback.Message;
  656.             char[] trim = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', '\\', '|', ';', ':', '"', '\'', ',', '<', '.', '>', '/', '?' };
  657.  
  658.             StreamReader sReader = new StreamReader("chat.txt");
  659.             for (int i = 0; i < 30; i++)
  660.             {
  661.                 trimmed = trimmed.Replace(trim[i].ToString(), "");
  662.             }
  663.             while ((rLine = sReader.ReadLine()) != null)
  664.             {
  665.                 string text = rLine.Remove(rLine.IndexOf('|') - 1);
  666.                 string response = rLine.Remove(0, rLine.IndexOf('|') + 2);
  667.                 if (callback.Message.Contains(text))
  668.                 {
  669.                     steamFriends.SendChatMessage(callback.ChatRoomID, EChatEntryType.ChatMsg, response); //here, we replace callback.Sender with callback.ChatRoomID, so we send the message to the chat room instead of the person.
  670.  
  671.                     sReader.Close();
  672.                     return;
  673.                 }
  674.             }
  675.         }
  676.  
  677.         //we create a seperation function to make checking and using arguements much easier
  678.         //           number of arguements -1 v     seperation char  the string to seperate | the number of arguements - 1 is due to the fact that each arguement is preceded by one space, so "!friend [sid64]" has two args, but only one space.
  679.         public static string[] Seperate(int number, char seperator, string thestring)
  680.         {
  681.             //we create a return array, set v to the max number of arguements ANY of your commands will take.
  682.             string[] returned = new string[4];
  683.             //create a counter variable
  684.             int i = 0;
  685.             //create an error variable to check for errors in the string
  686.             int error = 0;
  687.             //Get the length of the command so we can check it against the error variable to see if the number of arguements expected equaled the number of arguements recieved. for example "!friend" takes two arguements
  688.             //if it were to only recieve one, once "error" equaled the string length and "i" was not equal to the expected number of arguements, we would return an error and handle it inside the switch statement
  689.             //such as sending a chat callback.Message of the command's syntax
  690.             int length = thestring.Length;
  691.             //check each char in a foreach loop
  692.             foreach (char s in thestring)
  693.             {
  694.                 //check to see if the number of arguements expected has been reached yet
  695.                 if (i != number)
  696.                 {
  697.                     //check to see if the number of arguements expected wasn't reached, or if too many were recieved
  698.                     if (error > length || number > 5)
  699.                     {
  700.                         //return an error code
  701.                         returned[0] = "-1";
  702.                         return returned;
  703.                     }
  704.                     //check to see if the current character is equal to our seperator, so we can then isolate it and move it into the appropriate args[x]
  705.                     else if (s == seperator)
  706.                     {
  707.                         returned[i] = thestring.Remove(thestring.IndexOf(s));
  708.                         thestring = thestring.Remove(0, thestring.IndexOf(s) + 1);
  709.                         i++;
  710.                     }
  711.                     //increment error after each iteration
  712.                     error++;
  713.                     //check to see if the # of arguements expected was not reached
  714.                     if (error == length && i != number)
  715.                     {
  716.                         returned[0] = "-1";
  717.                         return returned;
  718.                     }
  719.                 }
  720.  
  721.                 else
  722.                 {
  723.                     //return the last part of the string
  724.                     returned[i] = thestring;
  725.                 }
  726.             }
  727.             //return our array
  728.             return returned;
  729.         }                                                                                                                      
  730.  
  731.         //we need to pass it a SteamID to compare against the one we have in our list
  732.         public static bool isBotAdmin(SteamID sid)
  733.         {
  734.             //But first, we need to create "admins.txt" at bot start up. See Main()
  735.             //Now that we've created that. and populated it, we can check to see if it is the bot admin.
  736.             try //a try/catch statement to fix any issues in case you messed up putting the SID in
  737.             {
  738.                 //Now that we've got a LIST of admins, we can iterate through all of them and check to see if they are an admin.
  739.                 foreach (UInt64 ui in config.Admins) //iterate through all of the admins in the config
  740.                     if (ui == sid)
  741.                         return true; //return true if any of them match.
  742.  
  743.                 //However, if it doesn't match
  744.                 steamFriends.SendChatMessage(sid, EChatEntryType.ChatMsg, "No admin no command."); //inform user they are not allowed
  745.                 Console.WriteLine(steamFriends.GetFriendPersonaName(sid) + "attempted to use an administrator command while not an administrator.");
  746.                 return false; //let the function know the user is not authorized to use it.
  747.  
  748.             }
  749.             catch(Exception e)
  750.             {
  751.                 Console.WriteLine(e.Message);
  752.                 return false; //in case anything goes wrong, we want to automagically return false just in case.
  753.             }
  754.  
  755.         }
  756.  
  757.         public static void reloadConfig()
  758.         {
  759.             if(!File.Exists("config.cfg")) //if the file doesn't exist...
  760.             {
  761.                 //if you ever end up having a large amount of json you want to be default in the config, go to this website to generate a string builder for it. http://www.buildmystring.com/ just copy 'n' paste the JSON into it, and it will automagically generate it.
  762.                 StringBuilder sb = new StringBuilder();
  763.  
  764.                 sb.Append("{\r\n");
  765.                 sb.Append("  \"Admins\":[],\r\n");
  766.                 sb.Append("  \"Chatty\": false\r\n");
  767.                 sb.Append("}\r\n");
  768.                 // you don't really need a string builder per se, but it makes things easier on all of us.
  769.             }
  770.             try
  771.             {
  772.                 //now we parse the JSON, make sure to put a trycatch in order to find errors.
  773.                 JavaScriptSerializer jss = new JavaScriptSerializer();
  774.                 //now, make a rootobject at the top and name it config.
  775.                 //then set it equal like this:
  776.                 config = jss.Deserialize<RootObject>(File.ReadAllText("config.cfg")); //this will populate our JSON classes.
  777.             }
  778.             catch(Exception e)
  779.             {
  780.                 Console.WriteLine(e.Message); //write the error message
  781.                 //read line, wait for error to be fixed then attempt to reload the config again
  782.                 Console.ReadKey();
  783.                 reloadConfig();
  784.             }
  785.             //now that we've made our reloadconfig function, let's place it at main so the config gets parsed.
  786.             //then we will make changes to isBotAdmin and the Chat callbacks.
  787.         }
  788.     }
  789.     //before we start anything, make sure to add "System.Web.Extensions" to the "references", then add "using system.web.script.serialization" to the "using"s.
  790.     //Now, what exactly is JSON? Well, according to json.org it is "JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate."
  791.     //This is usually used for sending configuration and other data over the internet. However, we're going to cheat a bit and grab it from "config.cfg".
  792.     /*
  793.      * {
  794.      * "Admins":[],
  795.      * "Chatty":false
  796.      * }
  797.      */
  798.     //that is what our JSON config is going to look like. This is fairly bare-bones but it is just like that so you can find new uses for information that you can store.
  799.     //the easiest way to make a JSON Object in C# is to go to json2csharp.com and input the JSON you want.
  800.     // v this was generated by that website. Now we want the List to contain a UINT64, which is a SteamID. So change "object" to "uint64"
  801.     public class RootObject
  802.     {
  803.         public List<UInt64> Admins { get; set; } //why a list?! Well, a common question asked by my viewers is "how can I have more than one admin?", this solves that because we can change isBotAdmin to work with the list
  804.         public bool Chatty { get; set; } //bool variable to determine if we want the bot to talk or not.
  805.     } //let's create a "reloadconfig" function to load/reload the configuration file.
  806. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement