Coder Social home page Coder Social logo

brh55 / botkit-discord Goto Github PK

View Code? Open in Web Editor NEW
37.0 4.0 7.0 1.17 MB

๐Ÿค–๐Ÿ‘พ A Botkit connector for Discord with support for text, voice, attachments, embedded messages, and more.

JavaScript 100.00%
botkit discord discord-botkit chatbots botkit-connector discord-js nodejs-discord botkit-discord

botkit-discord's Introduction

botkit-discord

๐Ÿค–๐Ÿ‘พ A Botkit connector for Discord with support for text, voice, attachments, embedded messages, and more.

Travis (.org) Coveralls branch npm badge

This Botkit platform connector is intended to be used for Discord. Underneath the hood, this connector is utilizing discord.js. Currently the connector supports the following features:

  • Text: DM Channel, Group DM Channel, Guild Text Message
  • Voice: Audio Playback and Joining Audio Channels
  • Embedded Messages: Visually rich messages
  • File attachments: Attach files to be downloaded by receiver
  • Various Notifications: Presences, Guild Member Add/Remove/Update, Guild Role Changes, Channel Add/Delete/Create

Example Gif

Install

Note: Minimum Node Requirement 8+, Recommended 10, and >=10.10.0 if you use audio.

$ npm install botkit-discord

Basic Usage

const BotkitDiscord = require('botkit-discord');
const config = {
    token: '**' // Discord bot token
}

const discordBot = BotkitDiscord(config);

discordBot.hears('hello','direct_message',(bot, message) => {
    bot.reply(message, 'how goes there :)!');
});

discordBot.hears('.*', 'direct_mention', (bot, message) => {
    bot.reply(message, 'leave me to be please.');
});

Advance Usage

const BotkitDiscord = require('botkit-discord');
const config = {
    token: '**' // Discord bot token
}

// Let's join the user's voice channel if we receive a "b!play"
// play a song and leave, get rating from user, and save result
// if no rating is stored, we can end conversation
discordBot.hears('b!play', 'ambient', async (bot, message) => {
	try {
		const connection = await bot.api.joinVoiceChannel();
		const dispatcher = connection.playFile('/Users/brh55/Music/funny.mp3');
		dispatcher.setVolume(0.5)
		dispatcher.on('end', () => {
			bot.createConversation(message, (err, convo) => {
				convo.addQuestion('How would rate that from a scale of 0 to 5?', (response, convo) => {
					const numberRating = response.text.match(/[0-5]/g);
					if (numberRating.length < 1) {
						convo.say('Uhh... not a valid rating, try again later!');
						convo.next();
					}
					convo.say('Oh wow! Thanks for letting me know!');
					db.save(message.member.id, numberRating[0]);
					convo.next();
				});
			});
			// Leave at the end of the channel
			bot.api.leaveVoiceChannel();
		});
	} catch (e) {
		// If the user is not in a voice channel, tell them to join one
		bot.reply('Dude are you in voice channel?');
	});
});

Configuration

Attribute Description Type
token Discord bot token String
replyToSelf Enable the bot to reply to itself, by default this is turned off, but there may be circumstances when you want to allow that. Boolean (Default: false)

Example Projects

  • Magic-8 Ball
  • Pokedex Audio Discord Bot - Allows users to search for Pokemon through a Pokedex bot and plays the audio description in a voice channel. Read the written tutorial
  • Glitch Examples
    • Starter Kit for Glitch - Quickly deploy a Discord bot with easy to follow step-by-step instructions
    • Gritty Bot - Using Giphy and sports API integration to provide fun and witty interactions
    • Bizbot - Uses Google Sheets to customize your bot, providing a easy way to allow people to contribute stuff to your bot without giving them access to the code

Refer to Botkit documentation to utilize all of the other Botkit features.

Events

When you want your bot to respond to particular events that may be relevant, you can use the .on method.

discordBot.on(EVENT_NAME, event => {
    // do stuff
});

Incoming Events

Event Description
ambient a channel the bot is in has a new message
direct_message the bot received a direct message from a user
direct_mention the bot was addressed directly in a channel ("@bot hello")
mention the bot was mentioned by someone in a message ("hello @bot")

Bot Activity Events

Event Description
disconnect Bot has disconnected or failed to login
ready Bot is connected

Discord.js Events

Along with standard events, all Discord.js events have been migrated for your use. Please refer to the docs for usage.

Server Greeting Referenced in Docs

discordBot.on('guildMemberAdd', member => {
  const channel = member.guild.channels.find(ch => ch.name === 'member-log');
  if (!channel) return;
  channel.send(`Welcome to the server, ${member}`);
});
  • "channelCreate"
  • "channelDelete"
  • "channelPinsUpdate"
  • "channelUpdate"
  • "clientUserGuildSettingsUpdate"
  • "clientUserSettingsUpdate"
  • "debug"
  • "disconnect"
  • "emojiCreate"
  • "emojiDelete"
  • "emojiUpdate"
  • "error"
  • "guildBanAdd"
  • "guildBanRemove"
  • "guildCreate"
  • "guildDelete"
  • "guildMemberAdd"
  • "guildMemberAvailable"
  • "guildMemberRemove"
  • "guildMembersChunk"
  • "guildMemberSpeaking"
  • "guildMemberUpdate"
  • "guildUnavailable"
  • "guildUpdate"
  • "message"
  • "messageDelete"
  • "messageDeleteBulk"
  • "messageReactionAdd"
  • "messageReactionRemove"
  • "messageReactionRemoveAll"
  • "messageUpdate"
  • "presenceUpdate"
  • "rateLimit"
  • "ready"
  • "reconnecting"
  • "resume"
  • "roleCreate"
  • "roleDelete"
  • "roleUpdate"
  • "typingStart"
  • "typingStop"
  • "userNoteUpdate"
  • "userUpdate"
  • "voiceStateUpdate"
  • "warn"

Audio/Voice Functionalities

This connector utilizes the built-in discord.js audio functionality, but requires additional steps to work properly:

  1. First install a desired audio enconder either node-opus or opusscript (discord.js recommends node-opus for performance reasons, but opusscript works for development purposes)
    • npm install node-opus - Requires >= 10.10.0 Node
    • npm install opusscript
  2. Next install FFMPEG, you can choose any of the following methods:
    1. (Mac) Install through homebrew: brew update && brew install ffmpeg
    2. (Linux) Install through apt update && apt install ffmpeg
    3. (All) Download and install the binaries manually through the FFMPEG site

For convenience, you'll be able to use the voice functionality if the sender of the message is already in a voice channel. This will be available in the .api properties of the bot object passed as a parameter in the event handler.

  • joinVoiceChannel()
  • leaveVoiceChannel()

Example Usage:

discordBot.hears('!audio', 'ambient', (bot, message) => {
    if (!bot.api.joinVoiceChannel) {
       return bot.reply(message, 'I would if you were in a voice channel!');
    }

    bot.api.joinVoiceChannel().then(connection => {
	// Absolute path to local mp3 file
        dispatcher = connection.playFile('/Users/jdoe1/projects/music-bot/assets/song.mp3')
	dispatcher.setVolume(0.5)
	dispatcher.on('end', () => {
		bot.api.leaveVoiceChannel();
		dispatcher.destroy();
	});
     }).catch(err => {
        console.log(`Failed to play audio: ${err}`);
     });
})

Embeds

To use embeds, it's preferred to use the Discord.js RichEmbed builder, discordBot.RichEmbed().

image

discordBot.hears('!rpg', ['direct_message', 'ambient'], (bot, message) => {
	const embed = new discordBot.RichEmbed()
	embed.setAuthor(
		"Quick RPG Stats",
		"https://rpglink.com/icon/here"
	);

	embed.addField("Power Level ๐Ÿ‘Š", "Equivalent to a Goblin Archer ๐Ÿน");
	embed.addField("Skills Acquired ๐Ÿฅ•", "๐Ÿน Archery, ๐Ÿณ Cooking");
	embed.setColor('GREEN');
	bot.reply(message, embed)
});

Atachments

It's recommended to use the attachment helper, discordBot.Attachment:

image

discordBot.hears('!file', ['direct_message', 'ambient'], (bot, message) => {
	const attachment = new discordBot.Attachment('./temp.js', "Awesome Script!")
	bot.reply(message, attachment)
});

Here is an example from the Pokedex Bot:

image

Sample Code:

const embed = new controller.RichEmbed();
embed.setAuthor(
	"Pokedex",
	"https://icon-library.net/images/pokedex-icon/pokedex-icon-15.jpg" // Grabbing this icon from icon-library
);
embed.setTitle(formatName(result.name));
embed.setDescription(`**No. ${result.id}** \n **${result.types[0].type.name}**`);
embed.setThumbnail(result.sprites.front_default);
embed.addField("Weight", formatWeight(result.weight));
embed.addField("Height", formatHeight(result.height));
embed.setColor("GREEN");
embed.addField("Description", result.description);

bot.reply(message, embed);

License

โ’ธ MIT Brandon Him / brh55

Please let me know if you plan on forking or would like professional support. Open-source is a hobby, but it would be great as a full-time gig :)

This wouldn't be possible without all the tremendous effort and contributors behind discord.js.

botkit-discord's People

Contributors

brh55 avatar dependabot[bot] avatar joemcmahon avatar yannzerookie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

botkit-discord's Issues

I don't understand what I'm doing wrong

It sounds stupid, but I can't do this, every time I try to download the Botkit-Discord npm "modules" it always fails, and I don't understand why. And that's it, I'm looking for assistance in using this or clarification on what I'm doing wrong, sorry for the inconvenience.

Area of Improvements in Docs

Would like to improve the documentation a little further, areas of improvement:

  • More examples and details with links to discord.js counterparts under each section
    • RichEmbed
    • Attachments
    • Text / DM (Need this still)
    • Voice
  • Add more real use examples, especially robust ones
  • Show case more examples/recipes for different events available to listen on

Discord.js Update

Was wondering if there was any plans to update Discord.js to version 12. Botkit is on 11.

Occasional exceptions in isMention when message.text is uninitialized

Symptom: entries in the log similar to the following:

An error occurred in the categorize middleware:  TypeError: Cannot read property 'indexOf' of undefined
    at isMention (/home/jmcmahon/spud/node_modules/botkit-discord/middleware/categorize.js:1:52)
    at categorize (/home/jmcmahon/spud/node_modules/botkit-discord/middleware/categorize.js:21:6)
    at Ware.module.exports.handler (/home/jmcmahon/spud/node_modules/botkit-discord/middleware/categorize.js:33:2)
    at Ware.<anonymous> (/home/jmcmahon/spud/node_modules/wrap-fn/index.js:45:19)
    at next (/home/jmcmahon/spud/node_modules/ware/lib/index.js:85:20)
    at Ware.run (/home/jmcmahon/spud/node_modules/ware/lib/index.js:88:3)
    at Object.Botkit.botkit.categorize (/home/jmcmahon/spud/node_modules/botkit/lib/CoreBot.js:118:38)
    at /home/jmcmahon/spud/node_modules/botkit/lib/CoreBot.js:112:20
    at next (/home/jmcmahon/spud/node_modules/ware/lib/index.js:82:27)
    at /home/jmcmahon/spud/node_modules/wrap-fn/index.js:121:18

PR #21 fixes this.

replies to itself

The bot replies to messages that it writes
example

const discordBot = BotkitDiscord(config);

discordBot.hears('hello','direct_message',(bot, message) => {
    bot.reply(message, 'hello');
});

if you write "hello" to it it will just say hello over and over.
also the receive middlewares also get called for messages the bot sends

Bug: cannot reply to direct_message messages

Hello,

First of all, I'd like to tell you how much happy I was to find someone putting together BotKit and Discord. I am very excited!

I started playing with your code, and I think I spotted something fishy in bot.js, that makes the bot.reply method fail for messages of type direct_message. Consider this, from lines 27 to 36:

		if (src.type === 'direct_mention') {
			message.to = src.author.id;
		}

		if (
			src.type === 'mention' ||
			src.type === 'direct_mention'	
		) {
			message.to = src.channelId;
		}

I believe the second test of src.type === 'direct_mention' is wrong, and should be:

		if (
			src.type === 'mention' ||
			src.type === 'direct_message'	
		) {...

Otherwise you won't be able to reply to messages of type direct_message.

Do you welcome Pull Requests? Be advised that this is my first Node.js project - you have been warned ;)

Keep up the great work!

Abstract a custom event for MOTD / New Comers

Currently, there isn't an easy way to trigger events for new users joining the guild / server (other than the discord.js way). But because this is so commonly used, I think this is important to add an abstraction which includes some basic APIs and use cases.

For example, moving users to a private room, and allowing them to accept Terms of Agreements.

Migration to Discord.js

While the currently Discord library is light-weight, Discord.js is constantly being updated and supports rich-presences which would be ideal for a discord bot.

Project does not install anymore (erlpack issue), need update - help!

When I npm install, I am getting an error about erlpack. I believe this is because the project depends on a forked version of discord/erlpack : hammerandchisel/erlpack that is probably not up-to-date. Also see discord/erlpack#34

$ npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! Found: [email protected]
npm ERR! node_modules/erlpack
npm ERR!   erlpack@"github:hammerandchisel/erlpack" from [email protected]
npm ERR!   node_modules/botkit-discord
npm ERR!     botkit-discord@"^0.1.3" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional erlpack@"discordapp/erlpack" from [email protected]
npm ERR! node_modules/discord.js
npm ERR!   discord.js@"^11.4.2" from [email protected]
npm ERR!   node_modules/botkit-discord
npm ERR!     botkit-discord@"^0.1.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/yann/.npm/eresolve-report.txt for a full report.

Looking for Maintainers

I'm busy with new things in my life, and would love to assign a few maintainers to the project. Please let me know if you are interested.

[installation] Minimal version of Node/npm ? Failures when installing

Hi,
What is the minimal version required of NodeJS and npm? I am using the LTS 10.16.0 version of Node (npm 6.9.0) and I get tons of problems with ffmpeg when doing:
npm install git+ssh://[email protected]/brh55/botkit-discord.git:

npm WARN deprecated [email protected]: ffmpeg-binaries is no longer being maintained. use ffmpeg-static, or just install ffmpeg
npm WARN deprecated [email protected]: New code is available at github.com/uNetworking/uWebSockets.js
npm WARN deprecated [email protected]: use node-fetch instead

> [email protected] install /var/www/lsd/bot/node_modules/lzma-native
> node-pre-gyp install --fallback-to-build && node node_modules/rimraf/bin.js build

[lzma-native] Success: "/var/www/lsd/bot/node_modules/lzma-native/binding-v3.0.8-node-v64-linux-x64/lzma_native.node" is installed via remote

> [email protected] install /var/www/lsd/bot/node_modules/erlpack
> node-gyp rebuild

make: Entering directory '/var/www/lsd/bot/node_modules/erlpack/build'
  CC(target) Release/obj.target/zlib/vendor/zlib/adler32.o
  CC(target) Release/obj.target/zlib/vendor/zlib/compress.o
  CC(target) Release/obj.target/zlib/vendor/zlib/crc32.o
  CC(target) Release/obj.target/zlib/vendor/zlib/deflate.o
  CC(target) Release/obj.target/zlib/vendor/zlib/gzclose.o
  CC(target) Release/obj.target/zlib/vendor/zlib/gzlib.o
  CC(target) Release/obj.target/zlib/vendor/zlib/gzread.o
  CC(target) Release/obj.target/zlib/vendor/zlib/gzwrite.o
  CC(target) Release/obj.target/zlib/vendor/zlib/infback.o
  CC(target) Release/obj.target/zlib/vendor/zlib/inffast.o
  CC(target) Release/obj.target/zlib/vendor/zlib/inflate.o
  CC(target) Release/obj.target/zlib/vendor/zlib/inftrees.o
  CC(target) Release/obj.target/zlib/vendor/zlib/trees.o
  CC(target) Release/obj.target/zlib/vendor/zlib/uncompr.o
  CC(target) Release/obj.target/zlib/vendor/zlib/zutil.o
  AR(target) Release/obj.target/vendor/zlib.a
  COPY Release/zlib.a
  CXX(target) Release/obj.target/erlpack/js/erlpack.o
In file included from ../js/erlpack.cc:2:0:
../js/encoder.h: In member function 'int Encoder::pack(v8::Local<v8::Value>, int)':
../js/encoder.h:58:44: warning: 'int32_t v8::Value::Int32Value() const' is deprecated (declared at /home/deploy/.node-gyp/10.16.0/include/node/v8.h:2478): Use maybe version [-Wdeprecated-declarations]
             int number = value->Int32Value();
                                            ^
../js/encoder.h:67:68: warning: 'uint32_t v8::Value::Uint32Value() const' is deprecated (declared at /home/deploy/.node-gyp/10.16.0/include/node/v8.h:2477): Use maybe version [-Wdeprecated-declarations]
                 auto uNum = (unsigned long long)value->Uint32Value();
                                                                    ^
../js/encoder.h:72:49: warning: 'double v8::Value::NumberValue() const' is deprecated (declared at /home/deploy/.node-gyp/10.16.0/include/node/v8.h:2475): Use maybe version [-Wdeprecated-declarations]
             double decimal = value->NumberValue();
                                                 ^
  SOLINK_MODULE(target) Release/obj.target/erlpack.node
  COPY Release/erlpack.node
make: Leaving directory '/var/www/lsd/bot/node_modules/erlpack/build'

> [email protected] install /var/www/lsd/bot/node_modules/ffmpeg-binaries
> node install

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: getaddrinfo ENOTFOUND johnvansickle.com johnvansickle.com:443
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Emitted 'error' event at:
    at TLSSocket.socketErrorListener (_http_client.js:392:9)
    at TLSSocket.emit (events.js:198:13)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
npm WARN [email protected] requires a peer of bufferutil@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of erlpack@discordapp/erlpack but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of libsodium-wrappers@^0.7.3 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of node-opus@^0.2.7 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of sodium@^2.0.3 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @discordjs/uws@^10.149.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node install`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/deploy/.npm/_logs/2019-06-01T11_53_57_020Z-debug.log

Optional FFMPEG Binary download

Allow users to download their own ffmpeg binary dependency. This needs some further testing, but we may be able to accomplish this with through peer dependencies. This will require some conditionals to raise an exception when it's not present, but users intend to use the voice features.

BOT status

How can i set my bot status?
Can I use (Bot.user.setStatus) and (Bot.user.setPresence) which are same as discord.js in botkit-discord ?

'ambient' not working

using the ambient setting on .hears() produces no results.

demo code (adapted from the glitch starterkit)

  controller.hears('!test', ['ambient'], (bot, message) => {
    
    let response = "test success!"
        bot.reply(message, response);

  });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.