Skip to content

Commit

Permalink
True 5.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
metagn committed Dec 7, 2017
1 parent 68c949e commit c095186
Show file tree
Hide file tree
Showing 20 changed files with 269 additions and 205 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*.iml
/builds/
/output/
*.bat
*.ps1
/gradlew
/.gradle/
/build/
Expand Down
12 changes: 9 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ apply plugin: 'maven'
apply plugin: 'idea'
apply plugin: 'application'

version = "5.0.0"
group = "hlaaftana"
archivesBaseName = "DiscordG"
mainClassName = "hlaaftana.discordg.DSLMain"

jar {
Expand All @@ -25,6 +28,9 @@ dependencies {
compile 'org.abstractj.kalium:kalium:0.4.0'*/
}

version = "5.0.0"
group = "com.github.hlaaftana"
archivesBaseName = "DiscordG"
groovydoc {
docTitle = "DiscordG ${this.version} Documentation"
windowTitle = "DiscordG Documentation"
destinationDir = new File("out/doc")
classpath = sourceSets.main.compileClasspath
}
6 changes: 3 additions & 3 deletions examples/ChannelListener.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ import hlaaftana.discordg.*

client = DiscordG.withToken args[0]

client.listener('channel') {
client.listen('channel') {
if (channel.text && !channel.private)
channel.sendMessage("Hello there, new channel!")
}

client.listener('channel deleted') {
client.listen('channel deleted') {
if (guild) guild.sendMessage("Looks like $channel.type channel \"$channel.name\" was deleted.")
}

client.listener('channel changed') {
client.listen('channel changed') {
if (channel.text)
channel.sendMessage("Seems this channel changed. I like it.")
else guild.sendMessage("Seems $channel.mention changed. I like it.")
Expand Down
6 changes: 3 additions & 3 deletions examples/MemberListener.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import hlaaftana.discordg.*

Client client = DiscordG.withToken args[0]

client.listener('member') {
client.listen('member') {
guild.sendMessage("Welcome to the guild, $member.mention!")
}

client.listener('member left') {
client.listen('member left') {
guild.sendMessage("Aww, $member.mention left the guild.")
}

client.listener('member changed') {
client.listen('member changed') {
guild.sendMessage("I see you changed, $member.mention.")
}
2 changes: 1 addition & 1 deletion examples/PingPong.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ Client client = DiscordG.withToken args[0]
* Names like "message" and "sendMessage" directly correspond to values in the ".listener" method,
* but need to be gathered from the first argument of the closure in the ".addListener" method.
*/
client.listener('message') {
client.listen('message') {
if (content.startsWith("!ping")) respond "Pong!"
}
2 changes: 1 addition & 1 deletion examples/PingPongPlus.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ static String getCommandArgs(String message, String command){
}

client = DiscordG.withToken args[0]
client.listener('message'){
client.listen('message'){
// Refer to isMessageCommand above to understand how it works.
if (isMessageCommand(content, "ping")){
// Refer to getCommandArgs above to understand how it works.
Expand Down
6 changes: 3 additions & 3 deletions examples/ServerListener.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import hlaaftana.discordg.*

Client client = DiscordG.withToken args[0]

client.listener 'guild', {
client.listen 'guild', {
guild.sendMessage("Hello there, new guild!")
}

client.listener 'guild deleted', {
client.listen 'guild deleted', {
println "It seems I left or was banned in/kicked out of $guild.name."
}

client.listener 'guild changed', {
client.listen 'guild changed', {
guild.sendMessage("Seems this guild updated.")
}
53 changes: 53 additions & 0 deletions examples/dsl/DSLExample.bot
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// java -jar DiscordG.jar this-file.bot

class Tag {
String name
String content
User author
}

bot {
trigger = '&'

client {
filter ~/(?i)stupid/, 'smart'
threadPoolSize 5
}

listen 'member join', {
guild.sendMessage "Hello there, $member!"
}

def tags = [:]

command 'tag', usages: [
'&tag help',
'&tag set (name) (content)',
'&tag delete (name)',
'&tag author (name)',
'&tag by (name)',
'&tag (name)'
], {
def (option, name, value) = arguments.split(/\s+/, 3)

if (option == 'help') {
respond "Usage:\n" + command.usages.join('\n')
} else if (option == 'set') {
tags[option] = new Tag(name: name, content: value, author: author)
respond "Set tag $name."
} else if (option == 'delete') {
respond tags.remove(name) ? "Removed tag $name." : "Tag $name doesn't exist."
} else if (option == 'author') {
def tag = tags[name]
respond tag ? "Author for tag $name is $tag.author.uniqueName." : "Tag $name not found."
} else if (option == 'by') {
def user = client.user(name)
def foundTags = tags.findAll { tagName, tag -> tag.author == user }
respond foundTags ? "Tags by $user.uniqueName (${foundTags.size()}): " + foundTags*.value*.name.join(', ')
: "No tags found by $user.uniqueName."
} else {
def tag = tags[name]
respond tag ? "$tag.content" : "Tag $name not found."
}
}
}
130 changes: 89 additions & 41 deletions src/main/groovy/hlaaftana/discordg/Client.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ import hlaaftana.discordg.collections.Cache
import hlaaftana.discordg.collections.DiscordListCache

import hlaaftana.discordg.exceptions.MessageInvalidException
import hlaaftana.discordg.logic.ActionPool
import hlaaftana.discordg.logic.ListenerSystem
import hlaaftana.discordg.logic.ParentListenerSystem
import static hlaaftana.discordg.logic.ActionPool.create as newPool
import hlaaftana.discordg.logic.*
import hlaaftana.discordg.net.*
import hlaaftana.discordg.util.*
import hlaaftana.discordg.objects.*
Expand All @@ -29,8 +28,10 @@ import org.eclipse.jetty.websocket.client.WebSocketClient
@SuppressWarnings('GroovyUnusedDeclaration')
@CompileStatic
class Client extends User {
private static final Closure<ActionPool> newPool = ActionPool.&new
static Map eventAliases = [MESSAGE: 'MESSAGE_CREATE',
/**
* Map of uppercase event names to be mapped to real discord event names in parseEvent.
*/
static Map<String, String> eventAliases = [MESSAGE: 'MESSAGE_CREATE',
NEW_MESSAGE: 'MESSAGE_CREATE', MESSAGE_DELETED: 'MESSAGE_DELETE',
MESSAGE_BULK_DELETE: 'MESSAGE_DELETE_BULK',
MESSAGE_BULK_DELETED: 'MESSAGE_DELETE_BULK',
Expand Down Expand Up @@ -71,14 +72,20 @@ class Client extends User {
RECIPIENT_REMOVED: 'CHANNEL_RECIPIENT_REMOVE', RELATIONSHIP: 'RELATIONSHIP_ADD',
NEW_RELATIONSHIP: 'RELATIONSHIP_ADD', RELATIONSHIP_ADDED: 'RELATIONSHIP_ADD',
RELATIONSHIP_REMOVED: 'RELATIONSHIP_REMOVE']
static List knownDiscordEvents = ['READY', 'MESSAGE_ACK', 'GUILD_INTEGRATIONS_UPDATE',
/**
* Events Discord is known to send.
*/
static List<String> knownDiscordEvents = ['READY', 'MESSAGE_ACK', 'GUILD_INTEGRATIONS_UPDATE',
'GUILD_EMOJIS_UPDATE', 'VOICE_STATE_UPDATE', 'VOICE_GUILD_UPDATE', 'USER_UPDATE',
'USER_GUILD_SETTINGS_UPDATE', 'USER_SETTINGS_UPDATE', 'GUILD_MEMBERS_CHUNK',
'GUILD_SYNC', 'CHANNEL_PINS_UPDATE', 'CHANNEL_PINS_ACK',
'MESSAGE_REACTION_REMOVE_ALL', 'WEBHOOKS_UPDATE', 'RESUMED'] +
(eventAliases.values() as ArrayList).toSet()
static List knownEvents = ['INITIAL_GUILD_CREATE', 'UNRECOGINZED', 'ALL'] + knownDiscordEvents

/**
* Events DiscordG might send.
*/
static List<String> knownEvents = ['INITIAL_GUILD_CREATE', 'UNRECOGINZED', 'ALL'] + knownDiscordEvents

String customUserAgent = ''
String getFullUserAgent(){ "$DiscordG.USER_AGENT $customUserAgent" }

Expand All @@ -90,49 +97,80 @@ class Client extends User {
boolean confirmedBot
void setBot(boolean x) { if (x && !confirmedBot) confirmedBot = true }

// if the key is a string, it calls .replace
// if the key is a pattern, it calls .replaceAll
Map messageFilters = [
/** if the key is a string, it calls .replace
* if the key is a pattern, it calls .replaceAll
*/
Map<Object, Object> messageFilters = new HashMap<Object, Object>(
'@everyone': '@\u200beveryone',
'@here': '@\u200bhere'
]
// name in log
)
/**
* name in log
*/
String logName = 'DiscordG'
// discord gateway version, dont change unless you know what it is and want to
/**
* discord gateway version, dont change unless you know what it is and want to
*/
int gatewayVersion = 6
// cache tokens from logins. dont turn this off.
/**
* cache tokens from email and password logins. dont turn this off.
*/
boolean cacheTokens = true
// path to the token cache file
/**
* path to the token cache file
*/
String tokenCachePath = 'token.json'
// maximum amount of events that can be handled at the same time
// increasing might help with lag but takes up more CPU
int eventThreadCount = 3
// number of maximum members in a guild until discord doesnt send offline members
// set lower for a possible RAM decrease
/**
* maximum amount of events that can be handled at the same time
* increasing might help with lag but takes up more CPU
*/
int threadPoolSize = 3
/**
* number of maximum members in a guild until discord doesnt send offline members
* set lower for a possible RAM decrease
*/
int largeThreshold = 250
// request offline members after discord gives us the online ones for large guilds
// set this to false if youre changing large threshold or if it uses too much RAM
/**
* request offline members after discord gives us the online ones for large guilds
* set this to false if youre changing large threshold or if it uses too much RAM
*/
boolean requestMembersOnReady = true
// adds the READY raw event data to the cache
// set to false for possible RAM decrease
/**
* adds the READY raw event data to the cache
* set to false for possible RAM decrease
*/
boolean copyReady = true
// retry a request on a 5xx status code
// generally harmless, 5xx status codes are usually nothing
/**
* retry a request on a 5xx status code
* generally harmless, 5xx status codes are usually nothing
*/
boolean retryOn502 = true
// requests a member on PRESENCE_UPDATE for the joined_at data for a newly discovered member
// dont turn it on unless you need join dates and cant request offline members
/**
* requests a member on PRESENCE_UPDATE for the joined_at data for a newly discovered member
* dont turn it on unless you need join dates and cant request offline members
*/
boolean allowMemberRequesting = false
// spread message bulk delete events to separate message delete events
// true by default for easier handling by bots
/**
* spread message bulk delete events to separate message delete events
* true by default for easier handling by bots
*/
boolean spreadBulkDelete = true
// timeout for waiting for guild_create events after the READY
// only for bots and accounts at or over 100 guilds
/**
* timeout for waiting for guild_create events after the READY
* only for bots and accounts at or over 100 guilds
*/
long guildTimeout = 30_000
// whitelisted events
List includedEvents = []
// blacklisted events
List excludedEvents = ['TYPING_START']
// for shards, [shardId, shardCount]
/**
* whitelisted events
*/
List<String> eventWhitelist = []
/**
* blacklisted events
*/
List<String> eventBlacklist = ['TYPING_START']
/**
* for shards, [shardId, shardCount]
*/
Tuple2 shardTuple

Log log
Expand All @@ -150,7 +188,6 @@ class Client extends User {
login: newPool(1, 60_000),
connect: newPool(1, 30_000)
]
// if you want to use global variables through the API object. mostly for utility

List<DiscordRawWSListener> rawListeners = []
@Delegate(excludes = ['getClass', 'equals']) ListenerSystem listenerSystem = new ParentListenerSystem(this)
Expand Down Expand Up @@ -209,6 +246,9 @@ class Client extends User {

WSClient getWebSocketClient(){ ws }

def blacklist(event) { client.eventBlacklist.add(parseEvent(event)) }
def whitelist(event) { client.eventWhitelist.add(parseEvent(event)) }

void login(String email, String password, boolean threaded=true){
Closure a = {
log.info 'Getting token...'
Expand Down Expand Up @@ -1283,17 +1323,25 @@ class Client extends User {
isWebhook ? clos() : askPool('sendMessages', getChannelQueueName(c), clos)
}

Message sendFile(Map data, c, implicatedFile, filename = null) {
Message sendFile(Map data, c, implicatedFile, filename) {
def file
if (implicatedFile.class in [File, String]) file = implicatedFile as File
else file = ConversionUtil.getBytes(implicatedFile)
new Message(this, sendFileRaw((filename ? [filename: filename] : [:]) << data, c, file))
}

Message sendFile(c, implicatedFile, filename = null){
Message sendFile(Map data, c, implicatedFile) {
sendFile(data, c, implicatedFile, null)
}

Message sendFile(c, implicatedFile, filename){
sendFile([:], c, implicatedFile, filename)
}

Message sendFile(c, implicatedFile){
sendFile([:], c, implicatedFile, null)
}

Message requestMessage(c, ms, boolean addToCache = true){
def ch = id(c)
def m = new Message(this,
Expand Down
9 changes: 7 additions & 2 deletions src/main/groovy/hlaaftana/discordg/DSLMain.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,18 @@ class DSLMain {
ImportCustomizer imports = new ImportCustomizer()
imports.addStarImports('hlaaftana.discordg', 'hlaaftana.discordg.dsl',
'hlaaftana.discordg.objects', 'hlaaftana.discordg.status',
'hlaaftana.discordg.net', 'hlaaftana.discordg.util')
'hlaaftana.discordg.net', 'hlaaftana.discordg.util', 'hlaaftana.discordg.util.bot',
'hlaaftana.discordg.exceptions', 'hlaaftana.discordg.logic')
CompilerConfiguration cc = new CompilerConfiguration()
cc.addCompilationCustomizers(imports)
cc.scriptBaseClass = DelegatingScript.name
GroovyShell sh = new GroovyShell(new Binding(), cc)
DelegatingScript script = (DelegatingScript) sh.parse(new File(args[0]))
script.delegate = new GroovyBot()
def dsl = new GroovyBot()
script.delegate = dsl
script.run()
if (null != dsl.bot) dsl.bot.initialize()
else if (null != dsl.client) dsl.client.login()
else throw new IllegalArgumentException('Why run a DSL if you aren\'t going to use it?')
}
}
Loading

0 comments on commit c095186

Please sign in to comment.