Create a search bot on discord

If you are using Discord.js and you want to integrate a search engine for your website in Discord, this can be inspiring you.

The scenario is the next :

  1. Generate a JSON file from the server and update it each hour using Cron and PHP.
    (you can also use Js server if you want).
  2. Read this generated file and get the data matching with the users key words .

JSON  file exemple: it containes the best monuments in Moscow and Saint Petersburg.

{
	"Moscow":[
		{
			"name":"Zamoskvorechie",
			"address":"Zamoskvorechie area, Moscou 115054"
		},
		{
			"name":"Red square",
			"address":"Krasnaya ploshchad, Moscou 109012"
		}
	],
	"Saint_petersburg":[
		{
			"name":"Isaac’s Cathedral",
			"address":"Isaakiyevskaya Sq., 4 Saint-Petersbourg"
		},
		{
			"name":"Ermitage",
			"address":"Palace Square, 2 Saint-Petersbourg"
		}
	]
}

Bot.js

const Discord = require('discord.js')
const request = require('request')
const each = require('each')
const embed = new Discord.RichEmbed()
const bot   = new Discord.Client()

bot.on('ready', ()=>{

	console.log(`[ # ] Your Discord Bot is ready!`) 

})

bot.on('message', (message)=> {

	if ( message.content.startsWith("!monument") ) {

		let url = "https://My_Json_file.com/data.json" //Your JSON URL
	 
		request( {url: url, json: true}, (error, response, data)=> {

		    if ( !error && response.statusCode === 200 ) {

		        let keyword = message.content.toLowerCase().replace(/\s|!monument/g, "")
		        let results = Object.keys(data).find( key => key.includes(keyword))

		        if ( keyword.length >2 && results !== undefined ) {
		        
				    each( data[results] ).call( (element, index, next) => {

					   	if (message.author.id !== bot.user.id && message.content){ 

							console.log(` Data : ${element}`) // debugging data

							message.channel.send(`${element.name}, address: ${element.address}`)

							setImmediate(next)

						}

					}).next( (err) => {
						console.log(err ? err.message : 'success!');
					})
					
					message.channel.send(items)

				}else{console.log(`${keyword} -> not found!`)}
		        
		    }
		})

	}

})

bot.login('___Your_Private_key___')

When the user tape !monument Saint petersburg OR !monument Saint Or !monument petersburg it will always return: Isaac’s Cathedral and Ermitage.
I wish that is inspired you. if you have any question leave a comment, I’ll try to answer ASAP.

Leave a Reply