Skip to content

Commit ed0bca0

Browse files
committed
Finished, porting scriptable tricks over to new module based mangobot...
1 parent e503e1a commit ed0bca0

File tree

12 files changed

+1345
-77
lines changed

12 files changed

+1345
-77
lines changed

build.gradle

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ dependencies {
6767

6868
// library('org.classdump.luna:luna-all-shaded:0.4.1')
6969

70+
71+
library('org.luaj:luaj-jme:3.0.1')
72+
7073
library('dev.arbjerg:lavaplayer:2.2.3')
7174
library('dev.lavalink.youtube:common:1.12.0')
7275
}

src/main/java/module-info.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
requires static lavaplayer;
1212
requires static common;
1313
requires java.desktop;
14+
requires luaj.jme;
1415

1516

1617
exports org.mangorage.mangobotplugin.entrypoint;

src/main/java/org/mangorage/mangobotplugin/commands/trick/TrickScriptable.java

Lines changed: 90 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,27 @@
2525
import net.dv8tion.jda.api.entities.Message;
2626
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
2727

28+
import org.luaj.vm2.Globals;
29+
import org.luaj.vm2.LoadState;
30+
import org.luaj.vm2.LuaTable;
31+
import org.luaj.vm2.LuaValue;
32+
import org.luaj.vm2.compiler.LuaC;
33+
import org.luaj.vm2.lib.BaseLib;
34+
import org.luaj.vm2.lib.MathLib;
35+
import org.luaj.vm2.lib.PackageLib;
36+
import org.mangorage.mangobotplugin.commands.trick.lua.LuaJDA;
37+
import org.mangorage.mangobotplugin.commands.trick.lua.internal.CoerceJavaToLua;
38+
import org.mangorage.mangobotplugin.commands.trick.lua.objects.LuaStringArray;
2839
import org.mangorage.mangobotplugin.entrypoint.MangoBot;
2940

41+
import java.util.concurrent.Executors;
42+
import java.util.concurrent.Future;
43+
import java.util.concurrent.ScheduledExecutorService;
44+
import java.util.concurrent.ScheduledFuture;
45+
import java.util.concurrent.TimeUnit;
46+
import java.util.concurrent.atomic.AtomicReference;
47+
import java.util.function.Consumer;
48+
3049
public class TrickScriptable {
3150
private final MangoBot plugin;
3251

@@ -35,83 +54,78 @@ public TrickScriptable(MangoBot plugin) {
3554
}
3655

3756

38-
// public Globals sandBoxedGlobals() {
39-
// Globals server_globals = new Globals();
40-
//
41-
// server_globals.load(new JseBaseLib());
42-
// server_globals.load(new PackageLib());
43-
// server_globals.load(new JseMathLib());
44-
//
45-
//
46-
// LoadState.install(server_globals);
47-
// LuaC.install(server_globals);
48-
//
49-
// var array = new String[]{"os", "io", "luajava", "debug", "load", "loadfile"};
50-
//
51-
// Consumer<String> NILLIFY = a -> {
52-
// server_globals.set(a, LuaValue.NIL);
53-
// };
54-
//
55-
// for (String library : array)
56-
// NILLIFY.accept(library);
57-
//
58-
// return server_globals;
59-
// }
57+
public Globals sandBoxedGlobals() {
58+
Globals server_globals = new Globals();
59+
60+
server_globals.load(new BaseLib());
61+
server_globals.load(new MathLib());
62+
server_globals.load(new PackageLib());
63+
64+
LoadState.install(server_globals);
65+
LuaC.install(server_globals);
66+
67+
var array = new String[]{"os", "io", "luajava", "debug", "load", "loadfile"};
68+
69+
Consumer<String> NILLIFY = a -> {
70+
server_globals.set(a, LuaValue.NIL);
71+
};
72+
73+
for (String library : array)
74+
NILLIFY.accept(library);
75+
76+
return server_globals;
77+
}
6078

6179
public void execute(Trick trick, String script, Message message, MessageChannel messageChannel, String[] args) {
62-
// // Create a ScheduledExecutorService
63-
// ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
64-
// AtomicReference<ScheduledFuture<?>> TASK = new AtomicReference<>();
65-
//
66-
// // Define the task you want to execute
67-
//
68-
// Globals globals = sandBoxedGlobals();
69-
// LuaValue code = globals.load(script);
70-
//
71-
// Runnable task = () -> {
72-
// try {
73-
// code.call();
74-
//
75-
// LuaValue method = globals.get("execute");
76-
// LuaTable arr = new LuaTable();
77-
// for (int i = 0; i < args.length; i++)
78-
// arr.set(i + 1, LuaValue.valueOf(args[i]));
79-
//
80-
// if (!method.isnil()) {
81-
// method.call(
82-
// CoerceJavaToLua.coerce(new LuaJDA(plugin, trick, message, messageChannel)),
83-
// CoerceJavaToLua.coerce(new LuaStringArray(args))
84-
// );
85-
// }
86-
// if (TASK.get() != null) {
87-
// var a = TASK.get();
88-
// if (a.isDone() || a.isCancelled()) return;
89-
// a.cancel(true);
90-
// }
91-
// } catch (Exception e) {
92-
// message.reply(e.getMessage()).mentionRepliedUser(false).queue();
93-
// }
94-
// };
95-
//
96-
// // Submit the task to the executor
97-
// Future<?> future = executor.submit(() -> {
98-
// long time = System.currentTimeMillis();
99-
// task.run();
100-
// System.out.println("Script Took: %s ms".formatted(System.currentTimeMillis() - time));
101-
// });
102-
//
103-
// // Schedule a task to cancel the original task if it runs longer than the timeout
104-
// TASK.set(executor.schedule(() -> {
105-
// if (future.isDone() || future.isCancelled()) return;
106-
// message.reply("Trick took to long to run. Stopping Trick...").mentionRepliedUser(false).queue();
107-
// future.cancel(true);
108-
// }, 1000, TimeUnit.MILLISECONDS));
109-
//
110-
// // Shutdown the executor
111-
// executor.shutdown();
112-
113-
if (message != null) {
114-
message.reply("Scripts Disabled").queue();
115-
}
80+
// Create a ScheduledExecutorService
81+
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
82+
AtomicReference<ScheduledFuture<?>> TASK = new AtomicReference<>();
83+
84+
// Define the task you want to execute
85+
86+
Globals globals = sandBoxedGlobals();
87+
LuaValue code = globals.load(script);
88+
89+
Runnable task = () -> {
90+
try {
91+
code.call();
92+
93+
LuaValue method = globals.get("execute");
94+
LuaTable arr = new LuaTable();
95+
for (int i = 0; i < args.length; i++)
96+
arr.set(i + 1, LuaValue.valueOf(args[i]));
97+
98+
if (!method.isnil()) {
99+
method.call(
100+
CoerceJavaToLua.coerce(new LuaJDA(plugin, trick, message, messageChannel)),
101+
CoerceJavaToLua.coerce(new LuaStringArray(args))
102+
);
103+
}
104+
if (TASK.get() != null) {
105+
var a = TASK.get();
106+
if (a.isDone() || a.isCancelled()) return;
107+
a.cancel(true);
108+
}
109+
} catch (Exception e) {
110+
message.reply(e.getMessage()).mentionRepliedUser(false).queue();
111+
}
112+
};
113+
114+
// Submit the task to the executor
115+
Future<?> future = executor.submit(() -> {
116+
long time = System.currentTimeMillis();
117+
task.run();
118+
System.out.println("Script Took: %s ms".formatted(System.currentTimeMillis() - time));
119+
});
120+
121+
// Schedule a task to cancel the original task if it runs longer than the timeout
122+
TASK.set(executor.schedule(() -> {
123+
if (future.isDone() || future.isCancelled()) return;
124+
message.reply("Trick took to long to run. Stopping Trick...").mentionRepliedUser(false).queue();
125+
future.cancel(true);
126+
}, 1000, TimeUnit.MILLISECONDS));
127+
128+
// Shutdown the executor
129+
executor.shutdown();
116130
}
117131
}
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
/*******************************************************************************
2+
* Copyright (c) 2009-2011 Luaj.org. All rights reserved.
3+
*
4+
* Permission is hereby granted, free of charge, to any person obtaining a copy
5+
* of this software and associated documentation files (the "Software"), to deal
6+
* in the Software without restriction, including without limitation the rights
7+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8+
* copies of the Software, and to permit persons to whom the Software is
9+
* furnished to do so, subject to the following conditions:
10+
*
11+
* The above copyright notice and this permission notice shall be included in
12+
* all copies or substantial portions of the Software.
13+
*
14+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20+
* THE SOFTWARE.
21+
******************************************************************************/
22+
package org.mangorage.mangobotplugin.commands.trick.lua.internal;
23+
24+
import org.luaj.vm2.LuaDouble;
25+
import org.luaj.vm2.LuaInteger;
26+
import org.luaj.vm2.LuaString;
27+
import org.luaj.vm2.LuaUserdata;
28+
import org.luaj.vm2.LuaValue;
29+
30+
import java.util.HashMap;
31+
import java.util.Map;
32+
33+
/**
34+
* Helper class to coerce values from Java to lua within the luajava library.
35+
* <p>
36+
* This class is primarily used by the {@link org.luaj.vm2.lib.jse.LuajavaLib},
37+
* but can also be used directly when working with Java/lua bindings.
38+
* <p>
39+
* To coerce scalar types, the various, generally the {@code valueOf(type)} methods
40+
* on {@link LuaValue} may be used:
41+
* <ul>
42+
* <li>{@link LuaValue#valueOf(boolean)}</li>
43+
* <li>{@link LuaValue#valueOf(byte[])}</li>
44+
* <li>{@link LuaValue#valueOf(double)}</li>
45+
* <li>{@link LuaValue#valueOf(int)}</li>
46+
* <li>{@link LuaValue#valueOf(String)}</li>
47+
* </ul>
48+
* <p>
49+
* To coerce arrays of objects and lists, the {@code listOf(..)} and {@code tableOf(...)} methods
50+
* on {@link LuaValue} may be used:
51+
* <ul>
52+
* <li>{@link LuaValue#listOf(LuaValue[])}</li>
53+
* <li>{@link LuaValue#listOf(LuaValue[], org.luaj.vm2.Varargs)}</li>
54+
* <li>{@link LuaValue#tableOf(LuaValue[])}</li>
55+
* <li>{@link LuaValue#tableOf(LuaValue[], LuaValue[], org.luaj.vm2.Varargs)}</li>
56+
* </ul>
57+
* The method {@link CoerceJavaToLua#coerce(Object)} looks as the type and dimesioning
58+
* of the argument and tries to guess the best fit for corrsponding lua scalar,
59+
* table, or table of tables.
60+
*
61+
* @see CoerceJavaToLua#coerce(Object)
62+
* @see org.luaj.vm2.lib.jse.LuajavaLib
63+
*/
64+
public class CoerceJavaToLua {
65+
66+
static interface Coercion {
67+
public LuaValue coerce( Object javaValue );
68+
};
69+
70+
private static final class BoolCoercion implements Coercion {
71+
public LuaValue coerce( Object javaValue ) {
72+
Boolean b = (Boolean) javaValue;
73+
return b.booleanValue()? LuaValue.TRUE: LuaValue.FALSE;
74+
}
75+
}
76+
77+
private static final class IntCoercion implements Coercion {
78+
public LuaValue coerce( Object javaValue ) {
79+
Number n = (Number) javaValue;
80+
return LuaInteger.valueOf( n.intValue() );
81+
}
82+
}
83+
84+
private static final class CharCoercion implements Coercion {
85+
public LuaValue coerce( Object javaValue ) {
86+
Character c = (Character) javaValue;
87+
return LuaInteger.valueOf( c.charValue() );
88+
}
89+
}
90+
91+
private static final class DoubleCoercion implements Coercion {
92+
public LuaValue coerce( Object javaValue ) {
93+
Number n = (Number) javaValue;
94+
return LuaDouble.valueOf( n.doubleValue() );
95+
}
96+
}
97+
98+
private static final class StringCoercion implements Coercion {
99+
public LuaValue coerce( Object javaValue ) {
100+
return LuaString.valueOf( javaValue.toString() );
101+
}
102+
}
103+
104+
private static final class BytesCoercion implements Coercion {
105+
public LuaValue coerce( Object javaValue ) {
106+
return LuaValue.valueOf((byte[]) javaValue);
107+
}
108+
}
109+
110+
private static final class ClassCoercion implements Coercion {
111+
public LuaValue coerce( Object javaValue ) {
112+
return JavaClass.forClass((Class) javaValue);
113+
}
114+
}
115+
116+
private static final class InstanceCoercion implements Coercion {
117+
public LuaValue coerce(Object javaValue) {
118+
return new JavaInstance(javaValue);
119+
}
120+
}
121+
122+
private static final class ArrayCoercion implements Coercion {
123+
public LuaValue coerce(Object javaValue) {
124+
// should be userdata?
125+
return new JavaArray(javaValue);
126+
}
127+
}
128+
129+
private static final class LuaCoercion implements Coercion {
130+
public LuaValue coerce( Object javaValue ) {
131+
return (LuaValue) javaValue;
132+
}
133+
}
134+
135+
136+
static final Map COERCIONS = new HashMap();
137+
138+
static {
139+
Coercion boolCoercion = new BoolCoercion() ;
140+
Coercion intCoercion = new IntCoercion() ;
141+
Coercion charCoercion = new CharCoercion() ;
142+
Coercion doubleCoercion = new DoubleCoercion() ;
143+
Coercion stringCoercion = new StringCoercion() ;
144+
Coercion bytesCoercion = new BytesCoercion() ;
145+
Coercion classCoercion = new ClassCoercion() ;
146+
COERCIONS.put( Boolean.class, boolCoercion );
147+
COERCIONS.put( Byte.class, intCoercion );
148+
COERCIONS.put( Character.class, charCoercion );
149+
COERCIONS.put( Short.class, intCoercion );
150+
COERCIONS.put( Integer.class, intCoercion );
151+
COERCIONS.put( Long.class, doubleCoercion );
152+
COERCIONS.put( Float.class, doubleCoercion );
153+
COERCIONS.put( Double.class, doubleCoercion );
154+
COERCIONS.put( String.class, stringCoercion );
155+
COERCIONS.put( byte[].class, bytesCoercion );
156+
COERCIONS.put( Class.class, classCoercion );
157+
}
158+
159+
/**
160+
* Coerse a Java object to a corresponding lua value.
161+
* <p>
162+
* Integral types {@code boolean}, {@code byte}, {@code char}, and {@code int}
163+
* will become {@link LuaInteger};
164+
* {@code long}, {@code float}, and {@code double} will become {@link LuaDouble};
165+
* {@code String} and {@code byte[]} will become {@link LuaString};
166+
* types inheriting from {@link LuaValue} will be returned without coercion;
167+
* other types will become {@link LuaUserdata}.
168+
* @param o Java object needing conversion
169+
* @return {@link LuaValue} corresponding to the supplied Java value.
170+
* @see LuaValue
171+
* @see LuaInteger
172+
* @see LuaDouble
173+
* @see LuaString
174+
* @see LuaUserdata
175+
*/
176+
public static LuaValue coerce(Object o) {
177+
if ( o == null )
178+
return LuaValue.NIL;
179+
Class clazz = o.getClass();
180+
Coercion c = (Coercion) COERCIONS.get( clazz );
181+
if ( c == null ) {
182+
c = clazz.isArray()? arrayCoercion:
183+
o instanceof LuaValue ? luaCoercion:
184+
instanceCoercion;
185+
COERCIONS.put( clazz, c );
186+
}
187+
return c.coerce(o);
188+
}
189+
190+
static final Coercion instanceCoercion = new InstanceCoercion();
191+
192+
static final Coercion arrayCoercion = new ArrayCoercion();
193+
194+
static final Coercion luaCoercion = new LuaCoercion() ;
195+
}

0 commit comments

Comments
 (0)