Minecraft Chat Message Replacement - java

I am making a permissions plugin, and want to replace the name of a player with their rank tag. For this, I have the following code:
public void playerChat(AsyncPlayerChatEvent e) {
Player target = e.getPlayer();
String message = e.getMessage().replaceAll(target.getName(), colorize(rFile.getString("players." + target)) + " " + target.getName());
e.setMessage(message);
}
Whenever I send a message to chat, it appears like it would normally.
What am I doing wrong here?
Additionally, I am using a config file (cFile) and a ranks.yml file (rFile).

First off, make sure you include the #EventHandler annotation.
#EventHandler
public void playerChat(AsyncPlayerChatEvent e) {
[...]
}
Next, check if the listener is registered in your onEnable()method.
getServer().getPluginManager().registerEvents(new YourListener(...), this);
(Replace the YourListener with this in case it's your main class)
Finally, as Luftbaum said, use AsyncPlayerChatEvent#setFormat within the event.
Example Usage:
e.setFormat(colorize(rFile.getString("players." + target)) + ": " + e.getMessage());
Edit:
In order to translate color codes such as '&3' to Bukkit's ChatColor format, you can use the ChatColor#translateAlternativeColorCodes method.
ChatColor.translateAlternateColorCodes('&', stringThatContainsCodes);

Useevent.setFormat(playerRank + ": " + event.getMessage());
This basically formats the message to be the way you want. You can use ChatColor to do colors. Also make sure you have #EventHandler.

Related

Discord JDA: Why is the Reader throwing "Unknown Interaction"

i have a button which sends a message into a specific textchannel to ping authorised staff, but everytime its throwing UNKNOWN INTERACTION and is not sending the message. Ive tried many things and i dont know whats wrong and how to fix it, because other buttons work. ereignis is the "event" in german
public void onButtonInteraction(ButtonInteractionEvent ereignis) {
if (ereignis.getButton().getId().equals("ssuuii")) {
if (ereignis.getGuild().getId().equals("GUILD_ID")) {
ereignis.deferReply().queue();
ereignis.getGuild().getTextChannelById("TEXTCHANNEL_ID").sendMessage(ereignis.getGuild().getRoleById("ROLE_ID")
.getAsMention() + ", " + ereignis.getMember().getAsMention() + " möchte Support haben").queue();
} else if (ereignis.getGuild().getId().equals("GUILD_ID_A")) {
ereignis.deferReply().queue();
ereignis.getGuild().getTextChannelById("TEXTCHANNEL_ID_A").sendMessage("exampleman, " +
ereignis.getMember().getAsMention() + " wants Support").queue();
}
}
}
and the Button:
e.getChannel().sendMessageEmbeds(s.build()).setActionRow(Button.success("ssuuii", "Call Support"))
.complete().delete().queueAfter(15, TimeUnit.SECONDS);

bitcoinJ get transaction value

I downloaded a lot of blockchain data using https://bitcoin.org, I took some file and I try to analyse it with bitcoinj library.
I would like to get information from every transaction:
-who send bitcoins,
-how much,
-who receive bitcoins.
I use:
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>0.15.10</version>
</dependency>
I have a code:
NetworkParameters np = new MainNetParams();
Context.getOrCreate(MainNetParams.get());
BlockFileLoader loader = new BlockFileLoader(np,List.of(new File("test/resources/blk00450.dat")));
for (Block block : loader) {
for (Transaction tx : block.getTransactions()) {
System.out.println("Transaction ID" + tx.getTxId().toString());
for (TransactionInput ti : tx.getInputs()) {
// how to get wallet addresses of inputs?
}
// this code works for 99% of transactions but for some throws exceptions
for (TransactionOutput to : tx.getOutputs()) {
// sometimes this line throws: org.bitcoinj.script.ScriptException: Cannot cast this script to an address
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
System.out.println("out value:" + to.getValue().toString());
}
}
}
Can you share some snippet that will work for all transactions in the blockchain?
There are at least two type of transaction, P2PKH and P2SH.
Your code would work well with P2PKH, but wouldn not work with P2SH.
You can change the line from:
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
to:
System.out.println("out address:" + to.getAddressFromP2PKHScript(np)!=null?to.getAddressFromP2PKHScript(np):to.getAddressFromP2SH(np));
The API of Bitcoin says the methods getAddressFromP2PKHScript() and getAddressFromP2SH() are deprecated, and I have not find suitable method.
However, P2SH means "Pay to Script Hash", which means it could contain two or more public keys to support multi-signature. Moreover, getAddressFromP2SH() returns only one address, perhaps this is the reason why it is deprecated.
I also wrote a convinient method to check the inputs and outputs of a block:
private void printCoinValueInOut(Block block) {
Coin blockInputSum = Coin.ZERO;
Coin blockOutputSum = Coin.ZERO;
System.out.println("--------------------Block["+block.getHashAsString()+"]------"+block.getPrevBlockHash()+"------------------------");
for(Transaction tx : block.getTransactions()) {
Coin txInputSum = tx.getOutputSum();
Coin txOutputSum = tx.getOutputSum();
blockInputSum = blockInputSum.add(txInputSum);
blockOutputSum = blockOutputSum.add(txOutputSum);
System.out.println("Tx["+tx.getTxId()+"]:\t" + txInputSum + "(satoshi) IN, " + txOutputSum + "(satoshi) OUT.");
}
System.out.println("Block total:\t" + blockInputSum + "(satoshi) IN, " + blockOutputSum + "(satoshi) OUT. \n");
}

How to check that frame does not contain jlabel with specific text with help of Assertj?

I want to test my simple application with AssertJ.
I can check that text is showing like that:
frame.label(JLabelMatcher.withText(text).andShowing());
But is there any way to check that specific text not showing?
As a result, I solved this issue in such a not pretty way:
public void iDontSeeText(String text) {
try {
frame.label(JLabelMatcher.withText(Pattern.compile(".*" + text + ".*", Pattern.CASE_INSENSITIVE)).andShowing());
} catch (Exception e) {
// Control isn't found. Test complete successful
return;
}
// Control is found. Execute exception
throw new RuntimeException("Text \"" + text + "\" is found in frame.");
}

Change album names using mp3agic

I wanted to loop through a folder containig .mp3 files and changing their album names (if they don't have one) to their title (e.g. Remix.mp3 with Title "Remix" gets the Album "Remix") using mp3agic.
This is my code so far:
if (mp3file.hasId3v1Tag()) {
ID3v1 id3v1Tag = mp3file.getId3v1Tag();
try {
if (id3v1Tag.getAlbum().equals("")) {
id3v1Tag.setAlbum(id3v1Tag.getTitle());
mp3file.save(SAVE_DIR + "\\" + child.getName());
System.out.println(SAVE_DIR + "/" + child.getName());
} else {
mp3file.save(SAVE_DIR + "/" + child.getName());
}
} catch (Exception e) {
mp3file.save(SAVE_DIR + "/" + child.getName());
}
}
I get the following error:
Exception in thread "main" com.mpatric.mp3agic.NotSupportedException: Packing Obselete frames is not supported
at com.mpatric.mp3agic.ID3v2ObseleteFrame.packFrame(ID3v2ObseleteFrame.java:32)
at com.mpatric.mp3agic.ID3v2Frame.toBytes(ID3v2Frame.java:83)
at com.mpatric.mp3agic.AbstractID3v2Tag.packSpecifiedFrames(AbstractID3v2Tag.java:275)
at com.mpatric.mp3agic.AbstractID3v2Tag.packFrames(AbstractID3v2Tag.java:261)
at com.mpatric.mp3agic.AbstractID3v2Tag.packTag(AbstractID3v2Tag.java:227)
at com.mpatric.mp3agic.AbstractID3v2Tag.toBytes(AbstractID3v2Tag.java:218)
at com.mpatric.mp3agic.Mp3File.save(Mp3File.java:450)
at de.thejetstream.main.Iterator.(Iterator.java:57)
at de.thejetstream.main.Main.main(Main.java:12)
at this file:
name: Feel Good in Black and Yellow.mp3
title: Feel Good in Black and Yellow (feat. Gorillaz & De La Soul)
album: Black and Yellow - Single
It crashes at line 57, which equals to the last save (in the catch).
What is the problem with this code? Is it just because the file uses an old kind of codec or something like this?
I found the solution:
The problem was that these files used ip3v2 tags instead of ip3v1. Simply checking which on it is and adjusting the code accordingly solved everything.

Parrot AR.Drone 2.0 - JavaDrone (Get the drone details E.G. Battery Level, Altitude, Speed etc)?

I am working on Parrot AR. Drone project. The libraries are downloaded and implemented in this project from JavaDrone website (https://code.google.com/p/javadrone/downloads/list). However, although I did included the all the correct libraries and make the right class call to get the method, it still cannot return me the correct information. All the results returned appeared to be "false". Any idea what happening on this code? Please help me :(
So what I did is I have 2 buttons : (i) connect (ii) take off buttons. The Connect button function is for establish connection to drone while Take off button is used for make the drone fly move a bit and return me the drone's NAV navigation data. Sadly all the returned NAV data appears not working.
Note : This code is working fine upon code compilation. But it just cannot return me the correct & valid NAV data from drone.
private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("Connect?");
drone = new ARDrone();
data = new NavData();
drone.playLED(10,10,10);
drone.connect();
drone.clearEmergencySignal();
System.err.println("Ready to connect!!");
// Wait until drone is ready
drone.waitForReady(CONNECT_TIMEOUT);
System.err.println("Drone State: " + drone.getState());
// do TRIM operation
drone.trim();
System.err.println("Congratulation! You have connected to Drone!");
System.out.println("You can issue flight commands now!");
batteryStatus.setText("0" + "%");
batteryStatus.setForeground(Color.ORANGE);
batteryStatus.setText("" + data.getBattery());
}
private void jButtonTakeOffActionPerformed(java.awt.event.ActionEvent evt) {
System.err.println("Current Drone State : " + drone.getState().toString());
System.err.println("Taking off");
drone.takeOff();
Thread.sleep(4000);
System.err.println("**********\nMOVE\n**********");
drone.move(0.0f, 150.5f, 500.0f, 0.0f);
Thread.sleep(1000);
System.err.println("******************************************");
System.err.println("Drone Infomation");
System.err.println("Battery Too High ? " + data.isBatteryTooHigh());
System.err.println("Battery Too Low ? " + data.isBatteryTooLow());
System.err.println("Drone Flying ? " + data.isFlying());
System.err.println("Control Received ? " + data.isControlReceived());
System.err.println("Motor Down ? " + data.isMotorsDown());
System.err.println("Not Enough Power ?" + data.isNotEnoughPower());
System.err.println("Trim Received ? " + data.isTrimReceived());
System.err.println("Trim Running? " + data.isTrimRunning());
System.err.println("Trim succeded? " + data.isTrimSucceeded());
System.err.println("PIC Number OK? "+ data.isPICVersionNumberOK());
System.err.println("******************************************");
Thread.sleep(5000);
drone.sendAllNavigationData();
drone.land();
}
Output :
******************************************
Drone Infomation
Battery Life: 0.0%
Battery Too High ? false
Battery Too Low ? false
Drone Flying ? false
Control Received ? false
Motor Down ? false
Not Enough Power ?false
Trim Received ? false
Trim Running? false
Trim succeded? false
PIC Number OK? false
********************************************
Update:
What I did was followed John's suggestion. I did implemented all the neccessary methods and NavDataListener for getting the NavData from drone.
import com.codeminders.ardrone.ARDrone;
import com.codeminders.ardrone.ARDrone.VideoChannel;
import com.codeminders.ardrone.NavData;
import com.codeminders.ardrone.NavDataListener;
public class arDrone extends javax.swing.JFrame implements Runnable, NavDataListener{
public ARDrone drone;
public NavData data = new NavData();
public arDrone(String text) {
//FreeTTS speech text
this.text=text;
}
public arDrone() {
initComponents();
setIcon();
initDrone();
}
private void initDrone() {
try {
drone = new ARDrone();
data = new NavData();
drone.addNavDataListener(this);
} catch (UnknownHostException ex) {
System.err.println(ex);
return;
}
}
public void navDataReceived(NavData nd) {
System.err.println("Testing navDataReceived is running...");
updateBatteryStatus(nd.getBattery());
this.flying.set(nd.isFlying());
}
private void updateBatteryStatus(final int value) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
batteryStatus.setText(value + "%");
if (value < 15) {
batteryStatus.setForeground(Color.RED);
} else if (value < 50) {
batteryStatus.setForeground(Color.ORANGE);
} else {
batteryStatus.setForeground(Color.GREEN);
}
}
});
}
The problem is that you are not doing anything to actually get navdata. You can't just create a NavData object and hope it gets filled in with valid data--It won't.
You need to use the com.codeminders.ardrone.NavDataListener interface.
Implement the NavDataListener interface, and the
navDataReceived method.
Add your listener using the ARDrone
method addNavDataListener.
In your navDataRecieved method
you will receive a NavData object with valid telemetry data.
Do you set the Drone IP address? According to sources the default IP for the drone is 192.168.1.1.
You can call another constructor to set the IP:
drone = new ARDrone(InetAddress.getByName("xxx.xxx.xxx.xxx"));
replace xxx.xxx.xxx.xxx with the actual drone IP.

Categories