Ban command not working JDA please help debuged and everything - discord-jda

Hello so i am making a bot in JDA and i just made a ban command but it aint banning anyone the code is
i mention the user and also put a reason and put the user id and still make no difference
package me.programmer.CodeDevelopment.Commands;
import me.programmer.CodeDevelopment.Bot;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import java.util.List;
public class Ban extends ListenerAdapter {
public void onMessageGuildReceived(List<String> args, GuildMessageReceivedEvent e){
String msg = e.getMessage().getContentRaw();
if(msg.equalsIgnoreCase(Bot.PREFIX + "ban")){
TextChannel channel = e.getChannel();
Member member = e.getMember();
List<Member> mentionedMembers = e.getMessage().getMentionedMembers();
if (mentionedMembers.isEmpty() || args.size() < 2) {
channel.sendMessage("Missing Arguments").queue();
return;
}
Member target = mentionedMembers.get(0);
String reason = String.join(" ", args.subList(1, args.size()));
if (!member.hasPermission(Permission.BAN_MEMBERS) && !member.canInteract(target)){
channel.sendMessage("You dont have pmerission to run this command").queue();
return;
}
target.ban(1)
.reason(String.format("Ban by: %#s, with reason: %s", e.getAuthor(), reason)).queue();
}
}
}
Please help i have been stuck on this for a little while.

Like Minn mentioned, You didn't override the method from ListenerAdapter properly. The name and parameter list have to match.
Also, You're checking if the entire message is equal to {PREFIX}ban yet your ban command is structured like so {PREFIX}ban (user) so your code always stops on this line:
if(msg.equalsIgnoreCase(Bot.PREFIX + "ban"))
Because that is never true when using the command correctly.
This should work instead (I've changed the msg check to starts with from equals, I've changed the method name to the right one with the right parameters from ListenerAdapter and I've then kept your usage of args by splitting the msg string and putting that into a list):
public class Ban extends ListenerAdapter {
#Override
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String msg = e.getMessage().getContentRaw();
if (msg.startsWith(Bot.PREFIX + "ban")) {
TextChannel channel = e.getChannel();
Member member = e.getMember();
List<Member> mentionedMembers = e.getMessage().getMentionedMembers();
List<String> args = Arrays.asList(msg.split(" "));
if (mentionedMembers.isEmpty() || args.size() < 2) {
channel.sendMessage("Missing Arguments").queue();
return;
}
Member target = mentionedMembers.get(0);
String reason = String.join(" ", args.subList(1, args.size()));
if (!member.hasPermission(Permission.BAN_MEMBERS) && !member.canInteract(target)) {
channel.sendMessage("You dont have pmerission to run this command").queue();
return;
}
target.ban(1)
.reason(String.format("Ban by: %#s, with reason: %s", e.getAuthor(), reason)).queue();
}
}
}

Related

Updating an entry in PersistentVector not working NEAR Protocol

I'm trying to update the status of a job object. I get the "success" message return but the value is not updating. Do I miss something?
#nearBindgen
export class Contract {
private jobs: PersistentVector<Job> = new PersistentVector<Job>('jobs');
......
#mutateState()
cancelJob(jobTitle: string): string {
for (let i = 0; i < this.jobs.length; i++) {
if (this.jobs[i].title == jobTitle) {
this.jobs[i].status = "Cancelled";
return "success"
}
}
return "not found";
}
And I'm calling it like that:
near call apptwo.msaudi.testnet cancelJob '{\"jobTitle\":\"title2\"}' --account-id=msaudi.testnet
It’s not enough to update entry when you fetch it. You need to update the storage on the contract as well. Write it back in so to speak.
This isn’t enough
this.jobs[i].status = "Cancelled";
You need to add it back in:
if (this.jobs[i].title == jobTitle) {
const job: Job = this.jobs[i]; // Need an intermediate object in memory
job.status = "Cancelled";
this.jobs.replace(i, job); // Update storage with the new job.
return "success"
}

How to do syntaxhighlighting for terminal rules in Xtext?

I would like to do custom syntaxhighlighting in xtext. I would like to highlight everything that matches a terminal rule in a specific color.
For example my terminal rule:
terminal MYRULE:
('ab'|'2')*
;
I would like to color the everything like a comment what matches this terminal rule.
I tired the following:
package org.xtext.example.mydsl.ui;
import java.util.regex.Pattern;
import org.eclipse.xtext.ide.editor.syntaxcoloring.HighlightingStyles;
import org.eclipse.xtext.ui.editor.syntaxcoloring.DefaultAntlrTokenToAttributeIdMapper;
public class STAntlrTokenToAttributeIdMapper extends DefaultAntlrTokenToAttributeIdMapper {
private static final Pattern QUOTED = Pattern.compile("(?:^'([^']*)'$)|(?:^\"([^\"]*)\")$", Pattern.MULTILINE);
private static final Pattern PUNCTUATION = Pattern.compile("\\p{Punct}*");
#Override
protected String calculateId(String tokenName, int tokenType) {
System.out.println("token = " + tokenName);
if ("MYRULE".equals(tokenName)) {
return HighlightingStyles.COMMENT_ID;
}
if(QUOTED.matcher(tokenName).matches()) {
return HighlightingStyles.KEYWORD_ID;
}
if("RULE_STRING".equals(tokenName)) {
return HighlightingStyles.STRING_ID;
}
if("RULE_INT".equals(tokenName)) {
return HighlightingStyles.NUMBER_ID;
}
if("RULE_ML_COMMENT".equals(tokenName) || "RULE_SL_COMMENT".equals(tokenName)) {
return HighlightingStyles.COMMENT_ID;
}
return HighlightingStyles.DEFAULT_ID;
}
}
I see the print for "MYRULE". The code is accepted from the editor. But the special code part is not highlighted.
Of course the rule is just an example and not part of the DLS I am working on. But I can't tell details about my DSL.

How to paste the text copied in clipboard through Selenium and Java on MacOS

I want to paste some text in one of the textbox in MACOS. I am trying below code. But Control + v and Command + v both are not working. I have also seen that this is known issue, but not sure if it is resolved or not.
https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5919
The code is as below.
public void copyToClipbord(String copyTo)
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection str = new StringSelection(copyTo);
clipboard.setContents(str, null );
}
// And paste into required input/testfield/testarea field object
public void pasteText(WebElement element, String value)
{
copyToClipbord(value);
element.click();
//new Actions( driver ).contextClick( element ).sendKeys( "P" ).sendKeys("\n").perform();
element.sendKeys(Keys.CONTROL, "V");
}
I have also tried context click, that also does not work. I have validated that copyToClipboard function is working properly. Please suggest me, if there are any work around to this.
Thanks,
Umang
You have to select paste option in pop up which open after right and then click on paste option.
You can write code like this.
new Actions(driver ).contextClick(element).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).
sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
For me Paste option is present at 5th position. So I have written sendKeys(Keys.ARROW_DOWN) 5 times. You can write this as per your requirement.
I hope this will work for you.
As you have mentioned copyToClipboard() function is working properly moving forward to send the character sequence through sendKeys() you can use the following solution:
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
copyToClipbord(value);
String data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
element.sendKeys(data);
public String copyFromClipboard() {
boolean found = false
String data = ''
int count = 0
while (found == false) {
count++
try {
WebDriver driver = DriverFactory.getWebDriver()
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
data = ((Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor)) as String)
if (!(data.contains('https'))) {
found = false
} else {
println((('Found the data in the ' + count) + ' try: ') + data)
return data
found = true
break
}
}
catch (UnsupportedFlavorException e) {
println(e)
}
catch (IOException e) {
println(e)
}
}
}

AIR NativeProcess on Mac gives Error:3219, all solutions failing

I've read up most solutions for this error and none seem to apply.
I'm running a basic AS3 app in FlashBuilder, on OS-X.
descriptor is set to extendedDesktop
have set the profile in FB to 'extendedDesktop'
am publishing as 'signed native installer'
I've tried launching the file from both:
app:/demo.sh
file:///Users/visualife/Desktop/AE/demo.sh
the target file is set to 777 (executable)
the target file runs fine when directly targetted
i'm running the exe on the same OS and machine it's created on
changing the 'demo.sh' file to a jpg etc doesn't change anything
No matter what I try I get told native process is support, everything runs fine until start is called then a Error: 3219 is thrown with no further information.
all help greatly appreciated!
I've included my code below:
package {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.display.Sprite;
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.NativeProcessExitEvent;
import flash.events.ProgressEvent;
import flash.filesystem.File;
import flash.text.TextField;
public class VauxhallController extends Sprite {
private var debug_txt:TextField;
public var process:NativeProcess;
private var sh:File;
public function VauxhallController() {
if (stage) {
init();
} else {
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function init($e:Event=null):void {
this.removeEventListener(Event.ADDED_TO_STAGE, init);
build();
if (NativeProcess.isSupported) {
initListeners();
debugMe("Native process supported");
go();
} else {
debugMe("Native not supported");
}
}
private function build():void {
// debug
debug_txt = new TextField();
debug_txt.width = 300;
debug_txt.height= 600;
this.addChild(debug_txt);
}
private function initListeners():void { }
private function go():void {
runShellFile();
}
private function runShellFile():void {
debugMe("runShellFile");
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var essArgs:Vector.<String> = new Vector.<String>();
var file:File;
file = File.desktopDirectory.resolvePath("AE/demo.sh");
debugMe("path|"+ File.desktopDirectory.resolvePath("AE/demo.sh").url);
nativeProcessStartupInfo.executable = file;
nativeProcessStartupInfo.workingDirectory = File.desktopDirectory;
nativeProcessStartupInfo.executable = file;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
process.addEventListener(NativeProcessExitEvent.EXIT, onExit);
process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
try {
process.start(nativeProcessStartupInfo);
} catch (error:IllegalOperationError) {
debugMe(error.toString());
} catch (error:ArgumentError) {
debugMe(error.toString());
} catch (error:Error) {
debugMe(error.toString());
}
debugMe("# DONE");
}
public function onOutputData(event:ProgressEvent):void { debugMe("Got: "+ process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable)); }
public function onErrorData(event:ProgressEvent):void { debugMe("ERROR: "+ process.standardError.readUTFBytes(process.standardError.bytesAvailable)); }
public function onExit(event:NativeProcessExitEvent):void { debugMe("Process exited with: "+ event.exitCode); }
public function onIOError(event:IOErrorEvent):void { debugMe("IOError: "+ event.toString()); }
private function debugMe(_str:String):void { debug_txt.appendText(_str +"\n"); }
}
}
Have you read this article?
http://www.actionscripterrors.com/?p=2527
<supportedProfiles>extendedDesktop desktop</supportedProfiles>
I have the same error and in my case is because I'm trying to open .exe on MacOS. Verify if your demo.sh script interacts with .exe files.

Breaking on exception: String expected

When I run my code I get:
Breaking on exception: String expected
What I am trying to do is connect to my server using a websocket. However, it seems that no matter if my server is online or not the client still crashes.
My code:
import 'dart:html';
WebSocket serverConn;
int connectionAttempts;
TextAreaElement inputField = querySelector("#inputField");
String key;
void submitMessage(Event e) {
if (serverConn.readyState == WebSocket.OPEN) {
querySelector("#chatLog").text = inputField.value;
inputField.value = "";
}
}
void recreateConnection(Event e) {
connectionAttempts++;
if (connectionAttempts <= 5) {
inputField.value = "Connection failed, reconnecting. Attempt" + connectionAttempts.toString() + "out of 5";
serverConn = new WebSocket("ws://127.0.0.1:8887");
serverConn.onClose.listen(recreateConnection);
serverConn.onError.listen(recreateConnection);
} else {
inputField.value = "Connections ran out, please refresh site";
}
}
void connected(Event e) {
serverConn.sendString(key);
if (serverConn.readyState == WebSocket.OPEN) {
inputField.value = "CONNECTED!";
inputField.readOnly = false;
}
}
void main() {
serverConn = new WebSocket("ws://127.0.0.1:8887");
serverConn.onClose.listen(recreateConnection);
serverConn.onError.listen(recreateConnection);
serverConn.onOpen.listen(connected);
//querySelector("#inputField").onInput.listen(submitMessage);
querySelector("#sendInput").onClick.listen(submitMessage);
}
My Dart Editor says nothing about where the problem comes from nor does it give any warning until run-time.
You need to initialize int connectionAttempts; with a valid value;
connectionAttempts++; fails with an exception on null.
You also need an onMessage handler to receive messages.
serverConn.onMessage.listen((MessageEvent e) {
recreateConnection should register an onOpen handler as well.
After serverConn = new WebSocket the listener registered in main() will not work
If you register a listener where only one single event is expected you can use first instead of listen
serverConn.onOpen.first.then(connected);
According to #JAre s comment.
Try to use a hardcoded string
querySelector("#chatLog").text = 'someValue';
to ensure this is not the culprit.

Resources