What steps should I take to enable a clock plugin for my Discord Bot using the Discordeno framework?

I recently attempted to develop a plugin for a Discord bot utilizing the Discordeno Library. The goal of this plugin was to automatically update the name of a Voice channel to display the local time on the computer every minute. However, I encountered an issue where the channel would only be renamed when the bot started and would not update correctly thereafter.

Here is a snippet of the code structure:

export async function clock(client: BotWithCache<Bot>) {
    const d = new Date()
    const conf = config.plugins.clockChannel
    function clockEmoji(date: Date) {
        // Code for converting time to emojis
    }
    // Additional code for updating channel information
}

The purpose of this code was to fetch the current time from the computer running the bot and continuously update the channel name accordingly. This feature was intended to help members track time in case I am unavailable online. However, instead of updating every minute as planned, the channel was only renamed once at the start. Despite troubleshooting efforts, the channel continued to display the same time repeatedly instead of reflecting the accurate time.

Answer №1

The way your code is currently structured has a minor logical flaw. At present, the channel name is calculated once and then continuously set to that same value. It would be more appropriate to update it each time the interval runs.

Here's how the corrected code should appear:

export async function clock(client: BotWithCache<Bot>) {
    const conf = config.plugins.clockChannel
    function clockEmoji(date: Date) {
        const hour = date.toLocaleTimeString('en-US',
            { hour12: true, hour: 'numeric', timeZone: conf.timezone }
        ).replace(/\s(AM|PM)$/, '');
        const numToEmoji = {
            '12': '🕛',
            '0': '🕛',
            '1': '🕐',
            '2': '🕑',
            '3': '🕒',
            '4': '🕓',
            '5': '🕔',
            '6': '🕕',
            '7': '🕖',
            '8': '🕗',
            '9': '🕘',
            '10': '🕙',
            '11': '🕚'
        }
        // deno-lint-ignore no-explicit-any
        return (numToEmoji as any)[hour] as string
    }

    if (conf.channelID == "0") {
        const { id } = await client.helpers.createChannel(config.guildID, {
            name: chName,
            parentId: conf.categoryID == "0" ? undefined : conf.categoryID,
            type: ChannelTypes.GuildVoice,
            permissionOverwrites: [{
                deny: ["CONNECT"],
                id: BigInt(config.guildID),
                type: OverwriteTypes.Role
            }]
        })
        config.plugins.clockChannel.channelID = String(id);
        const data = JSON.stringify(config, null, 4);
        Deno.writeTextFileSync("config.json", data);
    }

    const updateChannel = () => {
        const d = new Date();
        const c = dateToString(d, {
            clockOnly: true,
            includesTimezone: true,
            timezone: conf.timezone
        });
        const chName = conf.channelName!.replace("$TIME", c).replace("$EMOJI", clockEmoji(d));
    
        editChannel(client, BigInt(conf.channelID!), {
            name: chName
        });
    }

    updateChannel();

    const interval = 1000 * 60 * (!conf.intervalInMinutes ? 10: conf.intervalInMinutes);

    setInterval(() => {
        updateChannel();
    }, interval)
}

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

Utilize devextreme for uploading files

Currently, I am trying to implement an upload document feature using Dev-Extreme, but I keep encountering an error https://i.sstatic.net/dLxWx.png onFileUpload(event){ this.file = event.target.files[0] } <dxi-column [showInColumnChooser]="fa ...

utilize TypeScript to iterate through an array in a JSON object

How can I loop through the subjects array in a JSON response? JSON Response: { "$id": "1", "Council_ID": 116, "number": "67", "subjects": [ { "$id": "2", "subjectCode": "67", "type": 4, ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

Invoke the method in customButton component of fullcalendar

I've integrated a custom button into my fullcalendar: ngOnInit() { this.calendarOptions = { customButtons: { custom1: { text: 'Add event', click() { this.openModal(); } } }, height: 600, editable: t ...

Defining a type with limited knowledge: if you only have one key in the object

Attempting to establish a type for an object Consider the following object structure: { a: 123, b: "hello", c: { d:"world" } } The keys present in the object are unknown. To define its type, I would use Record<st ...

How to use Angular pipes to format dates as Long Dates in the template

Suppose I have a date input such as 2022-04-02T00:00:00. When I utilize {{data?.dateStarted | date:'MM/dd/YYYY'}}, the result will be 04/02/2022. But how can we transform it into a Long Date format like April 2, 2022? Does anyone have any sugges ...

ionChange - only detect changes made in the view and update the model in Ionic 2

In my Ionic 2 application, I have a feature that allows users to schedule notifications as reminders. The requirements for this feature are as follows: Upon entering the reminder page, it should check if there is a saved reminder. If a reminder is saved ...

Steps for setting the keys of a map as a priority when initializing a state variable in Typescript for a React component

I am working with a state variable that connects a string username to a UserData object. Initially, the usernames are stored in the string array 'users'. Is there a method to assign the initial state of 'userDataMap' with the keys fro ...

What is a simple method to convert TypeScript to JavaScript?

Is it possible to eliminate TypeScript-specific keywords from a JavaScript file without using the tsc command, while ensuring that the file remains readable by humans and maintains JSX syntax? ...

The issue arises when TypeScript is unable to accurately infer the type as not being undefined following a type guard condition using

The following code snippet illustrates that in the else statement, it is evident that b cannot be undefined (a||b returns truthy and since a is falsy, b must be truthy). Why does Typescript show the error 'b' is possibly 'undefined', a ...

Error encountered during Angular production build: Attempting to assign value to a reference or variable not possible

Encountering issues building the production version of my Angular app. The IDE console only displays this message: ERROR in Cannot assign to a reference or variable! To successfully build, I need to include these options: --aot=false --buildOptimizer ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

"Learn the process of integrating Javascript files from the Angular assets folder into a specific Angular component or module (such as Angular 2, 4,

I have custom1.js, custom2.js, and custom3.js JavaScript files that I need to load into Angular components component1, component2, and component3 respectively. Instead of adding these files to the index.html globally, I want to load them specifically for e ...

Issues arise when attempting to store data into an array with the assistance of FileReader

I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor. Here is the API call I am makin ...

Learn the method for triggering events with a strongly-typed payload in Vue 3 Composition API and TypeScript

I'm currently exploring Vue 3 Composition API along with TypeScript, particularly focusing on emitting events with a strictly typed payload. There's an example provided below, but I'm unsure if it's the most effective way to achieve t ...

I need a way to call a function in my Typescript code that will update the total value

I am trying to update my total automatically when the quantity or price changes, but so far nothing is happening. The products in question are as follows: this.products = this.ps.getProduct(); this.form= this.fb.group({ 'total': ...

Is there a way to apply Validators.required just once for all required form fields in a Reactive Form?

Latest version of Angular is 4.4.3. In Reactive Form, you can use Validators.required for each form field as shown below: this.loginForm = this.fb.group({ firstName: ['', [Validators.required, Validators.maxLength(55)]], ...

Using Angular and TypeScript: A guide to binding an ngModel to a variable key within an object

I have an object called WeeklyDriver with various keys. My goal is to iterate over an array of objects containing WeeklyDriver instances (referred to as drivers in my code), and then loop through a specific set of keys belonging to the WeeklyDriver object: ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

Having trouble retrieving the "history" from props?

I am working with a React component. import * as React from 'react'; import { Component } from 'react'; import { FormControl, Button } from 'react-bootstrap'; type Props = { history: any[]; }; // Question on defining Prop ...