I would like to know how to send a player a list of their shops when they type /shoplist. Also, I would like to know how to change the name of a shop depending on what they type so if they use /shopname Shop1 Pie it would change the name of Shop1 to pie. Or if they do not have a shop called shop1 then it would say a message if they don't have any shops when they make a shop then it builds a new section in the config for them.
Here is my main file:
public class Shops extends JavaPlugin implements Listener {
public void onEnable() {
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getLogger().info("*Shops Plugin Enabled *");
Bukkit.getServer().getLogger().info("*Shops by McMatt *");
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getPluginManager().registerEvents(new Signs(), this);
getConfig().options().copyDefaults(true);
saveConfig();
}
public void onDisable() {
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getLogger().info("*Shops Plugin Disabled *");
Bukkit.getServer().getLogger().info("*Shops by McMatt *");
Bukkit.getServer().getLogger().info("************************");
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("shops")) {
if (!(sender instanceof Player)) {
sender.sendMessage("You must be a player to run this command");
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("shops.shops")) {
player.sendMessage(ChatColor.RED + "You do not have to permission (shops.shops)");
return true;
} else {
player.sendMessage(ChatColor.GOLD + "Shops:");
player.sendMessage(ChatColor.RED + "---" + ChatColor.GOLD + "Commands" + ChatColor.RED + "---");
player.sendMessage(ChatColor.DARK_GREEN + "/shops" + ChatColor.GREEN + " Displays this");
player.sendMessage(ChatColor.DARK_GREEN + "/shopslist" + ChatColor.GREEN + " Used to list shops");
player.sendMessage(ChatColor.RED + "---" + ChatColor.GOLD + "Signs" + "---");
player.sendMessage(ChatColor.DARK_GREEN + "First line:" + ChatColor.GREEN + " [shop]");
player.sendMessage(ChatColor.DARK_GREEN + "Second line:" + ChatColor.GREEN + " {Open or Closed}");
}
}
return true;
}
public boolean onCommand1(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("shopslist")) {
sender.sendMessage("Getting shops info!");
sender.sendMessage(getConfig().getString("" + sender.getName()));
return true;
}
return false;
}
}
Here's my listener file
public class Signs implements Listener {
#EventHandler
public void onSignChange(SignChangeEvent e) {
if (e.getLine(0).equalsIgnoreCase("[shop]")) {
Block attached = e.getBlock().getRelative(0, -1, 0);
String name = e.getPlayer().getDisplayName();
if (!(attached.getType() == Material.CHEST))
e.getPlayer().sendMessage(ChatColor.RED + "Please place the shop on a chest!");
else {
if (!e.getPlayer().hasPermission("shops.create"))
e.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to create a shop! (shops.create)");
else {
if (!Arrays.asList("open", "closed").contains(e.getLine(1).toLowerCase())) {
e.getPlayer().sendMessage(ChatColor.RED + "You must specify if the shop is open or closed on the second line!");
} else {
boolean closed = true;
if ("open".equalsIgnoreCase(e.getLine(1))) {
closed = false;
}
String lineThree = closed ? "§cClosed" : "§aOpen";
e.setLine(3, lineThree);
e.setLine(0, "§9[Shop]");
e.setLine(1, "§b" + name + "'s");
e.setLine(2, "§bShop");
e.getPlayer().sendMessage(ChatColor.GREEN + "Shop Created!");
e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.LEVEL_UP, 10, 10);
//if(getConfig().equals(null)){
//int shopAmount = 0;
//shopAmount = shopAmount + 1;
//getConfig().createSection(name);
//getConfig().addDefault(name + ":.Shops:", "Shop" + shopAmount);
}
}
}
}
}
#EventHandler
public void onPlayerInteract(PlayerInteractEvent e) {
if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Player p = e.getPlayer();
Block b = e.getClickedBlock();
Material m = b.getType();
if (!(m == Material.SIGN_POST)) {
return;
} else {
Sign sign = (Sign) e.getClickedBlock().getState();
if ((sign.getLine(0).equalsIgnoreCase("§9[Shop]"))) {
if ((sign.getLine(3).equalsIgnoreCase("§aOpen"))) {
p.sendMessage("I opened the shop!");
}
}
}
}
}
}
And here's my configuration file
McMatt:
- Shop1
You could get the List<String> of all of the player's shops by using
config.getStringList(playerName);
So, for example, if your config looked like this:
McMatt:
- "Shop1"
- "Awesome Shop"
jojodmo:
- "Jojo Shop"
using
config.getStringList("McMatt");
Would return a List<String> containing the strings Shop1 and Awesome Shop.
Also, to avoid a NullPointerException, you should make sure the player has shops in the config by using
if(config.contains(playerName))
and send the player a message telling them that they have no shops.
So, your code could look something like this:
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
if(cmd.getName().equalsIgnoreCase("shops")){
//your code
if(sender instanceof Player){
Player player = (Player) sender;
String name = player.getName();
if(config.contains(name)){
List<String> shops = config.getStringList(name);
for(String shop : shops){
//do something with the shop
}
}
else{
//the user has no shops
}
}
//...
}
}
Related
I'm trying to make it so when someone with the role "Owner" types the mute command, it takes the person they #mentioned and gives them the "Muted" role.
The rest of the code works on it's own, the only part that is not working is the line
event.getGuild().addRoleToMember(member,event.getGuild().getRoleById(0)).complete();
and the variable "member" is defined by
Member member = event.getGuild().getMemberById(mentionid);
The full chunk of code is:
package radishmouse.FoodWorld.Events;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import radishmouse.FoodWorld.FoodWorld;
public class GuildMessageReceived extends ListenerAdapter {
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split("\\s+");
if (args[0].equalsIgnoreCase(FoodWorld.prefix + "mute")) {
if (hasRole("Owner", event)) {
if (args.length == 2) {
String mentionid = args[1].replace("<#!", "").replace(">", "");
Member member = event.getGuild().getMemberById(mentionid);
event.getGuild().addRoleToMember(member, event.getGuild().getRoleById(0)).complete();
EmbedBuilder msg = FoodWorld.sendMessage(null, "idk " + mentionid + member, "Blue");
event.getChannel().sendMessageEmbeds(msg.build()).queue();
}
else {
EmbedBuilder msg = FoodWorld.sendMessage("Specify Who To Mute", "Usage: " + FoodWorld.prefix + "mute [#mention who to mute]", "Blue");
event.getChannel().sendMessageEmbeds(msg.build()).queue();
}
}
}
/* If the bot ever sends a message, then add a ❌ reaction so users can delete that message */
if (event.getAuthor().equals(event.getJDA().getSelfUser())) {
event.getMessage().addReaction("❌").queue();
}
}
private boolean hasRole(String string, GuildMessageReceivedEvent event) {
Boolean toReturn = false;
for(int i=0; i < event.getMember().getRoles().size(); i++){
if("Owner".equals(event.getMember().getRoles().get(i).getName())){
toReturn = true;
}
}
return toReturn;
}
For reference, I'm following this tutorial on youtube: tutorial.
I'm not the most familiar with JDA and don't know how this would be done in an easier way.
Instead of parsing the string:
String mentionid = args[1].replace("<#!", "").replace(">", "");
Member member = event.getGuild().getMemberById(mentionid);
Use getMentionedMembers:
List<Member> mentions = event.getMessage().getMentionedMembers();
if (mentions.isEmpty()) {
EmbedBuilder msg = FoodWorld.sendMessage("Specify Who To Mute", "Usage: " + FoodWorld.prefix + "mute [#mention who to mute]", "Blue");
event.getChannel().sendMessageEmbeds(msg.build()).queue();
} else {
Member member = mentions.get(0);
event.getGuild().addRoleToMember(member, event.getGuild().getRoleById(0)).queue();
EmbedBuilder msg = FoodWorld.sendMessage(null, "idk " + member.getId() + member, "Blue");
event.getChannel().sendMessageEmbeds(msg.build()).queue();
}
I have two classes of DB in which there is a method "GetMoney" and Commands
In general, the point is that in the DB class I need to somehow get a player, or rather the sender of the command that is written in the Commands class. How can I do this?
//DB - GETMONEY
public int GetMoney(String name) throws Exception {
String tableName = this.plugin.getConfig().getString("tableName");
String dbNames = this.plugin.getConfig().getString("columnFirst");
String dbBalance = this.plugin.getConfig().getString("columnSecond");
Connection c = this.getConnection();
Statement s = c.createStatement();
ResultSet res = s.executeQuery("SELECT " + dbBalance +" FROM "+ tableName +" WHERE " + dbNames +" = '"+ name +"'" );
res.next();
return res.getInt(dbBalance);
}
//COMMANDS - onCommand
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = sender.getName();;
if(args.length == 0 ) {
String showBalance = this.plugin.getConfig().getString("messages.showBalance");
try {
int balance = this.database.GetMoney(name);
showBalance = showBalance.replace("&", "\u00a7").replace("_nm", name).replace("_bl", String.valueOf(balance));
sender.sendMessage(showBalance);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
I think passing Player interface is better than a simple name. First you have to make sure the sender is a Player not a ConsoleCommandSender. After this you can pass the Player and in the GetMoney() method you simply get the player's name with player.getName() method.
EDIT: I saw you need the command sender. You can pass it too instead of player just replace GetMoney parameter with CommandSender and delete instance check where we determine the sender is a player or not. After all you simply check it again wherever you want and cast it to Player again.
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
if (sender instanceof Player) {
Player player = (Player) sender;
String showBalance = this.plugin.getConfig().getString("messages.showBalance");
try {
int balance = this.database.GetMoney(player);
showBalance = showBalance.replace("&", "\u00a7").replace("_nm", player.getName()).replace("_bl", String.valueOf(balance));
sender.sendMessage(showBalance);
} catch (Exception e) {
e.printStackTrace();
}
} else {
sender.sendMessage("Player only command.");
}
}
return false;
}
//DB - Getmoney
public int GetMoney(Player player) throws Exception {
String tableName = this.plugin.getConfig().getString("tableName");
String dbNames = this.plugin.getConfig().getString("columnFirst");
String dbBalance = this.plugin.getConfig().getString("columnSecond");
Connection c = this.getConnection();
Statement s = c.createStatement();
ResultSet res = s.executeQuery("SELECT " + dbBalance +" FROM "+ tableName +" WHERE " + dbNames +" = '"+ player.getName() +"'" );
res.next();
return res.getInt(dbBalance);
}
I am not too familiar with polymorphism, and was wondering if I have it used in my code?
If this doesn't contain a polymorphic reference, could you lead me in a direction of where I would need to go? The files that the program is using are not included, as I am mainly curious about whether or not any polymorphic references are used.
java file 1 - this file runs the program
import java.util.Scanner;
public class ADTDemo {
ADTDictionary dictionary;
public static void menu() {
System.out.println("Welcome the Faculty Directory Program");
System.out.println(" Use commands:");
System.out.println(" list all");
System.out.println(" list DEPT_NAME");
System.out.println(" add DEPT_NAME, FIRST LAST");
System.out.println(" remove DEPT_NAME, FIRST LAST");
System.out.println(" exit");
}
public static void main(String[] args) {
menu();
String command;
ADTDemo dictObj = new ADTDemo();
dictObj.dictionary = new ADTDictionary();
dictObj.dictionary.read();
Scanner scanner = new Scanner(System.in);
do {
System.out.println("");
System.out.print(">>");
command = scanner.nextLine().trim();
if (!command.equals("exit")) {
dictObj.action(command);
} else {
dictObj.dictionary.saveEntries();
System.out.println("Goodbye! Have a nice day!");
}
} while (!command.equalsIgnoreCase("exit"));
}
public void action(String command) {
if (command.equalsIgnoreCase("LIST ALL")) {
dictionary.listAll();
return;
}
else if (command.toUpperCase().contains("LIST")) {
if (command.length() == 4){
System.out.println("Command needed.");
return;
}
command = command.substring(5, command.length());
dictionary.listDeptName(command);
return;
}
else if (command.toUpperCase().contains("ADD")) {
command = command.substring(4, command.length());
dictionary.add(command);
return;
}
else if (command.toUpperCase().contains("REMOVE")) {
command = command.substring(6, command.length());
dictionary.remove(command);
}
}
}
java file 2
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ADTDictionary {
Map<String, List<String>> adtDictionary;
public void read() {
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
Scanner departmentScanner = new Scanner(departmentFile);
Scanner facultyScanner = new Scanner(facultyFile);
adtDictionary = new HashMap<String, List<String>>();
while (departmentScanner.hasNextLine()) {
String department = departmentScanner.nextLine().trim();
adtDictionary.put(department, new ArrayList<String>());
}
while (facultyScanner.hasNextLine()) {
String faculty = facultyScanner.nextLine();
String[] values = faculty.split(",");
adtDictionary.get(values[1].trim()).add(values[0]);
}
} catch (FileNotFoundException ex) {
System.out.println("ERROR: File not found.");
}
}
public void listAll() {
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
System.out.println(value + ", " + key);
}
}
}
public void listDeptName(String department) {
if (null != adtDictionary.get(department)) {
for (String name : adtDictionary.get(department)) {
System.out.println(name);
}
}
else{
System.out.println("Unknown entry made.");
}
}
public void add(String value) {
if(!value.contains(",")){
System.out.println("Incorrect entry.");
return;
}
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
String[] facName = faculty.split(" ");
if (!(facName.length == 2)){
System.out.println("Please only enter First and Last name of faculty member.");
return;
}
if (!(null != adtDictionary.get(dept))) {
if(adtDictionary.containsKey(dept.toUpperCase())){
System.out.println("Incorrect departtment entry.");
return;
}
else if (dept == dept.toUpperCase()){
adtDictionary.put(dept, new ArrayList<String>());
}
else{
System.out.println("Incorrect department entry.");
return;
}
}
for (String name : adtDictionary.get(dept)) {
if (name.equalsIgnoreCase(faculty)) {
System.out.println("Cannot add " + name + " to " + dept + " because they already exist there.");
return;
}
}
adtDictionary.get(dept).add(faculty);
System.out.println("OK, added " + faculty);
}
public void remove(String value) {
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
adtDictionary.get(dept).remove(faculty);
System.out.println("OK, removed " + faculty + " from " + dept);
}
public void saveEntries(){
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
PrintWriter facWriter = new PrintWriter(facultyFile);
PrintWriter deptWriter = new PrintWriter(departmentFile);
for (Object s : adtDictionary.keySet()) {
deptWriter.println(s);
}
deptWriter.close();
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
facWriter.println(value + ", " + key);
}
}
facWriter.close();
}
catch (IOException ex){
System.out.println("ERROR saving file.");
}
}
}
public static void addToUserList(User newUser){
boolean hasFound = false;
for (User user : users) {
if(user.getUserID() == newUser.getUserID()){
System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
hasFound = true;
break;
}
}
if(hasFound = false){
users.add(newUser);
}
}
How do I refactor this code? In users arraylist, there shouldn't be duplicate users by ID.
I think using boolean variable is a bit unnecessary but I couldn't find any better solution.
P.Ss: Also if there is a convenion for these kind of coding styles, can you provide a name? Thank you.
You don't need the boolean, just return from the method if the user exists.
public static void addToUserList(User newUser){
for (User user : users) {
if(user.getUserID() == newUser.getUserID()){
System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
return;
}
}
users.add(newUser);
}
please try with this.Change the == in first if to != like below and remove the last part
public static void addToUserList(User newUser){
boolean hasFound = false;
for (User user : users) {
if(user.getUserID() != newUser.getUserID()){
users.add(newUser);
}
else{
System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
}
}
}
As I was coding, I tested my plugin and this seemed to happen:
basically, when a player kills another player, his kill count goes up by one. However, when a player has for instance 5 kills, so will all the other players. Here is my code:
public class KillDeathCounter extends JavaPlugin {
public void onEnable() {
new PlayerListener(this);
getLogger().info("Players will not be able to kit spam.");
this.getConfig().addDefault("playerkills", 0);
this.getConfig().addDefault("playerdeaths", 0);
this.getConfig().options().copyDefaults(true);
saveConfig();
}
public void onDisable() {
getLogger().info("Kill Death Counter has been disabled.");
saveConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (cmd.getName().equalsIgnoreCase("digipvp")) {
Player p = (Player) sender;
p.sendMessage(ChatColor.AQUA
+ "Our PVP plugin was developed by Pierre Lichtlé, the owner, also known as Master Digi."
+ " If you would like to contact him for a plugin, send him an email at developer.petlamb#gmail.com."
+ " Thanks for playing on our server!");
return true;
}
return false;
}
}
package me.katsunicalis.plugin;
import org.bukkit.ChatColor;
import org.bukkit.Statistic;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
public class PlayerListener implements Listener {
KillDeathCounter kdc;
public PlayerListener(KillDeathCounter plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
kdc = plugin;
}
#EventHandler
public void playerKillsPlayer(EntityDeathEvent e) {
Entity deade = e.getEntity();
Entity killer = e.getEntity().getKiller();
if (killer instanceof Player && deade instanceof Player){
int kills = kdc.getConfig().getInt("playerkills");
int deaths = kdc.getConfig().getInt("playerdeaths");
kdc.getConfig().set("playerkills", kills += 1);
kdc.getConfig().set("playerdeaths", deaths += 1);
killer.sendMessage("You now have " + kills + " kills!");
deade.sendMessage("You now have " + deaths + " deaths!");
}
}
}
Thanks very much guys! :)
The problem is that you're increasing the same variable for every time a player kills another player. To fix this, you should use a different variable for each player, for example "kills.playerUUIDHere" and "deaths.playerUUIDHere".
To get a player's UUID, you can use player.getUniqueId(), then to get the String representation of the UUID, you could use uuid.toString(). So, you could do something like this to change a player's kills:
String uuid = player.getUniqueId().toString();
int kills = kdc.getConfig().getInt("playerkills." + uuid);
kdc.getConfig().set("playerkills." + uuid, kills += 1);
The same logic can be used for deaths, so, you could use something like this for your playerKillsPlayer() method:
#EventHandler
public void playerKillsPlayer(EntityDeathEvent e) {
Entity dead = e.getEntity();
Entity killer = e.getEntity().getKiller();
if(killer instanceof Player && dead instanceof Player){
String killerUUID = ((Player) killer).getUniqueId().toString();
String deadUUID = ((Player) dead).getUniqueId().toString();
int kills = kdc.getConfig().getInt("playerkills." + killerUUID);
int deaths = kdc.getConfig().getInt("playerdeaths." + deadUUID);
kdc.getConfig().set("playerkills." + killerUUID + , kills += 1);
kdc.getConfig().set("playerdeaths." + deadUUID, deaths += 1);
killer.sendMessage("You now have " + kills + " kills!");
dead.sendMessage("You now have " + deaths + " deaths!");
}
}