Simp-O-Matic

Dumb Discord bot in TS.
git clone git://git.knutsen.co/Simp-O-Matic
Log | Files | Refs | README | LICENSE

info.js (13800B)


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
const sanitizeSubstanceName = require('../include/sanitize-substance-name.js');
const Discord = require('discord.js');
const customsJSON = require('../include/customs.json');

const infoQuery = require('../queries/info.js');

const rp = require('request-promise');

const Helpers = require('../helpers.js')

const fetchAndParseURL = async url => {
  try {
    const responseData = await rp(url);

    return JSON.parse(responseData);
  } catch (err) {
    console.error(err);
  }

  return null;
}

const fetchPWSubstanceData = async substanceName => {
  const query = infoQuery.info(substanceName);

  const encodedQuery = encodeURIComponent(query);

  return fetchAndParseURL(
    `https://api.psychonautwiki.org/?query=${encodedQuery}`
  );
}

exports.run = async (client, message, args) => {
  // For keeping track of whether or not a substance is found in the custom sheets
  var hasCustom;

  // Capture messages posted to a given channel and remove all symbols and put everything into lower case
  var str = message.content;
  var substanceName = parseSubstanceName(str);

  // Checks to see if drug is on the customs list
  if (checkIfCustomSheet(substanceName)) {
    console.log('Pulling from custom');
    hasCustom = true;

    // Find the location of the substance object in the JSON and set substance
    let substance = locateCustomSheetLocation(substanceName);

    createPWChannelMessage(substance, message);
  } else {
    console.log('Pulling from PW');
    hasCustom = false;
  }

  if (hasCustom == false) {
    console.log(`Requesting info for ${substanceName}`);
    // Loads GraphQL query as "query" variable

    try {
      const { data } = await fetchPWSubstanceData(substanceName);

      // Logs API's returned object of requested substance
      console.log("Substances response: " + JSON.stringify(data));

      // Send a message to channel if there are zero or more than one substances returned by the API
      // Not sure if the API in its current configuration can return more than one substance
      if (data.substances.length === 0) {
        console.log('Pulling from TS');

        let tripSitURL = `http://tripbot.tripsit.me/api/tripsit/getDrug?name=${substanceName}`;

        const responseData = await fetchAndParseURL(tripSitURL);

        if (responseData.err === true) {
          message.channel.send(`Error: No API data available for **${substanceName}**`);
        } else {
          let substance = responseData.data[0];

          createTSChannelMessage(substance, message);
        }

        return;
      } else if (data.substances.length > 1) {
        message.channel
          .send(`There are multiple substances matching \`${substanceName}\` on PsychonautWiki.`)
          .catch(console.error);
        return;
      } else {
        // Set substance to the first returned substance from PW API
        var substance = data.substances[0];
        createPWChannelMessage(substance, message);
      }
    } catch (err) {
      console.log('Promise rejected/errored out');
      console.log(err);
    }

    // Reset hasCustom
    hasCustom = false;
  }
};

// Functions
//// Create a MessageEmbed powered message utilizing the various field builder functions
function createPWChannelMessage(substance, message) {
  const embed = Helpers.TemplatedMessageEmbed()
    .setTitle(`**${capitalize(substance.name)} drug information**`)
    .addField(
      ':telescope: __Class__',
      buildChemicalClassField(substance) +
      '\n' +
      buildPsychoactiveClassField(substance)
    )
    .addField(':scales: __Dosages__', `${buildDosageField(substance)}\n`, true)
    .addField(
      ':clock2: __Duration__',
      `${buildDurationField(substance)}\n`,
      true
    )
    .addField(
      ':warning: __Addiction potential__',
      buildAddictionPotentialField(substance),
      true
    )
    .addField(
      ':chart_with_upwards_trend: __Tolerance__',
      `${buildToleranceField(substance)}\n`,
      true
    )
    .addField(':globe_with_meridians: __Links__', buildLinksField(substance));

  message.channel.send({ embed });
}
// Custom sheet functions
//// Check if the requested substance is in the customs.json file
function checkIfCustomSheet(drug) {
  console.log('drug: ' + drug);
  if (
    drug == 'ayahuasca' ||
    drug == 'datura' ||
    drug == 'salvia' ||
    drug == 'lsa'
  ) {
    return true;
  } else {
    return false;
  }
}

//// Find the location of a given substance in the customs.json file
function locateCustomSheetLocation(drug) {
  var locationsArray = [];
  var loc;

  // Loop through the JSON file and add all of the names and locations to locationsArray
  for (let i = 0; i < customsJSON.data.substances.length; i++) {
    locationsArray.push({
      name: customsJSON.data.substances[i].name,
      location: i
    });
  }

  // Loop through the locationsArray to find the location of a given substance
  for (let i = 0; i < locationsArray.length; i++) {
    if (locationsArray[i].name == drug) {
      loc = i;
    }
  }

  // Set substance equal to the correct substance in the JSON file
  return customsJSON.data.substances[loc];
}

// Capitalization function
function capitalize(name) {
  if (name === 'lsa') {
    return name.toUpperCase();
  } else {
    return name[0].toUpperCase() + name.slice(1);
  }
}

// Message builders
function buildToleranceField(substance) {
  let tolerances = substance.tolerance;
  let toleranceArr = [];

  if (tolerances) {
    let createToleranceString = function(string, tolerance) {
      return `**${capitalize(string)}**: ${tolerance}`;
    };

    let pushToleranceToArray = function(toleranceTier, tolerance) {
      if (tolerance) {
        toleranceArr.push(createToleranceString(toleranceTier, tolerance));
      }
    };

    // If substance does not have standard tolerances return the custom tolerance
    if (substance.name == 'ayahuasca' || substance.name == 'salvia') {
      return substance.tolerance.tolerance;
    } else {
      // return standard tolerances
      pushToleranceToArray('full', tolerances.full);
      pushToleranceToArray('half', tolerances.half);
      pushToleranceToArray('baseline', tolerances.zero);

      return toleranceArr.join('\n');
    }
  } else {
    return 'No information';
  }
}

function buildDosageField(substance) {
  var messages = [];

  for (let i = 0; i < substance.roas.length; i++) {
    let roa = substance.roas[i];
    let dose = roa.dose;
    let name = capitalize(roa.name);

    // Convert dosage object into a string
    let dosageObjectToString = function(dosageTier) {
      // Set substance dose units
      let unit = dose.units;

      // If there's a dose return dose + unit
      if (dosageTier) {
        if (typeof dosageTier === 'number') {
          return `${dosageTier}${unit}`;
        }
        // If there's a dose range return dose range + unit
        return `${dosageTier.min} - ${dosageTier.max}${unit}`;
      }
    };

    // Function for creating dosage message string
    let createMessageString = function(string, dosage) {
      return `**${capitalize(string)}**: ${dosageObjectToString(dosage)}`;
    };

    // Function to push dosage message to array
    let pushDosageToMessageArray = function(phaseString, phase) {
      if (phase) {
        messages.push(createMessageString(phaseString, phase));
      }
    };

    if (substance.name == 'ayahuasca' || substance.name == 'datura') {
      // Ayahuasca hardcoded message (can really be used for any substance without standard dosage information)
      messages.push(`*(${name})*`);

      // If nonstandard dose add dosage information to messages array
      if (dose) {
        messages.push(`${dose.dosage}`);
        messages.push('');
      } else {
        // This should really never happen
        messages.push('No dosage information.');
      }
    } else {
      messages.push(`*(${name})*`);

      // Add all dosage information
      // Uses double conditional to prevent massive no information walls
      if (dose) {
        pushDosageToMessageArray('threshold', dose.threshold);
        pushDosageToMessageArray('light', dose.light);
        pushDosageToMessageArray('common', dose.common);
        pushDosageToMessageArray('strong', dose.strong);
        pushDosageToMessageArray('heavy', dose.heavy);
        messages.push('');
      } else {
        // Or none if there is none
        messages.push('No dosage information.');
      }
    }
  }
  // Join the message array into a string
  return messages.length > 0 ? messages.join("\n") : "No dosage info."
}

function buildDurationField(substance) {
  var messages = [];

  for (let i = 0; i < substance.roas.length; i++) {
    let roa = substance.roas[i];
    let name = capitalize(roa.name);

    // Parses duration object and returns string
    let durationObjectToString = function(phaseDuration) {
      // If there's a duration range return it + units
      if (phaseDuration) {
        return `${phaseDuration.min} - ${phaseDuration.max} ${
          phaseDuration.units
        }`;
      }
      return undefined;
    };

    // Function for creating message string
    let createMessageString = function(string, phase) {
      return `**${capitalize(string)}**: ${durationObjectToString(phase)}`;
    };

    // Function for pushing dosage message to array
    let pushDurationToMessageArray = function(durationString, phase) {
      if (phase) {
        messages.push(createMessageString(durationString, phase));
      }
    };

    if (substance.name) {
      // Duration
      messages.push(`*(${name})*`);

      if (roa.duration) {
        pushDurationToMessageArray('onset', roa.duration.onset);
        pushDurationToMessageArray('comeup', roa.duration.comeup);
        pushDurationToMessageArray('peak', roa.duration.peak);
        pushDurationToMessageArray('offset', roa.duration.offset);
        pushDurationToMessageArray('afterglow', roa.duration.afterglow);
        pushDurationToMessageArray('total', roa.duration.total);
        messages.push(' ');
      } else {
        messages.push('No duration information.');
      }
    } else {
      console.log('Not sure why this would ever happen');
      messages.push('An unknown error has occurred <@278301453620084736>');
    }
  }
  return messages.length > 0 ? messages.join("\n") : "No duration info."
}

// Builds the chemical class field
function buildChemicalClassField(substance) {
  if ((typeof substance.class != undefined) &&
      (substance.class !== null) &&
      (typeof substance.class.chemical != undefined) &&
      (substance.class.chemical != null))
  {
    return `**Chemical**: ${substance.class.chemical[0]}`;
  } else {
    return 'No chemical class information.';
  }
}

// Builds the psychoactive class field
function buildPsychoactiveClassField(substance) {
  if ((typeof substance.class != undefined) &&
      (substance.class !== null) &&
      (typeof substance.class.psychoactive != undefined) &&
      (substance.class.psychoactive != null))
  {
    return `**Psychoactive**: ${substance.class.psychoactive[0]}`;
  } else {
    return 'No psychoactive class information.';
  }
}

// Builds the addiction potential field
function buildAddictionPotentialField(substance) {
  if (substance.addictionPotential !== null) {
    return `${capitalize(substance.addictionPotential)}\n`;
  } else {
    return 'No addiction potential information.';
  }
}

// Builds the link field
function buildLinksField(substance) {
  return `[PsychonautWiki](https://psychonautwiki.org/wiki/${ substance.name.replace(/ /g, '_',) }) - [Effect Index](https://www.effectindex.com) - [Drug combination chart](https://wiki.tripsit.me/images/3/3a/Combo_2.png)`;
}

function createTSChannelMessage(substance, message) {
  const embed = Helpers.TemplatedMessageEmbed()
    .setTitle(`**${substance.pretty_name} drug information**`)
    .addField(
      ':scales: __Dosages__',
      `${buildTSDosageField(substance)}\n`,
      true
    )
    .addField(
      ':clock2: __Duration__',
      `${buildTSDurationField(substance)}\n`,
      true
    )
    .addField(':globe_with_meridians: __Links__', buildTSLinksField(substance));

  message.channel.send({ embed }).catch(console.error);
}

// Capitalization function
function capitalize(name) {
  if (name === 'lsa') {
    return name.toUpperCase();
  } else {
    return name[0].toUpperCase() + name.slice(1);
  }
}

// Build TS dosage field
function buildTSDosageField(substance) {
  console.log(`in buildTSDosageField -- ${JSON.stringify(substance.formatted_dose)}`)

  if ((typeof substance.formatted_dose != undefined) &&
      (substance.formatted_dose != null))
  {
    // try fancy formatting
    let substanceName = Object.keys(substance.formatted_dose)[0];
    return Object.entries(substance.formatted_dose[substanceName]).map(([intensity, dosageRange]) => {
      return `**${capitalize(intensity)}**: ${dosageRange}`;
    }).join("\n");
  }

  return `${substance.properties.dose}`;
}

// Build TS duration field
function buildTSDurationField(substance) {
  return `${substance.properties.duration}`;
}

// Build TS links field
function buildTSLinksField(substance) {
  return `[PsychonautWiki](https://psychonautwiki.org/wiki/${
    substance.name
  })\n[Effect Index](https://www.effectindex.com)\n[Drug combination chart](http://wiki.tripsit.me/images/3/3a/Combo_2.png)\n[TripSit](http://www.tripsit.me)\n\nInformation sourced from TripSit`;
}

// Parses and sanitizes substance name
function parseSubstanceName(string) {
  let unsanitizedDrugName = string
    .toLowerCase()
    .replace(/^[^\s]+ /, '', -1) // remove first word
    .replace(/-/g, '', -1)
    .replace(/ /g, '', -1);

  // Sanitizes input names to match PsychonautWiki API names
  return sanitizeSubstanceName(unsanitizedDrugName);
}