@Shiro_Shihi

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Discordのbotをよりよいプログラムにしたい。

解決したいこと

よりよいプログラムにしたい。

botの内容:地震速報を伝えるbot

Discord.jsでbotを制作しています。
よりよいプログラムにするためにはどのようにすればよいでしょうか。
また、間違っている点等ありましたらご教授ください。

const Discord = require('discord.js');
const fetch = require('node-fetch');
const { createCanvas, loadImage } = require('canvas');
const { channelLink, ChannelType } = require('discord.js');

const webhookUrl = 'WEBHOOK_URL'; //Replase with your webhook URL
const earthquakeApiUrl = 'http://www.jma.go.jp/bosai/quake/data/list.json';
const regionApiUrl = 'http://www.jma.go.jp/bosai/common/const/area.json';
const canvasWidth = 800;
const canvasHeight = 600;
const intensityColors = [
    '#00ff00', //Intensity 1
    '#ffff00', //Intensity 2
    '#ffa000', //Intensity 3
    '#ff0000', //Intensity 4
    '#800080', //Intensity 5-
    '#800080', //Intensity 5+
    '#800080', //Intensity 6-
    '#800080', //Intensity 6+
    '#800080', //Intensity 7
];

//Initialize Discord client
const client = new Discord.Client();

//Fetch region data
let regionData;
fetch(regionApiUrl)
    .then(res => res.json())
    .then(data => {
        regionData = data;
    });

//Create canvas and draw regions
const canvas = createCanvas(canvasWidth, canvasHeight);
const context = canvas.getContext('2d');
context.fillStyle = '#ffffff';
context.fillRect(0, 0, canvasWidth, canvasHeight);
context.font = 'bold 20px sans-serif';
context.textAlign = 'center';
context.textBaseline = 'middle';
for (let i = 0; i < regionData.length; i++) {
    const region = regionData[i];
    context.fillStyle = intensityColors[region.color - 1] || '#000000';
    context.fillRect(region.x, region.y, region.width, region.height);
    context.fillStyle = '#000000';
    context.fillText(region.name, region.x + region.width / 2, region.y + region.height / 2);
}

//Draw text at the bottom of the canvas
context.font = 'bold 12px sans-serif';
context.textAlign = 'right';
context.fillStyle = '#000000';
context.fillText('Data by JMA', canvasWidth - 5, canvasHeight - 15);
context.fillText('©Shihiro 2023 All Right Reserved.', canvasWidth - 5, canvasHeight - 5);

//Intialize last earthquake data
let lastEarthquakeData = [];

//Fetch earthquake data every 500ms
setInterval(() => {
    fetch(earthquakeApiUrl)
    .then(res => res.json())
    .then(data => {
        //Check if there is a new earthquake
        if(JSON.stringify(data) !== JSON.stringify(lastEarthquakeData)){
            lastEarthquakeData = data;

            //format earthquake data
            const massage = '**地震情報**\n${data[0].time.slice(0, 16)}に発生\nマグニチュード : ${data[0].magnitude}\n深さ : ${data[0].depth}km\n最大震度 : ${data[0].maxIntensity}';

            //Create earthquake map image
            const image = new Discord.MassageAttachment(canvas.toBuffer(), 'earthquake.png');

            //Draw earthquake epicenter on canvas
            const epicenter = data[0].epicenter;
            context.beginPath();
            context.arc(epicenter.x, epicenter.y,5, 0, 2 * Math.PI);
            context.fillStyle = '#ff0000';
            context.fill();

            //Initialize voice client
            const voiceClient = new Discord.VoiceConnection(client.guilds.cache.first().client, {selfDeaf: true});

            //Initialize voice channel
            let voiceChannel;

            //Listen for massage event
            client.on('message', massage => {
                if(messageLink.content.startsWith('!setchannel')){
                    //Get voixe channel from massage
                    const channelName = massage.content.slice(12);
                    voiceChannel = message.guild.channels.cache.find(channel => channel.name === channelName && ChannelType === 'voice');
                    if(!voiceChannel){
                        massage.reply('Voice channel ${channelName} not found.');
                    }else{
                        massage.reply('Voice channel ${channelName} set.');
                    }
                }
            });

            //Function to play emergency sound
            async function playEmergencySound(){
                try{
                    //Join voice channel
                    await voiceClient.connect();
                    await voiceChannel.join();

                    //Play emergency sound 3 times
                    for(let i = 0; i < 3; i++){
                        const dispatcher = voiceChannel.play('emergency.mp3');
                        await new Promise(resolve => dispatcher.on('finish', resolve));
                    }

                    //Disconnect from voice channel
                    voiceChannel.leave();
                    voiceClient.disconnect();
                }catch(error){
                    console.error(error);
                }
            }
            
            //Check for earthquakes with intensity 4 or higher
            if(data[0].maxIntensity >= 4){
                //Play emergency sound
                if(voiceChannel){
                    playEmergencySound();
                }else{
                    console.log('Voice channel not set.')
                }
            }

            //Send massage and image to Discord
            const webhook = new Discord.WebhookClient({ url: webhookUrl });
            webhook.send(massage, {files: [image] });

            //Check if the earthquake has an intensity of 4 or higher
            if(data[0].maxIntensity >= 4){
                const tunamiQarningMessage = '津波から身を守るため、海岸または川のそばから離れてください'
                webhook.send('@everyone' + tunamiQarningMessage);
            }
        }
    });
}, 500);

//Log in to Discord
client.login('BOT_TOKEN'); //Replase with your bot token```
0 likes

2Answer

Comments

  1. @Shiro_Shihi

    Questioner

    付け加えた方がよいものや、より使いやすくしたいです。
    わかりにくい内容で申し訳ございません。

Comments

  1. @Shiro_Shihi

    Questioner

    具体的にはどのようにすればよいですか?

Your answer might help someone💌