Skip to content
TORNLIFE More

[Guide] Learn to code API (with examples)

Started by Omanpx [1906686] on in Tutorials & Guides.

49 replies · 10.3k views · thread synced · 3 days ago · View on torn.com
About this thread

Posts archived: 50 / 50 posts (100%) · the total is Torn's reply count + the opening post at the last fetch

Counted by TornLife from the archived posts.

Archived posts
50
Discussion span
→
Authority score
76 / 100
Historical score
56 / 100
Story score
60 / 100
Engagement score
81 / 100

People posting, likes and official posts are not counted for this thread yet: on threads longer than one page they come from a periodic pass over the archive, which has not covered it.

Most-liked replies

Mentioned in this thread

DeKleineKobini [2114440] ×2

Omanpx [1906686]
The recent newspaper article about Torn API by 0xHemlock probably gave people a much better understanding of what Torn API is and what you can do with it. While the article does an amazing job highlighting the key points of API usage and even provides an example and links to further reading, i wanted to make a cheat-sheet for starting an API project using different programming languages. Because Lord knows it can be daunting at first if you haven’t had any experience with APIs before (speaking from personal experience).

For the purpose of demonstration, i’ll include an example of a super simple script that checks if a player (chosen completely randomly) is still in federal jail. We will be using the same API call for all examples, so let’s look at it closer:
https://api.torn.com/user/51498?selections=profile&comment=demo&key=YOUR_API_KEY
https://api.torn.com/user/ - this part is saying that we are interested in user details
51498 - this is the user ID for our fruit lover
?selections=profile - this part is saying that we are interested in the profile of said fruity boy
&comment=demo - this part lets Torn know who is using your API key (optional)
&key=YOUR_API_KEY - this is where you would enter your API key with correct permissions

To get a better understanding of how to make these API calls, you should start by reading the Unofficial Torn API documentation (which is preferred by most developers over the mostly abandoned Official Torn API documentation). It is also the #1 resource for testing API calls and getting an idea on how to parse them. Now let’s move to some examples!

If you just want to get to the juicy parts, here is a table of contents for you:I try to make money on the side in Torn by making custom spreadsheets or Shiny apps and i realise that sharing this might have a negative impact on my possible income, but i am strong believer in sharing knowledge freely. Sorry to anyone else who’s income might take a hit :P

P.S. if you found this guide useful, you can always show your gratitude by upvoting the posts you liked. Donations are also welcome (wink wink).

Edit: Link to a post on API safety.

Omanpx

Mentions: [Guide] API safety basics and tips · [Guide] Learn to code API (with examples)

Omanpx [1906686]

Notes on API calls

While the official API documentation is very informative and a great place to find answers to most of your questions, there are some things that i wish were documented a little bit better. I have spent more time than i would have liked on these details, so here are a few things that might be not so obvious.

What is a timestamp?

The timestamp you see in the API results is a Unix epoch (or Unix time or POSIX time or Unix timestamp) or the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT). Since Torn Central Time (TCT) is also GMT, it makes conversion between timestamp and normal dates a lot easier. You can play around with this using an EPOCH converter, but there are many ways to convert timestamps to dates. Perhaps the most common application you will find is in Google Sheets, where you can simply use the formula

[=timestamp / 86400 + DATE(1970,1,1) + TIME(0,0,0)]

to get a human-readable date-time (exclude the DATE or TIME part to only extract the other).

Note on logs

Most logs return only the 100 most recent events (this includes 'attacks', 'revives', 'log' and many others). However, 'attacksfull' and 'revivesfull' returns 1000 most recent events, but with less detail. So choose wisely which one suits your application best.

Filtering using `from` and `to`


While the API documentation says that " 'from' and 'to' UNIX timestamps can be passed to filter some selections", it does not specify which ones and how to use it. I will not cover all scenarios here, but instead focus on most common use cases.

To filter 'log' calls, you can either specify both `from` and `to` timestamps, or use just the `to` timestamp (does not work with just the `from`). This is helpful if you are interested in a specific period, or if you want to run a loop to extract historical data. Example:

https://api.torn.com/user/?selections=log&to=1666474567&key=YOUR_API_KEY

would return 100 most recent log entries up to the specified timestamp. This would include all log entries, to filter which ones you want, you would need to specify log type (see below).

For most other queries ('attacks', 'revives', 'attacksfull', etc.) you can either specify both `from` and `to`, or just `from` (except for 'attacks', which works with only `to` as well for some reason...). This can be confusing, so play around and try to make sense of it as best as you can :) Also, keep in mind the 100 and 1000 result limit per call.

Filtering using `timestamp`

Some calls accept `timestamp` instead of `from` and `to`. Most common application is probably getting historical 'personalstats' calls. For this you also need to specify the stats you are interested in (up to 10). Exmaple:

https://api.torn.com/user/?selections=personalstats&stat=networth,xantaken&timestamp=1666474567&key=YOUR_API_KEY

would return the networth and amount of xanax taken at the specified timestamp. Notice the extra `stat` option in the call. I don't use the `timestamp` for many other calls, so let me know if you think of any other things that would be good to know.

Selecting result categories

For some calls you might want (or even need to) specify which categories you are interested in. This was already shown in the 'personalstats' call with the `stat` option, but most common use is probably when looking at logs. For the 'log' call, you can specify which category is of interest to you by adding the log type option like so:

https://api.torn.com/user/?selections=log&log=8155&key=YOUR_API_KEY

would return the latest 100 "Attack mug" logs. This is specified by the `&log=8155` part. To get this ID, simply look at the URL when you filter your logs manually, like "https://www.torn.com/page.php?sid=log&log=8155”.

Note on result caching

When using a timestamp to call previous records (either `timestamp`, or `from` or `to`), you might notice you are getting the same result if you do two calls back to back. This is because historical logs are cached for 30 seconds and you need to wait a bit before using another timestamp for the same call. However, if you want to compare current vs a single previous entry, the caching is not an issue, since current logs are returned instantly (correct me if i'm wrong, speaking from personal experience). Also, i believe this issue can be bypassed by using different API keys (also not 100% sure).

Final remarks

This is not an exhaustive list of API quirks by far and is meant to lead you on the right track. A big thanks goes to DeKleineKobini [2114440] for clearing some things up and working on a proper API documentation which we can hope to see in the near future. Also, feel free to join the API discord to discuss Torn API related matters.

 

 

Mentions: DeKleineKobini [2114440] · Documentation and Discord

Omanpx [1906686]
Google’s Apps Script

Intro: This is the language used in Google Sheets for making custom scripts and creating automated spreadsheets, such as log tracking, price checking, calculators, etc. It is a cloud-based JavaScript platform, so having JS experience will help a lot, but is not mandatory. It might seem to be limited at first, but with enough ingenuity and imagination you can make amazing (and profitable) projects with it!

Usage: custom Google Sheets spreadsheets.

Examples: Vladar’s gym calculator, Jtower’s Torn Helper Tool .

To get started, create a Google Sheets spreadsheet and open the Apps Script editor in Extensions tab:
[image: i.imgur.com]

Code example:
----------------------------------------------
function magnoStatus() {
//Set your active sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Demo");
// Get the API key from cell B1 (this can also be defined as getRange(1,2))
var api = sheet.getRange("B1").getValue();
// Define API call
var call = "https://api.torn.com/user/51498?selections=profile&comment=GSdemo&key="+api;
// Get the JSON response from the API and save it as an object
var response = UrlFetchApp.fetch(call);
var json = response.getContentText();
var data = JSON.parse(json);
// This can also be simplified like so:
// var data = JSON.parse(UrlFetchApp.fetch(call).getContentText());
// Enter the status of MaGnO's plight in cell B2
var fed = "";
if(data['status']['state']=="Federal") {
fed = "Yes (thank God!)";
} else {
fed = "No (hide your API keys!)";
}
sheet.getRange("B2").setValue(fed);
//Finish pending spreadsheet operations
SpreadsheetApp.flush();
}
----------------------------------------------

The output of this code should look like this:
[image: i.imgur.com]

A nice feature of Google Sheets is that it’s easy to automate the scripts using the Triggers menu in Apps Script editor - you can set the function to run on a timer, whenever you open the sheet, or at a specific date for example:
[image: i.imgur.com]

You can also assign the script to run when you press a button on the spreadsheet. Just add an image and assign a script to it:
[image: i.imgur.com]

Mentions: [Spreadsheet] THT - Torn Helper & Tracker · Training Formula V2.0

Omanpx [1906686]
Python

Intro: Python probably needs no introduction, as it is one of the most versatile and popular coding languages. Since the possibilities are endless here, I will only cover an example of using Python to create a super simple Discord bot. Largest part of creating a Discord bot is setting it up and for that, check out the official Discord.py documentation and tutorials like this one. The example does not cover slash commands, as those are a bit more advanced.

Usage: Anything, really. From Discord bots, to backend of custom websites and data analysis pipelines.

Examples: YATA and likely most of the Discord bots out there.

If you want to make a Discord bot, you will need to have Python 3.8 or higher (example below was tested on Python 3.10).

Code example:
Click the link to see code. Torn forums are a pain!

After launching it and adding it to the server you can expect something like this:
[image: i.imgur.com]

If you want to keep the bot active, you will need to keep the python script running all the time. You can use a dedicated server, bot hosting service, or even a raspberry pi. Or just keep it running on your computer without ever shutting it down :)
Omanpx [1906686]
Java Script

DISCLAIMER: I know basically zero JavaScript and HTML and should not be trusted as a source for writing userscripts. The code in this example is scavenged from several scripts by skilled JS coders and works with good wishes alone. With that said, the script below SHOULD work as intended.

Intro: Like Python, Java Script has almost limitless applications, but the most common form Torn users encounter it is by installing userscripts (via Tampermonkey, Greasemonkey, etc.).


Usage: Similar to Python, but most commonly used to make userscripts.

Examples: TDup’s Battle Stats Predictor, finally’s Faction Battlestat Spies and many more.

Most common way of installing userscripts to a browser is by using Tampermonkey or Greasemonkey.

Code example:
Click the link to see code. Torn forums are a pain when writing indented code...

After importing this via Tampermonkey (if it even works), you should see a button above your name, which generates a pop-up detailing MaGnO’s current residency status:
[image: i.imgur.com]
[image: i.imgur.com]

Mentions: [Script] BSP - Battle Stats Predictor · [Script] Warhelper

Omanpx [1906686]
R

Intro: R is a statistical programming language mainly used in data science and research. When used as intended, it is close to Python in popularity, however it is much less versatile than Python. With that said, it is far from useless when it comes to Torn API utilisation and can be used to perform data analysis or even make interactive tools using Shiny. For more on Shiny, see this tutorial.

Usage: Data analysis on a large scale (user databases, simulations, etc.), pretty graphs, interactive tools.

Examples: Training analysis done using simulations in R, Torn-UI shiny application.

If you want to be using R for this, i strongly recommend installing Rstudio

Code example:
----------------------------------------------
# Load required libraries
library(shiny)
library(rjson)
# Global variables can go here
# set your API key
api <- "YOUR_API_KEY"
# set User ID
user <- "51498"
# Define API call
call <- paste0("https://api.torn.com/user/",user,"?selections=profile&comment=Rdemo&key=",api)
# Define the UI
ui <- fluidPage(
# Create a title
h1("Time to check up on MaGnO!"),
# Create a button
actionButton(inputId = "magno",label = "Is MaGnO still fedded?",
icon=icon(name="fas fa-dumpster-fire"))
)
# Define the server code
server <- function(input, output) {
# Get API response
response <- fromJSON(file=call)
# Check if MaGnO is still fedded
if(response$status$state=="Federal") {
fed <- "Yes (thank God!)"
} else {
fed <- "No (hide your API keys!)"
}
# Check if the user pressed the button
observeEvent(input$magno, {
# If button is pressed, make a message pop-up
showModal(
modalDialog(
title = "Is MaGnO still in federal jail?",
fed,
easyClose = TRUE,
footer = NULL)
)
})
}
# Return a Shiny app object
shinyApp(ui = ui, server = server)
----------------------------------------------

The final result is a crappy looking app that lets you know if your API keys are safe:
[image: i.imgur.com]


You can check the app yourself by clicking here.

While it looks unimpressive, Shiny is actually a very powerful platform with tons of customization and features. Plus it offers free hosting for up to 5 apps, so it doesn’t hurt to try!

Mentions: [Tutorial] Make and host Torn apps for free with R · Jumping vs Energy training (with data and plots!) · Torn UI - Gym gains, 1000+ targets, war calculator

Omanpx [1906686]
Where to start

As with most projects, the hardest part is coming up with an interesting and worthwhile idea. To help with this, i would recommend talking to other players and listening to what people are complaining about or what quality of life improvements they would like. Once you have a rough idea for a project, head over to the Torn API documentation page and start experimenting to see if it is possible.

Let’s say you wanted to organise a racing tournament inside your faction, but your lazy faction mates can’t be bothered to fill out a simple form to enter their racing skill and class. As a genius API coder, you take it upon yourself to make a spreadsheet with this data that can be used for matchmaking in the tournament. But where do you start?

It is always a good idea to split a project into smaller tasks:
  • First, you will need to get the list of your faction members with their user IDs.
  • Second, you will need to extract the racing skill and racing points earned for each member.
  • Finally, you will need to put this data into a spreadsheet (like Google Sheets) where you can do good old spreadsheet magic to make a tournament bracket (i will leave this step for you to figure out yourself :P ).
Getting faction member IDs. Head over to the Torn API docs and click the Faction tab, then select basic like so:
[image: i.imgur.com]

If you leave the Faction ID field empty, it will automatically default to the faction of the API key owner. The output should look something like this:
[image: i.imgur.com]

Right off the bat we can find what we came for - under “members”, there is the basic info about each member, starting with their player ID. To extract these IDs, simply loop through the “members” layer (following the Google Sheets example, it would be the data[“members”] field). You have just extracted the full list of faction member IDs in a single API call, pat yourself on the back.

Extracting each player’s racing skill and class. This is the meat and potatoes of the script. Now that you have all of the player IDs, you will need to write another loop looking at their “personalstats” selection. From this, you are only interested in “racingskill” and “racingpointsearned” fields (you can figure this out by looking through all available fields in “personalstats” API call). So your API call for each member would look something like this:

https://api.torn.com/user/MEMBER_ID?selections=personalstats&stat=racingskill,racingpointsearned&key=YOUR_API_KEY

[image: i.imgur.com]

See how we include MEMBER_ID from the list of faction member IDs and only extract the “&stat=racingskill,racingpointsearned” in the call? To get the values we want, you can use "data["personalstats"]["racingskill"]" and "data["personalstats"]["racingpointsearned"]". Keep in mind that for a large faction, this means a lot of API calls, so it is always a good idea to add a short pause between the calls in the loop to not reach the call limit of 100/minute. In Google Apps Script, this can be done using the command “Utilities.sleep(MILLISECONDS);”, where instead of MILLISECONDS you enter a number (500 would be 0.5 seconds for example).

Finally, you need to put all this data in the sheet. For racing skill it is straightforward, as you can just enter it as is. To get the racing class, you can use the racing points earned to get the exact class of each user, since the amount of points needed to unlock a specific class is known (see Torn wiki).

[image: i.imgur.com]

And there you have it - you have just made a spreadsheet for your upcoming faction racing tournament, now just figure out a clever way to pair up racers and burn that rubber!

Link to a working example spreadsheet: HERE. Copy it and go to the Apps Script editor if you want to explore the code.