Come mostrare le informazioni da un file (testo) in tempo reale sul mio discord bot

Aug 24 2020

Sto creando un discord bot per un SAMP (un server multiplayer online). Quindi voglio aggiungere un cmd al mio dicord bot che prende il testo da un documento di testo e lo invia in un canale del server discord. Quindi, la cosa importante è che..il documento di testo è il registro del server di gioco (il che significa che continuerà ad essere aggiornato ogni secondo come accade nel gioco) quindi ogni cosa che accade nel gioco verrà scritta automaticamente all'interno del registro. Ho il file di testo e non ho bisogno di prendermene cura perché fa da solo. Tutto ciò di cui ho bisogno è un cmd che mostri le cose esatte che continuano ad arrivare nel documento di testo in uno dei canali del server Discord (un aggiornamento in tempo reale. Il bot continuerà a postare tutto ciò che viene fuori in quel documento). Non so fare un comando del genere che ottiene informazioni dal documento e senza alcuna modifica, continua a postare nel canale del server una volta utilizzato il comando. (Il documento di testo può essere fornito, ma tieni presente che continuerà ad aggiornarsi ogni secondo quando il gioco è attivo). Quindi, spero che qualcuno possa inventare un tale comando.

Il bot è in javascript, quindi ofc il cmd dovrebbe essere in js (discord.js, node.js)

Fornirò il documento di testo se necessario. La mia mente dice che è piuttosto semplice, ma non so come creare un cmd del genere. Scusa e grazie <3

Il mio codice (quello che ho fatto fino ad ora) fornito come da richiesta -

client.on('message', message => {
  const help = new Discord.MessageEmbed()
    .setColor('#f0000')
    .setTitle('INFORMANT BOT HELP')
  .setAuthor('Informant')
  .setDescription('***Hey there! Given below are the list of available `commands`.More interesting commands will be added in the `future`.***')
 .addField('``!info``-',"To see the Infomante Bot Info")
 .addField('``!gangs``-',"To all see the the current gangs in HZG and their leader(s)")
 .addField('``!factions``-',"To see all the current factions and their leader(s)")
 .addField('``!guides``-',"Useful guides for new player. The guides are handpicked from HZG forums help center.")
 .addField('``!quiz``-',"HZG quiz (Only a few questions have been added and more will be coming soon.")
 .addField("``!gangsug``-", "Suggests a cool gang for you according to your interests. (from the current gang, some are selected | This cmd will be updated with more gangs soon!))")
 .addField('``!helpme``-',"Provides some basic help regarding HZG. (This cmd will be updated soon)")

  if (message.content === `${prefix}help`) { message.channel.send(help); } }); client.on('message', message => { const sug1 = new Discord.MessageEmbed() .setColor('#f0000') .setTitle('HORIZON GAMING - GANG SUGGESTIONS') .setAuthor('Informant') .setDescription('Hey there! Lets get it started. Are you a person who loves to roleplay? Do you prefer roleplay rather than heavy gun fights? If so, then Sentinel is the best gang for you! The Sentinel is a gang who runs a casino in LS.The like to keep a low profile and mostly engage in RP than regular gun fights like some other gangs. ') .setImage('https://cdn.discordapp.com/attachments/744143472503554072/746584514754773112/Untitled_35.png') .setFooter(' The bot is in the development stage! More gangs and info will be added to this cmd soon! ') const sug2 = new Discord.MessageEmbed() .setColor('#f0000') .setTitle('HORIZON GAMING - GANG SUGGESTIONS') .setAuthor('Informant') .setDescription('Hey there! As you replied, if you are a person who likes to engage in heavy fights more than `RP`, but still want to have some RP fun, then we got gangs like Gsteet,Black Hand Traids and many more gangs! Make sure you check em out ICly! ') .setImage('https://cdn.discordapp.com/attachments/744143472503554072/747009277129916436/images_9.jpg') .setFooter('The bot is in the development stage! More gangs and info will be added to this cmd soon! ') const sug3 = new Discord.MessageEmbed() .setColor('#f0000') .setTitle('HORIZON GAMING - GANG SUGGESTIONS') .setAuthor('Informant BHT') .setDescription('The Black Hand Traids, HQ - Verdant Bluffs. - ') .setImage('https://cdn.discordapp.com/attachments/744143472503554072/746623452223635526/Untitled_36.png') .setFooter('The bot is in the development stage! More gangs and info will be added to this cmd soon! ') const sug4 = new Discord.MessageEmbed() .setColor('#f0000') .setTitle('HORIZON GAMING - GANG SUGGESTIONS') .setAuthor('Informant Yakuza') .setDescription('Yakuza Organisation. HQ - Temple, Good with both RP and minimal gun fights. - ') .setImage('https://cdn.discordapp.com/attachments/744143472503554072/747019287402774528/959758414.png') const sug5 = new Discord.MessageEmbed() .setColor('#f0000') .setTitle('HORIZON GAMING - GANG SUGGESTIONS') .setAuthor('Informant Golden Palm Crips') .setDescription('Golden Palm Crips. Good with fights and basic RP. - ') .setImage('https://i.imgur.com/wqyDp9o.png') if (message.content === `${prefix}gangsug`) {
    
            
                    message.reply('Hey there! We send the suggestions based on your choise, so please choose what you prefer from the given options-.\n'
                            + 'Confirm with `rp`(roleplay) or with `fight` or `both`.');

                    message.channel.awaitMessages(m => m.author.id == message.author.id,
                            {max: 1, time: 40000}).then(collected => {
                                   
                                    if (collected.first().content.toLowerCase() == 'rp') {
                                            message.reply(sug1);
                                            message.reply(sug4)
                                  
                                    }
                                   if (collected.first().content.toLowerCase() == 'fight'){
                                       message.reply(sug2);
                                       message.reply(sug3)
                                       message.reply(sug5)
                                      }
                                  if (collected.first().content.toLowerCase() == 'both'){
                                    message.reply(sug1);
                                    message.reply(sug3)
                                    message.reply(sug2)
                                  }                                    
                            }).catch(() => {
                                    message.channel.send('request canceled due to no reply.');
                            });
                          }
                        })
                 
  
                        client.on('message', message => {
                          const hzgdonation = new Discord.MessageEmbed()
                          .setColor('#f0000')
                          .setTitle('HORIZON GAMING - SUPPORT!')
                          .setAuthor('Informant BOT')
                          .setDescription('***Check out the donations perks mate!***')
                          .addField ("``CHECK OUT THE DONATION PERKS!``-", "https://www.hzgaming.net/fullpage.php?id=donate")
                          .addField ("``Make sure you fill out this form after donating!`` -", "https://forums.hzgaming.net/forms.php?do=form&fid=16")
                          .setImage('https://cdn.discordapp.com/attachments/744143472503554072/747320822405791905/Untitled_39.png') 
                          const commhelp = new Discord.MessageEmbed()
                          .setColor('#f0000')
                          .setTitle('HORIZON GAMING - SUPPORT!')
                          .setAuthor('Informant BOT')
                          .setDescription('**Feel free to post any help request in `community help` - forums**')
                          .addField ("``COMMUNITY HELP QUESTION FORM``-", "https://forums.hzgaming.net/forms.php?do=form&fid=9")
                           
                          const hzforums = new Discord.MessageEmbed()
                          .setColor('#f0000')
                          .setTitle('HORIZON GAMING - SUPPORT!')
                          .setAuthor('Informant BOT')
                          .setDescription('**Check out HZG Forums using the link below!**')
                          .addField ("`HZG FORUMS`-", "https://forums.hzgaming.net/forum.php")
                          const hzcomp = new Discord.MessageEmbed()
                          .setColor('#f0000')
                          .setTitle('HORIZON GAMING - SUPPORT!')
                          .setAuthor('Informant BOT')
                          .setDescription('**Complaint section and player complaint link are given below!**')
                          .addField ("`Complaint section on forums`-", "https://forums.hzgaming.net/forumdisplay.php/7-Complaints")
                          .addField ("`Player complaint form`-", "https://forums.hzgaming.net/forms.php?do=form&fid=4")
               
                          if (message.content === `${prefix}helpme`) {
                          
                                  
                                          message.reply('Hey there! your help support has arrived! Choose from the given help options and reply.-.\n'
                                                  + 'Confirm with `donation`, `ig questions`, `complaints`or `forums`.');
                      
                                          message.channel.awaitMessages(m => m.author.id == message.author.id,
                                                  {max: 1, time: 40000}).then(collected => {
                                                         
                                                          if (collected.first().content.toLowerCase() == 'donation') {
                                                                  message.reply('**Hey there! You can donate for HZG and get many perks `in game`,`forums` and `HZG discord`.There are different perks for `Ruby donator`, `Saphire donator` and ` Diamond Donator`. Moreover you can donate to recive some induvitual ig/forum items like - `cars`,`house`, `business` and more! Check out all the perks and price using the `link` provided!**');
                                                                  message.reply(hzgdonation)
                                                        
                                                          }
                                                         if (collected.first().content.toLowerCase() == 'ig questions'){
                                                             message.reply('***Hey there! You can always feel free to use `/newb` in game to ask any server related questions! There is also a section called `community help center` on HZG forums where you can ask any question. Using `/gethelp` in game also serves the same purpose.We will try to have a section in this bot where you can ask questions `soon`! You can use `!guides` to see a list of guides that may come handy.***');
                                                             message.reply(commhelp)
                                                          
                                                            }
                                                        if (collected.first().content.toLowerCase() == 'forums'){
                                                          message.reply('Hey mate! There are many things you can do in HZG forums like, general discussions,ask for help,debates,apply for factions, apply for creating a gang and much more! Make sure you check it out!');
                                                          message.reply(hzforums)

                                                          
                                                        }    
                                                        if (collected.first().content.toLowerCase() == 'complaints'){
                                                          message.reply('Hey there! If you saw any player breaking server rules, you can always post a player complaint against that player! (There are even more like - Hacking complaints, Scam complaints)It may take some time for admins to review your complaint once posted. Make sure you got some evidence (prefer a video) and post a complaint using the link provided! ');
                                                          message.reply(hzcomp)
                                                          
                                                          
                                                        }                                                        
                                                  }).catch(() => {
                                                          message.channel.send('request canceled after 40 seconds.');
                                                  });
                                                }
                                              })
                                      


client.login(token);

Risposte

1 Anton Aug 25 2020 at 00:50

Nota: questo è più un commento che una risposta.

Sembra che tu non abbia provato a cercare su Google il problema. Fammi google per te.

Diamo un'occhiata a queste ricerche:

  • Come posso inviare un messaggio ogni giorno a un'ora specifica?
  • Invia messaggio programmato

Puoi google più esempi con discord.js send message at specific timela stringa di ricerca in Google.

L'idea è di inviare un messaggio non come risposta alla richiesta dell'utente, ma in un momento specifico (ogni 1 secondo, ad esempio).

Ci sono diversi modi per farlo. I più popolari sono: crone setTimeout.

Cron (dalla prima risposta)

const cron = require('cron');

client.on('message', ...); // You don't need to add anything to the message event listener

let scheduledMessage = new cron.CronJob('00 30 10 * * *', () => {
  // This runs every day at 10:30:00, you can do anything you want
  let channel = yourGuild.channels.get('id');
  channel.send(getLogs()); // <----- here we need a correct message with our logs
});

// When you want to start it, use:
scheduledMessage.start()
// You could also make a command to pause and resume the job

Qui creiamo un cronlavoro da eseguire ogni X minuti (quindi 1 corsa in un minuto è la velocità massima, ma non sono uno specialista in cron, ci sono molti consigli su Google su come eseguire ogni secondo).

setTimeout (dalla seconda risposta)

Solo un normale timeout JS:

client.on('ready', () => {
  setTimeout(function(){
    sendMessage(getLogs()); // <----- again, here we need a correct message with our logs
  }, 1000); // 1000 = every second
})

Cosa inviare?

L'unica domanda ora è come leggere il registro e inviare solo nuove righe da esso.

In questo momento non so come farlo in modo efficace, ci penserò più tardi. Ma per l'inizio puoi cercare su Google node js read file lines into array.

Questa è una delle prime ricerche :

var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");

Quindi la tua getLogs()funzione leggerà il file come array di stringhe e convertirà ogni stringa in Discord.MessageEmbed(), quindi la invierà al canale.

PS Ovviamente non scriverò tutto il codice per te :) ma spero che questo sia sufficiente per iniziare. In caso contrario, sentiti libero di commentare.