Unspecified variables in a Javascript bot

Currently, I am working on a project involving the Kik API to create a bot. The main goal is for the game to initiate when users type "!hangman". A boolean value called hangman activates this process and then becomes inactive. Players can then input "!hangman LETTER" to make guesses. It seems straightforward enough. However, there is an unusual glitch that occurs. The first time someone uses "!hangman", everything works correctly. But the second time, the code crashes, citing that "status" and "incorrectletters" are undefined variables, despite being defined earlier in the code. Any assistance or suggestions would be greatly appreciated!

var hangmanIsActive = false;
var hangmanBootup = true;

bot.onTextMessage((message) => {
    if (message.body.startsWith("!help")) {
        message.reply("I know the following commands:\n- !Hangman");
    }

    if (message.body.startsWith("!hangman")) {
        if (hangmanBootup == true){
            hangmanBootup = false;
            message.reply("Welcome to hangman!");

            var triesleft = "Tries left: "
            var inttriesleft = 10

            var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
                            "t", "u", "v", "w", "x", "y", "z"];

            var stage0 = triesleft + inttriesleft;

            var stage1 = "\n"
                        "\n"
                        "\n"
                        "              " + triesleft + {} + "\n"
                        "\n"
                        "\n"
                        "\n"
                        "_|___ \n";

            var stage2 = "\n"
                        " |\n"
                        " |\n"
                        " |            " + triesleft + {} + "\n"
                        " |\n"
                        " | \n"
                        " |\n"
                        "_|___ \n";

            //remaining stages omitted for brevity...

            var words = ["testword"];

            var keyword = "testword";

            var currentstage = stage0;

            var status = keyword.replace(/a/g, "-").replace(/b/g, "-").replace(/c/g, "-").replace(/d/g, "-").replace(/e/g, "-")
                .replace(/f/g, "-").replace(/g/g, "-").replace(/h/g, "-").replace(/i/g, "-").replace(/j/g, "-")
                .replace(/k/g, "-").replace(/l/g, "-").replace(/m/g, "-").replace(/n/g, "-").replace(/o/g, "-")
                .replace(/p/g, "-").replace(/q/g, "-").replace(/r/g, "-").replace(/s/g, "-").replace(/t/g, "-")
                .replace(/u/g, "-").replace(/v/g, "-").replace(/w/g, "-").replace(/x/g, "-").replace(/y/g, "-").replace(/z/g, "-");

            var inttriesleft = 10

            var incorrectletters = []
        };

        message.reply("Word: " + status + "\nIncorrect letters: " + incorrectletters);
        message.reply(currentstage);

        if (message.body.split(" ").length != 2){
            message.reply("To suggest a letter, use \"!hangman a\" for example.");
            return;
        }

        // remaining logic and conditions omitted for brevity...

    };
});

Answer №1

Firstly, it is unnecessary to place a semicolon ; after the closing brace } in if statements.

Secondly, the reason why they are not defined the second time is because you initially defined them inside the bot.onMessage function, which makes them local variables. Therefore, they are destroyed when the function completes. It's better to define them globally at the beginning like this:


var hangmanIsActive = false;
var hangmanBootup = true;
// Define them here instead
var triesleft = "Tries left: ";
var inttriesleft = 10;
var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
                    "t", "u", "v", "w", "x", "y", "z"];
                    
var stage0 = triesleft + inttriesleft;

var stage1 = "\n"
                "\n"
                "\n"
                "              " + triesleft + {} + "\n"
                "\n"
                "\n"
                "\n"
                "_|___ \n";
                
// Rest of the code remains the same...

Your usage of var every time you modify a variable seems repetitive. Remember, var should only be used when initially defining variables, and not every time you update them :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most effective method for serializing SVG data from the client's Document Object Model (DOM

As I delve into the world of creating interactive SVG/AJAX interfaces, I find myself faced with a challenge. Users are constantly manipulating elements on-the-fly and I want to give them the option to export their current view as a PNG image or an SVG docu ...

The query callback does not recognize 'done' as a function, leading to a

I'm attempting to save the result of a query into a variable. I've learned that using a callback is necessary for this task. However, I am encountering errors in the process. function fetchUserData(user) { if (user.checkUserStatus) { var u ...

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

Node.js allows for keeping pipe and sockets open even after streaming an HTTP response

My current challenge involves streaming data from an HTTP response to a cloud storage provider within an internal service. const response = await request<Readable>({ headers: httpOpts?.headers, data: httpOpts?.data, url, method, responseTyp ...

Why am I experiencing a problem with my ajax call only working once when I submit forms that are rendered with @Html.Render

I have a scenario where my index page loads with two partial views, each containing an ajax call that filters content based on date. The issue I'm facing is that the ajax call only works once successfully, and subsequent attempts cause a full page ref ...

What is the best way to refresh my view model while using chained promises?

I've recently started learning about promises and I'm facing a challenge with updating an object in my view from two chained promises: function Test($resource, FC, UserDetailsService) { 'ngInject'; var self = this; se ...

Using v-on:click to dynamically update multiple sections of content in a Vue.js and Liquid environment

Whenever I click on a button, I want the text and image to change. I attempted to do this but encountered difficulties in updating multiple elements simultaneously. {% for variant in product.variants %} <label for="variant_{{- variant.id }}"&g ...

Patience is key when using Selenium with Node.js - make sure to wait for the

Is there a way to ensure my code waits until the page is fully loaded in Node.js while using selenium-webdriver version 4.0.0? const driver = new Builder().forBrowser("firefox").build(); await driver.get("http://www.tsetmc.com/Loader.a ...

Issue: Using the useParams() hook triggers a TypeError, stating that useContext(...) is undefined

Having trouble with the useParams() react hook to fetch a parameter, and encountering this error: Error: useContext(...) is undefined The hooks file throws this error on line 40: /modules/hooks.js:40 39 | > 40 | const match = useContext(Context) ...

Utilizing Node.js with Redis for organizing data efficiently

Currently, I am in the process of configuring a Redis cache system for storing incoming JSON data in a specific format. My goal is to create an ordered list structure to accommodate the large volume of data that will be stored before eventual deletion. Th ...

What is the best way to combine this PHP, Javascript, and HTML document together?

My goal is to upload a CSV file exclusively using an HTML form and then save it in an array using PHP and Javascript. I have individual codes that work perfectly when used as separate files. However, when I attempt to combine them into one file, the Javas ...

Unable to transfer the component between components

This is the code I have: index.js: import React from "react"; import ReactDOM from "react-dom"; import {dest, People} from './components/people'; import json from './people.json'; function initFromJson() { let names = []; for(let ...

When checking if el.text() is equal to "string", it will return false, regardless of the actual content of the element being "string"

Looking at the code snippet below, it seems that the else block is always being executed instead of the if block. The alert confirms that the variable state has the value 'payment' as expected. var state = $('.check-state').text(); ale ...

Tips for implementing controlled components in Vue to update values in the parent component object

Utilizing controlled components, I am able to emit the selected value. For example, // app-select.vue <v-select :items="[1,2,3]" @change="$emit('input', $event)"></v-select> // parent-component.vue <app-sele ...

vaadin-grid selection issue not functioning

I'm encountering an issue with the row selection feature. The selectedItems array only updates when I select all items at once. I'm not sure if I'm missing something or if this is a bug. selectedItems: An array that contains the selected ...

Does the rendered ID of an ASPX control always appear the same in the source HTML code?

Let's say I have an aspx textbox with id="txtkms". In the HTML view source, it appears as ContentPlaceHolder1_Gridview1_txtkms_1. I'm curious if this control will always be rendered as ContentPlaceHolder1_Gridview1_txtkms_1 every time I run my as ...

The rendering of HTML DOM is being obstructed on iPhone devices running iOS 13

Currently, I'm developing a web-based URL stream music player using JavaScript. The player functions smoothly on Android devices, but I'm encountering an issue with DOM rendering being blocked on iPhone devices. Despite rearranging the JavaScript ...

Unable to redirect with Asp response.redirect

I have a Login popup form where I use an ajax post request to Login.asp script in order to prevent the page from going to the POST URL after submission. <script> $(function() { $('#contactForm').submit(function(e){ e.preventDe ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...