Using global variables to take lines from a file in order

FLASH NEWS! From OB2 version 0.1.15 you are able to configure resources in your configs, so you don’t need to use the old method described below.

You can go to the config Settings > Data > Resources and configure your file resources. It’s important that you give them a unique name. Then in your config, in the LoliCode section, you can type

TAKEONE FROM "resourceName" => "myString"

or

TAKE 5 FROM "resourceName" => "myList"

to take one or more values from the resource! Easy right?


OUTDATED
In this guide we will cover how to use an external resource, for example a file, which will be shared among all bots so that each bot will fetch a fresh line from the resource, in order, without resuing the same line twice.

This is useful for example if you have a list of user agents but you don’t want to use the built-in random user agent provider because you need every user agent to be used exactly once.

string line;
string file = "abc.txt";

// Lock on the global variables so only 1 bot enters at a time
lock (globals)
{
  IEnumerator<string> enumerator;

  // Try to get an existing enumerator
  try
  {
    enumerator = globals.Enumerator;
  }
  // If it doesn't exist, initialize it
  catch
  {
    enumerator = System.IO.File.ReadLines(file).GetEnumerator();
    globals.Enumerator = enumerator;
  }

  // Check if we can move to the next item of the enumerator
  // take one line.
  if (enumerator.MoveNext())
  {
    line = enumerator.Current;
  }
}

// Here the 'line' variable will be null if the enumerator has no more lines
// Now you can place your blocks and use the 'line' variable as you please!

This snippet will be greatly simplified once the config prologue section is implemented, because you will be able to set up global variables there instead of setting up the try/catch block in the body of the actual config.

Also, you would need to dispose of the enumerator when you’re done otherwise you won’t be able to delete the file because it will appear as being used by OpenBullet 2. This would be something to consider in a future update, by adding an epilogue section which gets called when a job is completed (stop/abort/finish) in order to dispose of the enumerator and release the file.

5 Likes

OUTDATED
You can also load them all in memory at the start and then take them from there.
This is an example with taking 25 lines at a time after loading them all in memory.

List<string> lines;

lock (globals)
{
  List<string> allLines;

  try
  {
    allLines = globals.lines;
  }
  catch
  {
    allLines = System.IO.File.ReadAllLines("abc.txt").ToList();
    globals.lines = allLines;
  }

  lines = allLines.Take(25).ToList();
  allLines.RemoveRange(0, 25);
}

// Now use the `lines` variable
// As you can see below, now globals.lines has 25 elements removed
LOG globals.lines[0]
3 Likes