💰 TimeIsMoney API 4.1/5.0 💰

TimeIsMoney
First of all i know that “TimeIsMoney” name is really bad :confounded:
this is my first plugin (yeeey :grin:) and i made this for @Jinlin_Chen 's plugin request

this is the link for downloading the plugin:

https://ore-staging.spongepowered.org/ZpknTr/TimeIsMoney

In this plugin;
-There is NO COMMANDS, :confused:
-NO PERMISSIONS
 :scream:
-this plugin gives X amount of money :money_mouth:
-every Y seconds to all players :ghost:
-and players can’t get more than Z amount per day
 :spy:
-daily logs are in config\TimeIsMoneyLogs directory
 :floppy_disk:
-ALSO this plugin doesn’t need reload, just change timeismoney.conf file and it will take all new variables directly


Finally im just a beginner :disappointed_relieved: in plugin making but if u need anything, comment here and i will try to make it
 :slight_smile:

3 Likes

got src?


i dont have a github yet, so this is the only java file


package ZpknTr;

import com.google.inject.Inject;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.spongepowered.api.Game;
import org.spongepowered.api.config.DefaultConfig;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.event.game.state.GameStoppingServerEvent;
import org.spongepowered.api.event.service.ChangeServiceProviderEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.service.economy.EconomyService;
import org.spongepowered.api.service.economy.account.UniqueAccount;

import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


import java.util.logging.Logger;

/**
 * Created by zpkn on 18.8.2016.
 */
@Plugin(id="timeismoney", name="TimeIsMoney", version="1.0")
public class TimeIsMoney {
    @Inject
    private Logger getLogger()
    {
        return logger;
    }
    private int counter=0;
    private int ginterval=10;
    private int greward;
    public static int money;
    public static int glimit;
    public static String limitfcom;
    public static String earnedmoney;
    private String grewardmessage;
    private String glimitreached;
    public static String tamad;
    String path;
    private EconomyService economyService;
    @Listener
    public void onChangeServiceProvider(ChangeServiceProviderEvent event) {
        if (event.getService().equals(EconomyService.class)) {
            economyService = (EconomyService) event.getNewProviderRegistration().getProvider();
        }
    }
    @Inject
    Game game;
    @Inject
    Logger logger;

    @Inject
    @DefaultConfig(sharedRoot = true)
    public File configuration = null;

    @Inject
    @DefaultConfig(sharedRoot = true)
    public ConfigurationLoader<CommentedConfigurationNode> configurationLoader = null;

    public CommentedConfigurationNode configurationNode = null;
    Timer timer = new Timer();

    @Listener
    public void onInit(GameStoppingServerEvent e){
        getLogger().info("Stopping:TimeIsMoney... TIM is made by ZpknTr");
        timer.cancel();
    }

    @Listener
    public void onInit(GameInitializationEvent e){
        getLogger().info("Loading:TimeIsMoney... TIM is made by ZpknTr");
        try {
            if (!configuration.exists()) {
                configuration.createNewFile();
                configurationNode = configurationLoader.load();
                configurationNode.getNode("Variables").setComment("These are the actual values.");
                configurationNode.getNode("Variables","IntervalInSeconds").setValue(60);
                configurationNode.getNode("Variables","Reward").setValue(20);
                configurationNode.getNode("Variables","DailyLimit").setValue(2400);
                configurationNode.getNode("WarningMsg").setComment("These are the messages.");
                configurationNode.getNode("WarningMsg","RewardMessage").setValue("Reward given for being online: ");
                configurationNode.getNode("WarningMsg","LimitReached").setValue("You have reached daily reward limit.");
                configurationNode.getNode("WarningMsg","LimitForCommand").setValue("Today's reward limit is: ");
                configurationNode.getNode("WarningMsg","EarnedMoney").setValue("You have earned: ");
                configurationLoader.save(configurationNode);
            }
            configurationNode = configurationLoader.load();
            ginterval = configurationNode.getNode("Variables","IntervalInSeconds").getInt();
            greward = configurationNode.getNode("Variables","Reward").getInt();
            glimit = configurationNode.getNode("Variables","DailyLimit").getInt();
            grewardmessage=configurationNode.getNode("WarningMsg","RewardMessage").getString();
            glimitreached = configurationNode.getNode("WarningMsg","LimitReached").getString();
            limitfcom = configurationNode.getNode("WarningMsg","LimitForCommand").getString();
            earnedmoney = configurationNode.getNode("WarningMsg","EarnedMoney").getString();
            configurationNode =configurationLoader.load();
        }catch(IOException exception){
                exception.printStackTrace();
            }
        path = configuration.getAbsolutePath();
        path= path.substring(0,path.length()-17);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    if (configuration.exists()) {
                        configurationNode = configurationLoader.load();
                        ginterval = configurationNode.getNode("Variables", "IntervalInSeconds").getInt();
                        greward = configurationNode.getNode("Variables", "Reward").getInt();
                        glimit = configurationNode.getNode("Variables", "DailyLimit").getInt();
                        grewardmessage = configurationNode.getNode("WarningMsg", "RewardMessage").getString();
                        glimitreached = configurationNode.getNode("WarningMsg", "LimitReached").getString();
                        limitfcom = configurationNode.getNode("WarningMsg", "LimitForCommand").getString();
                        earnedmoney = configurationNode.getNode("WarningMsg", "EarnedMoney").getString();
                        configurationNode = configurationLoader.load();
                    }
                }catch(IOException exception){
                    exception.printStackTrace();
                }
                if (counter>=ginterval) {
                    counter = 0;
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
                    Date date = new Date();
                    String tarih = dateFormat.format(date); //2014/08/06 15:59:48
                    tamad = Text.of(path, "\\TimeIsMoneyLogs\\", tarih, ".log").toPlain();
                    File theDir = new File(Text.of(path, "\\TimeIsMoneyLogs").toPlain());
// if the directory does not exist, create it
                    if (!theDir.exists()) {

                        try {
                            theDir.mkdir();
                        } catch (SecurityException se) {
                            //handle it
                            se.printStackTrace();
                        }
                    }
                    File f = new File(tamad);
                    if (!f.exists() && !f.isDirectory()) {
                        File file = new File(tamad);
                        FileWriter writer;
                        try {
                            writer = new FileWriter(file, true);
                            PrintWriter printer = new PrintWriter(writer);
                            printer.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    Boolean testingflag = false;
                    Integer moneyb = 0;
                    money = 0;
                    String line;
                    Integer kayitlinerow = 0;
                    List<String> kayit = new ArrayList<String>();
                    Integer linerow = 0;
                    for (Player player : game.getServer().getOnlinePlayers()) {
                        if (player != null) {
                            BufferedReader fr;
                            try {
                                fr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(tamad))));
                                kayit.clear();
                                String aname;
                                testingflag = false;
                                linerow = 0;
                                while ((line = fr.readLine()) != null) {
                                    kayit.add(linerow, line);
                                    String[] parts = line.split(" ");
                                    aname = parts[0]; // 004
                                    moneyb = Integer.parseInt(parts[1]); // 034556
                                    if (Objects.equals(aname, player.getName())) {
                                        testingflag = true;
                                        money = moneyb;
                                        kayitlinerow = linerow;
                                    }
                                    linerow += 1;
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (testingflag) {
                                if (glimit > money) {
                                    if (money + greward > glimit) {
                                        long x = glimit - money;
                                        Optional<UniqueAccount> uOpt = economyService.getOrCreateAccount(player.getUniqueId());
                                        if (uOpt.isPresent()) {
                                            UniqueAccount acc = uOpt.get();
                                            acc.deposit(economyService.getDefaultCurrency(), BigDecimal.valueOf(x), Cause.source(this).build());
                                        }
                                        player.sendMessage(Text.of(TextColors.GREEN, grewardmessage, TextColors.GOLD, x, economyService.getDefaultCurrency().getSymbol()));
                                        player.sendMessage(Text.of(TextColors.GREEN, earnedmoney, TextColors.GOLD, money));
                                        player.sendMessage(Text.of(TextColors.BLUE, glimitreached));
                                        File file = new File(tamad);
                                        FileWriter writer;
                                        try {

                                            writer = new FileWriter(file, false);
                                            PrintWriter printer = new PrintWriter(writer);
                                            for (int i = 0; i < linerow; i++) {
                                                if (i == kayitlinerow) {
                                                    printer.println(Text.of(player.getName(), " ", glimit).toPlain());
                                                } else {
                                                    printer.println(kayit.get(i));
                                                }
                                            }
                                            printer.close();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    } else {
                                        Optional<UniqueAccount> uOpt = economyService.getOrCreateAccount(player.getUniqueId());
                                        if (uOpt.isPresent()) {
                                            UniqueAccount acc = uOpt.get();
                                            long x = greward;
                                            acc.deposit(economyService.getDefaultCurrency(), BigDecimal.valueOf(x), Cause.source(this).build());
                                        }
                                        player.sendMessage(Text.of(TextColors.GREEN, grewardmessage, TextColors.GOLD, greward, economyService.getDefaultCurrency().getSymbol()));
                                        player.sendMessage(Text.of(TextColors.GREEN, earnedmoney, TextColors.GOLD, money));
                                        player.sendMessage(Text.of(TextColors.BLUE, limitfcom, TextColors.GOLD, glimit));
                                        File file = new File(tamad);
                                        FileWriter writer;
                                        try {
                                            writer = new FileWriter(file, false);
                                            PrintWriter printer = new PrintWriter(writer);
                                            for (int i = 0; i < linerow; i++) {
                                                if (i == kayitlinerow) {
                                                    printer.println(Text.of(player.getName(), " ", (money + greward)).toPlain());
                                                } else {
                                                    printer.println(kayit.get(i));
                                                }
                                            }
                                            printer.close();
                                        } catch (IOException e) {

                                            e.printStackTrace();
                                        }
                                    }
                                }

                            } else {
                                Optional<UniqueAccount> uOpt = economyService.getOrCreateAccount(player.getUniqueId());
                                if (uOpt.isPresent()) {
                                    UniqueAccount acc = uOpt.get();
                                    long x = greward;
                                    acc.deposit(economyService.getDefaultCurrency(), BigDecimal.valueOf(x), Cause.source(this).build());
                                }
                                player.sendMessage(Text.of(TextColors.GREEN, grewardmessage, TextColors.GOLD, greward, economyService.getDefaultCurrency().getSymbol()));
                                player.sendMessage(Text.of(TextColors.GREEN, earnedmoney, TextColors.GOLD, money));
                                player.sendMessage(Text.of(TextColors.BLUE, limitfcom, TextColors.GOLD, glimit));
                                File file = new File(tamad);
                                FileWriter writer;
                                try {
                                    writer = new FileWriter(file, true);
                                    PrintWriter printer = new PrintWriter(writer);
                                    printer.append(Text.of(player.getName(), " ", greward).toPlain());
                                    printer.close();
                                } catch (IOException e) {

                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }else {
                    counter+=1;
                }
            }
        }, 1000, 1000);
    }
}

its too complicated if u are looking for something i can tell u


Ah
 I assume you were responding to the plugin request thread for this very thing. I had a project almost entirely done for the same thing.

I have a few comments on this, click to view.

Comments
  • The @Inject on getLogger(), is unnecessary, as nothing is actually injected.
  • It’s a bad idea to use * imports (but that’s just a personal thing).
  • While java.util.logging.Logger technically works, the intended class is org.slf4j.Logger.
  • Rather than checking the service providers, usually people just get the service from the ServiceManager whenever they need it. No need to store it in a global variable anyway.
  • You shouldn’t initialize injected variables with null. Just leave them undefined.
  • No need to put load and unload log messages either, since Sponge does that automatically.
  • Paths and java.nio are recommended over Files and java.io for Configurate operations.
  • If you’ve injected the ConfigurationLoader, the configuration will always exists(). What I usually do is put a version node in the file, and check if it isVirtual().
  • The HOCON spec defines key names as being all lowercase, and hyphen separated. Again, though, this is a personal thing. Doesn’t directly break anything.
  • The Timer class is not recommended in Sponge, as it won’t be on the main thread. Instead, Task is recommended.
  • I would definitely not recommend doing an IO operation so often. Instead, cache the root node in a variable (like you are doing), and load it again on GameReloadEvent.
  • It’s not recommended to find paths yourself. If you use sharedRoot = false in your @DefaultConfig, a new folder will be created for your plugin in config, containing your config file, rather than the file being in the root of config. You can then get the folder with @Inject @ConfigDir(sharedRoot = false).
  • Any time you are creating files, they return a boolean. A creation failure won’t always throw an exception; if it returns false, it failed.
  • I am confused as to why you are creating Text objects, just to call toPlain(). Why not just do tamad = path + "\\TimeIsMoneyLogs\\" + tarih + ".log"?
  • You should probably use primitive types like boolean and int instead of class wrappers like Boolean and Integer. If they’re never intended to be null, the extra memory makes no sense.
  • Don’t just use the number and the symbol. Currencies have a method format that takes the BigDecimal and returns Text, so that the economy plugin can define a custom way of displaying it.
  • Important: Don’t store economy values in int. Ever. Store them in BigDecimal if possible, since it has infinite capacity, but if you find yourself needing to use a primitive, use double or float, since int will remove the decimal point, and custom currencies may really need that fractional component.
  • Tip: try (PrintWriter printer = new PrintWriter(new FileWriter(file, false))) { Called ‘try with resources’, it applies to anything implementing AutoCloseable, and automatically closes streams (like the PrintWriter, for example).
4 Likes

WOW :scream:
is this a comment or are u actually teaching me :grinning:
Thank you so much :slight_smile:
Actually i tried some different things in this plugin
 Since its my first try though

Thats why there are some unnecessary things like global defining etc.
(i tried to make a command but idk why i failed)
But i will try to do these on my next project :relaxed:

I want to learn about to set a permission for plugin default true
Could u link any simple example please :neutral_face:

Thx again for these invaluable information :relaxed:

PS: im just trying to learn and nevermind just release your project :slight_smile:
cuz this is just a little help for a friend there are still good plugin needs for sponge


im gonna sleep now

im awake for at least 42 hours and my eyes closing slowly


But!!! I will ask u if i cant do these optimizations
 Cuz my english is not that good
 i couldn’t understand some of those 

See u later and idk if its night or not in there but Good Night
 :sleeping:

Hi! Thanks for your help! I trust you have developed a very useful and necessary plugin for many people!:smiley:

thx :slight_smile: im working on a different project now

SellToServerCommand which i hope will let server ops to allow or disable players to sell or buy items directly from the server
 :slight_smile:
Also its usefull if ppl would use it with sign command plugins to make a shop in servers


(i want to add some little options like adjusting items worth with buy/sell rates
)

Great idea! Wish you early success.

There is a flaw that the plugin doesn’t remind the player for money payment at last time.

u are right i just found out that i made that part wrong
im fixing it now

i just fixed it
 i updated the link


Thank you very much.:grinning:

Hi is it possible to make working jar for 1.8.9?

im on it

(i didnt think someone will want to download this :smile: )

You really shouldn’t use MediaFire since they have a lot of ads, most of which are malicious. Sponge has a plugin-hosting system called Ore, or you could use GitHub Releases.

2 Likes

thx :slight_smile: i will


too many smilies
 too much happy
 bahhh


3 Likes

learning anything about coding makes me happy :smiley:
and whats wrong with being a joyfull person :yum:

2 Likes