My discord music bot dont working. Not receiving commands

I tried to develop a discord music bot instead of using another bots. Here`s my code:

const Discord = require('discord.js');
const {
        prefix,
        token,
} = require('./config.json');
const ytdl = require('ytdl-core');
const { CLient, GatewayIntentBits } = require('discord.js')
const client = new Discord.Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers,
    ],
});
const queue = new Map();

client.once('ready', () => {
        console.log('Ready!');
});

client.once('reconnecting', () => {
        console.log('Reconnecting!');
});

client.once('disconnect', () => {
        console.log('Disconnect!');
});

client.on('message', async message => {
        console.log('Message recieved')
        if (message.author.bot) return;
        if (!message.content.startsWith(prefix)) return;

        const serverQueue = queue.get(message.guild.id);

        if (message.content.startsWith(`!play`)) {
                execute(message, serverQueue);
                return;
        } else if (message.content.startsWith(`!skip`)) {
                skip(message, serverQueue);
                return;
        } else if (message.content.startsWith(`!stop`)) {
                stop(message, serverQueue);
                return;
        } else {
                message.channel.send('You need to enter a valid command!')
        }
});

async function execute(message, serverQueue) {
        const args = message.content.split(' ');

        const voiceChannel = message.member.voiceChannel;
        if (!voiceChannel) return message.channel.send('You need to be in a voice channel to play music!');
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
                return message.channel.send('I need the permissions to join and speak in your voice channel!');
        }

        const songInfo = await ytdl.getInfo(args[1]);
        const song = {
                title: songInfo.title,
                url: songInfo.video_url,
        };

        if (!serverQueue) {
                const queueContruct = {
                        textChannel: message.channel,
                        voiceChannel: voiceChannel,
                        connection: null,
                        songs: [],
                        volume: 5,
                        playing: true,
                };

                queue.set(message.guild.id, queueContruct);

                queueContruct.songs.push(song);

                try {
                        var connection = await voiceChannel.join();
                        queueContruct.connection = connection;
                        play(message.guild, queueContruct.songs[0]);
                } catch (err) {
                        console.log(err);
                        queue.delete(message.guild.id);
                        return message.channel.send(err);
                }
        } else {
                serverQueue.songs.push(song);
                console.log(serverQueue.songs);
                return message.channel.send(`${song.title} has been added to the queue!`);
        }

}

function skip(message, serverQueue) {
        if (!message.member.voiceChannel) return message.channel.send('You have to be in a voice channel to stop the music!');
        if (!serverQueue) return message.channel.send('There is no song that I could skip!');
        serverQueue.connection.dispatcher.end();
}

function stop(message, serverQueue) {
        if (!message.member.voiceChannel) return message.channel.send('You have to be in a voice channel to stop the music!');
        serverQueue.songs = [];
        serverQueue.connection.dispatcher.end();
}

function play(guild, song) {
        const serverQueue = queue.get(guild.id);

        if (!song) {
                serverQueue.voiceChannel.leave();
                queue.delete(guild.id);
                return;
        }

        const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
                .on('end', () => {
                        console.log('Music ended!');
                        serverQueue.songs.shift();
                        play(guild, serverQueue.songs[0]);
                })
                .on('error', error => {
                        console.error(error);
                });
        dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
}

client.login(token);

In config.json i have only token variable and prefix var, but i dont use prefix var now.
When I running this script my bot goes online in discord, but doesn’t receive commands, I set up a test output but it turns out the message processing function doesn’t work. What do you think the problem might be?
As a command prefix i use “!”.

Keyboard on mobile opens and closes instantly after entering text input field

Using opencart 2.3.0.2 on mobile device. My keyboard opens then immediately closes after entering my text input field. I successfully used the below code to move the add to cart button and options to above the description but now when I try to enter text into the text field options my keyboard pops open and closes a second later.

It’s my understanding (which is limited) that the window resize event should prevent this behavior but it’s still happening with one present in the code.

<script>
    $(function(){
        // We create a function
        function moveCart(){
            // If user screen is smaller than 768 pixel
            if($(window).width() < 768 ){
                /*
                    select cart area including cart button, options, product title and ...
                    if you want to only move cart button use '#product' instead of '#content > .row > .col-sm-4'
                */
                $('#content > .row > .col-sm-4').removeClass('col-sm-4').addClass('moved-div');
                // now move it
                $('.moved-div').insertAfter('.thumbnails');
            } else {
                /*
                    if user resized his/her screen width and now screen is wider than 767 pixel and we moved cart area before, move it to its original place.
                */
                if($('.moved-div').length){
                    $('.moved-div').insertAfter('#content > .row > .col-sm-8').addClass('col-sm-4').removeClass('moved-div');
                }
            }
        }

        // run function 
        moveCart();

        $(window).resize(function(){
            // run function again if user resized screen
            moveCart();
        })
    });
</script>

Keyboard on on mobile view opens and closes instantly after moving the add to cart and options above the descritpion

Using opencart 2.3.0.2 on mobile device. I’m trying to keep my keyboard from closing when I enter text into the text field option. I successfully used the below code to move the add to cart button and options above the description but now when I try to enter text into the text field options my keyboard pops open and closes a second later. Anyone know how to fix this? It’s my understanding (which is limited) that the window resize event should prevent this but it’s still happening with one present in the code.

<script>
    $(function(){
        // We create a function
        function moveCart(){
            // If user screen is smaller than 768 pixel
            if($(window).width() < 768 ){
                /*
                    select cart area including cart button, options, product title and ...
                    if you want to only move cart button use '#product' instead of '#content > .row > .col-sm-4'
                */
                $('#content > .row > .col-sm-4').removeClass('col-sm-4').addClass('moved-div');
                // now move it
                $('.moved-div').insertAfter('.thumbnails');
            } else {
                /*
                    if user resized his/her screen width and now screen is wider than 767 pixel and we moved cart area before, move it to its original place.
                */
                if($('.moved-div').length){
                    $('.moved-div').insertAfter('#content > .row > .col-sm-8').addClass('col-sm-4').removeClass('moved-div');
                }
            }
        }

        // run function 
        moveCart();

        $(window).resize(function(){
            // run function again if user resized screen
            moveCart();
        })
    });
</script>

SpyOn function does not recognize call after click event

I want to write a unit test for the function renderSetupPage with Vitest. Somthing with the mocked function startGame seems to be wrong, but I can’t find the error.

../scripts/utils.js:

export const renderSetupPage = (container) => {

  // create parent element
  const div = document.createElement("div")
  div.innerHTML = 
  `
  <label for="seed">Seed:</label>
  <input type="text" id="seed" name="seed">
  `

  // create button
  const button = document.createElement("button")
  button.id = "start-game-button"
  button.innerText = "Start Game"
  button.onclick = ()=> startGame()

  // append to parent
  div.appendChild(button)
  container.appendChild(div)
}

export const startGame = () => {
  window.alert("game started")
}

utils.test.js:

import { test, expect, vi, describe } from "vitest";
import * as utils from '../scripts/utils';
import {JSDOM} from "jsdom"

describe.only("that setup page is build correctly", ()=>{

    const dom = new JSDOM("<div id='container'></div>")
    global.document = dom.window.document
    const container = document.getElementById("container")

    utils.renderSetupPage(container)
    const button = container.getElementsByTagName("button")

    // passes
    test("that create button exists",() => {
        expect(button.length).toBe(1)
        expect(button[0].id).toBe("start-game-button")
    })
 
    // fails
    test("that button click starts game",()=>{

        const startGameSpy = vi.spyOn(utils, 'startGame').mockImplementation(()=>{})
        button[0].click()
        expect(startGameSpy).toHaveBeenCalled()

    })
})

The tests returns:

Error: AssertionError: expected "startGame" to be called at least once

which shouldn’t be correct since a click in browser gives me the “Game started” alert.

Not Function Delete Button : CodeIgniter 3 with MySQL and AJAX

I’m learning create application using CodeIgniter 3 that is combine with AJAX. I’ve create a list view of data with some buttons inside (Edit & Delete), but it seems that the code not function well in CodeIgniter 3 with AJAX. Please, can someone help me to fix my code, so it’s can work. Because I’m really new in CodeIgniter. Thank you

This is View :
`<?php
echo(“

?>`

form Electron app: Form fields become disabled after deletion on Windows, but work fine on Mac after form submission

I’m experiencing an issue with my Electron app when executed on Windows that doesn’t occur on macOS. It’s built as a desktop app. Here’s the problem:

When I click the “Delete” button to remove a “transporter” then I click on the “Add button”, all form fields become disabled (can’t edit anything in this form or any other form of the app -> No focus !). Just to mention that DELETION IS DONE !!! No problem with the delete in sqlite db.

the fields remain inaccessible BUT if I minimize the Electron window and then maximize it again, the fields become accessible when I click “Add” !!!! .
This issue only occurs on Windows; the app works perfectly on macOS.

I’ve tried several approaches to resolve this, including:

  • Forcing focus on form fields after deletion
  • Resetting the form
  • Checking for event listeners that might interfere
  • Logging to the console to track the application’s behavior

None of these attempts have solved the issue. I’m at a loss as to why this is happening only on Windows and why minimizing and maximizing the window seems to temporarily fix the problem.
Has anyone encountered a similar issue or can suggest a way to debug this platform-specific behavior in Electron?

Here’s a simplified version of my deletion function:

Main.js

ipcMain.handle('deleteTransporter', async (event, id) => {
  const sql = `DELETE FROM transporters WHERE id = ?`;
  return new Promise((resolve, reject) => {
    db.run(sql, [id], function(err) {
      if (err) {
        console.error('Error deleting transporter:', err);
        reject(err);
      } else {
        console.log(`Transporter with ID ${id} deleted.`);
        resolve(this.changes);
      }
    });
  });
});

Renderer.js

// Deletion
window.deleteTransporter = function (id) {
    if (confirm('Are you sure you want to delete this ?')) {
        window.electronAPI.deleteTransporter(id)
            .then(() => {
                showNotification('Deleted successfully', 'success');
                return loadManageData();  // Reload data after submission
            })
            .then(() => {
                enableAllFormFields(); 
                resetFormState();
                rafraichirInterface();
                logFormFieldsState();
            })
            .catch(error => {
                console.error('Deletion error:', error);
                showNotification('Deletion error', 'error');
                rafraichirInterface();  // Refresh UI
            });
    }
};

loadManageData() in Renderer.js

function loadManageData() {
        console.log('loadManageData start');
        
        Promise.all([
            window.electronAPI.getTransporters(),
            window.electronAPI.getDestinations()
        ])
        .then(([transporters, destinations]) => {
            console.log('Data retrieved and reloaded');
            
            updateTransporterList(transporters);
            updateDestinationList(destinations);
            
            console.log('UI updated');
            
            // Force a complete rerender
            ///document.body.style.display = 'none';
            setTimeout(() => {
                document.body.style.display = '';
                console.log('Re-rendu forcé');
                
                // Reactivate all fields
                enableAllFormFields();
                checkEventListeners();
            }, 100);
        })
        .catch(error => {
            console.error('Problem to load data', error);
            showNotification('Problem to load data", 'error');
        });
    }

EnableAllFormFields in renderer.js

// Function to reactivate all fields
function enableAllFormFields() {
    console.log('Début de enableAllFormFields');
    const forms = document.querySelectorAll('form');
    forms.forEach((form, formIndex) => {
        const fields = form.querySelectorAll('input, select, textarea, button');
        fields.forEach(field => {
            if (field) {
                field.disabled = false;  // Reactivate all tags and all fields
                console.log(`Activated element: ${field.id || field.name || 'Without name'}, type: ${field.type}`);
            } else {
                console.warn('Element not defined');
            }
        });
    });
    console.log('Fin de enableAllFormFields');
}

CheckEventListeners in Renderer.js

function checkEventListeners() {
    const elements = document.querySelectorAll('button, input, select, textarea');
    elements.forEach(el => {
        el.addEventListener('click', () => console.log(`Click on ${el.id || el.className}`));
        el.addEventListener('focus', () => console.log(`Focus on ${el.id || el.className}`));
    });
}

Delete

Add -> form tags not editable on Windows ! (but oK on MAC

How prevent navigation in React spa when user manually enters page href using react router v6?

We have SPA and use react router v6 for navigation.
I have page with set of restricted urls for each page.
Is there any convenient way block navigation when user manually enter the part of url? For example,: http://localhost:0000/patrol user in address bar change http://localhost:0000/otherway and press enter. Can I prevent this navigation if /otherway is in set of restricted urls for current page?
I try to use beforeunload window event but it does not work stable.

const useBlockNavigation = (restrictedUrls: string[]) => {
  const navigate = useNavigate();
  const location = useLocation();

  const [previousLocation, setPreviousLocation] = useState(location.pathname);

  useEffect(() => {
    const checkNavigation = (newPath: string) => {
      return restrictedUrls.includes(newPath);
    };

    const handleNavigation = () => {
      const newPath = location.pathname;

      if (checkNavigation(newPath)) {
        navigate(previousLocation); 
      } else {
        setPreviousLocation(newPath);
      }
    };

    window.addEventListener('popstate', handleNavigation);
    
    const handleBeforeUnload = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      event.returnValue = '';
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    
    handleNavigation();
    return () => {
      window.removeEventListener('popstate', handleNavigation);
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [location, navigate, restrictedUrls, previousLocation]);
};

const MyComponent = () => {
  const restrictedUrlsForCurrentPage = ['/restricted-page-1', '/restricted-page-2'];
  useBlockNavigation(restrictedUrlsForCurrentPage);

  return (
    <div>
      <h1>Current Page</h1>
    </div>
  );
};

export default MyComponent;

IIFE incompatibility with semi-colon JS [duplicate]

Can someone explain this JS behavior?
When inside of IIFE, a statement like
document.body.appendChild(s_host) wouldn’t work without a semi-colon
Having an error of Uncaught TypeError: document.body.appendChild(…) is not a function
And when I put a semi-colon after the statement but do not with my IIFE inside,
It will produce Uncaught TypeError: (intermediate value)(intermediate value)(intermediate value)(intermediate value)(intermediate value)(…) is not a function

The unexpected behavior

(() => {
    const s_host = document.createElement("div")
    const s_root = s_host.attachShadow({ mode: 'closed' })    
    document.body.appendChild(s_host)
    // Uncaught TypeError: document.body.appendChild(...) is not a function
    
    // Button for clear storage
    (() => {
        let storage = chrome.storage.local
        const clear_button = document.createElement("button")    
        clear_button.setAttribute("style",
            `   position: fixed;
                top: 0;
                right: 0;
                height: 20px;
                width: 40px;
                background-color: green;
                border: 1px solid black;            
            `)
        clear_button.addEventListener("click", () => {
            storage.get(null, data => {
                console.log("Storage before clearing: ")
                console.log(data)
                storage.clear(() => {
                    if(chrome.runtime.lastError){
                        console.error("Storage has not been cleared", chrome.runtime.lastError)
                    } else {
                        storage.get(null, data => console.log("Storage successfully cleared: ", data))
                    }
                })
            })
        })
        s_root.appendChild(clear_button)
    })()
    Uncaught TypeError: (intermediate value)(intermediate value)(intermediate value)(intermediate value)(intermediate value)(...) is not a function

Otherwise, it’s working well. I’m just curious and I think this is the right place to ask.

phaser 3: Uncaught TypeError: this.game.scene.launch is not a function unable to launch i have implemented a scene manager and im having trouble

phaser 3: Uncaught TypeError: this.game.scene.launch is not a function unable to launch i have implemented a scene manager and im having trouble.

please help i really want to be able to use this scenemanager as it makes stuff a lot easier. i need to use launch because i am having a battle with a lot of temporary variables like the health bars and stuff and when i open the inventory to use an item i need to be able to resume the battle. it lets me use start, and pause, and resume, but when i start it stops the previous scene. i need to use launch to get around this im pretty sure. but its not letting me. .

the line im having trouble with is this line

this.game.scene.launch(newSceneName, data);

the error im getting is:

Uncaught TypeError: this.game.scene.launch is not a function

i tried to provide context of this.game.scene. i never used it like this before. something wrong with the way im using it.

//when i start my game i run this.

const game = new Phaser.Game(config);


globals.initSceneManager(game);


game.scene.start('MainMenuScene');

//in my globals class i have this:

class Globals {
    constructor() {


        this._inputManager = new InputManager();
        this._sceneManager = null;
    }

    initSceneManager(game) {
        this.sceneManager = new SceneManager(game, this.inputManager); // Pass the input manager
        this.sceneManager.init(); // Initialize the SceneManager
    }

    //and getters and setters. 


    //this is my scenemanager. 


class SceneManager {
    constructor(game, inputManager) {
        this.game = game;
        this.inputManager = inputManager;
        this.currentScene = null;
        // this.sceneManager = game.scene;
    }


    init() {
        this.inputManager.init(this.game); // Initialize input manager with the game context
    }


    transitionTo(newSceneName, data = {}, pauseCurrent = false) {
        console.log(`Transitioning from ${this.currentScene} to ${newSceneName}`);
        console.log('SceneManager methods:', Object.keys(this.game.scene));
        console.log('Is start a function?', typeof this.game.scene.start === 'function');
        console.log('Is launch a function?', typeof this.game.scene.launch === 'function');
        // console.log('SceneManager methods:', Object.keys(this.sceneManager));


        // Disable input listeners immediately
        this.inputManager.disableListeners();


        try{
            if (this.currentScene) {
                if (pauseCurrent) {
                    // this.game.scene.pause(this.currentScene);
                    // console.log('Pausing: ', this.currentScene);
                    console.log('not stopping');
                } else {
                    this.game.scene.stop(this.currentScene);
                    console.log('Stopping: ', this.currentScene);
                }
            }
            // Set a short delay before starting the new scene
            setTimeout(() => {
                // this.currentScene = newSceneName;
                // this.game.scene.start(newSceneName, data);
                this.currentScene = newSceneName;

          
                if (pauseCurrent) {
                    console.log('Launching new scene:', newSceneName);
                    this.game.scene.launch(newSceneName, data);
                
                } else {
                    console.log('Starting new scene:', newSceneName);
                    this.game.scene.start(newSceneName, data);
                }

            
                // Set up new input listeners with a delay
                setTimeout(() => {
                    const inputs = this.getSceneInputs(newSceneName);
                    console.log('Setting inputs for', newSceneName, ':', inputs);
                    this.inputManager.setSceneInputs(newSceneName, inputs);            }, 50);
                }, 25);
            } catch (error) {
                console.error('Error during scene transition:', error);
            }
        }

Using integers for JSON OBJECT IDs created ‘NOT FOUND ERROR’ on the server when updating

I am using integers as object ids, whenever a new element is added, I increment the last id integer value in the list and assign it to the new added element’s id.

Adding items to my list and json db works just fine, but when trying to UPDATE the list (DELETE) it gives me a not found error 404.
I ultimately figured out it was because the assigned value to the IDs is an integer but not a string. But I need an integer value to increment and not a string, or else I have to parseInt the ID string from json file and then increment it then again convert it to a string in order to add new elements to the list.

I tried the following solution and it worked. But it seems redundant and probably not the best approach to fix this.

I have looked up this issue online, but There were no straight forward answers.

I would like to know why can’t json just accept an integer for a value? and is there a more efficient way to convert integer values to strings when added to a json object.

async function addItem(item) {
   ** const itemID = items.length ? (parseInt(items[items.length - 1].id) + 1).toString() : (1).toString();**
    const newAddedItem = {
      id: itemID,
      isChecked: false,
      item
    }
    const updatedListItems = [...items, newAddedItem];
    setItem(updatedListItems);

    //update the REST API
    const postOptions = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(newAddedItem)
    }
    const result = await apiRequest(API_URL, postOptions);
    if (result) setFetchError(result);
  }

Realm: How to reuse properties from a schema/class in a different schema?

Consider the following example –

Base.ts

import Realm from 'realm';

export type BaseId = Realm.BSON.ObjectId;

export interface BaseEntity {
    id?: BaseId;
    createdAt: string;
    updatedAt: string;
    syncDetails: SyncDetails;
}

export class BaseEntitySchema {
    _id!: Realm.BSON.ObjectId;

    createdAt!: Date;

    updatedAt!: Date;

    static schema: Realm.ObjectSchema = {
        name: 'BaseEntity',
        properties: {
            _id: 'objectId',
            createdAt: 'date',
            updatedAt: 'date',
        },
        primaryKey: '_id',
    };
}

Now, I want to create a new schema with the properties available in the above snippet.

System.ts

import Realm from ‘realm’;
import { BaseEntity, BaseEntitySchema } from ‘shared/offline-realm/schemas/base’;

export interface System extends BaseEntity {
name: string;
serialNumber: string;
locationId: string;
corporationId: string;
}

export class SystemSchema extends Realm.Object<SystemSchema> {
    name!: string;

    serialNumber!: string;

    locationId!: string;

    corporationId!: string;

    static schema: Realm.ObjectSchema = {
        name: 'System',
        properties: {
            ...BaseEntitySchema.schema.properties,
            name: 'string',
            serialNumber: 'string',
            locationId: 'string',
            corporationId: 'string',
        },
        primaryKey: '_id',
    };
}

I want the BaseEntity values to be available in SystemSchema by maybe inheriting/extending.

    _id!: Realm.BSON.ObjectId;

    createdAt!: Date;

    updatedAt!: Date;

I do not want to explicitly add it. I would rather like to extend it as I have multiple schemas which require the same properties and I would like typescript to recognise these values when I try to access it.

I tried doing something like –

export class BaseEntitySchema extends Realm.Object<BaseEntitySchema> {}

and then –

export class SystemSchema extends BaseEntitySchema

But, Realm’s useQuery would crash saying Unexpected arguments passed to useQuery when doing something like useQuery(SystemSchema)

BaseEntitySchema is a base schema which isn’t being used like a collection.

At present, I have to keep repeating the property values in each schema like so –

export class SystemSchema extends Realm.Object<SystemSchema> {
    name!: string;

    serialNumber!: string;

    locationId!: string;

    corporationId!: string;

    _id!: Realm.BSON.ObjectId;

    createdAt!: Date;

    updatedAt!: Date;

    static schema: Realm.ObjectSchema = {
        name: 'System',
        properties: {
            ...BaseEntitySchema.schema.properties,
            name: 'string',
            serialNumber: 'string',
            locationId: 'string',
            corporationId: 'string',
        },
        primaryKey: '_id',
    };
}

Are there any better ways to handle this issue? Thanks!