Exemplo n.º 1
0
  @Override
  public void execute(final MessageEvent event, final String[] args) {
    User sender = event.getUser();
    Channel channel = event.getChannel();

    if (!System.getProperty("os.name").toLowerCase().contains("win")) {
      try {
        int unixTime =
            Integer.parseInt(
                new Scanner(new FileInputStream("/proc/uptime"))
                    .next()
                    .replaceAll("\\.[0-9]+", ""));
        int day = (int) TimeUnit.SECONDS.toDays(unixTime);
        long hours = TimeUnit.SECONDS.toHours(unixTime) - (day * 24);
        long minute =
            TimeUnit.SECONDS.toMinutes(unixTime) - (TimeUnit.SECONDS.toHours(unixTime) * 60);
        long seconds =
            TimeUnit.SECONDS.toSeconds(unixTime) - (TimeUnit.SECONDS.toMinutes(unixTime) * 60);

        channel
            .send()
            .message(
                Utils.colourise(
                    String.format(
                        "&2System uptime: &r%s days %s hours %s minutes %s seconds",
                        day, hours, minute, seconds)));
      } catch (FileNotFoundException ex) {
        sender.send().notice("File \"/proc/uptime\" not found. Are you sure you're using Linux?");
      }
      return;
    }
    sender.send().notice("This command is only supported on Unix based systems.");
  }
  @Test
  public void testAddOnPrivateChatMessageListener() throws Exception {
    CompletableFuture<String> usernameFuture = new CompletableFuture<>();
    CompletableFuture<ChatMessage> chatMessageFuture = new CompletableFuture<>();
    instance.addOnPrivateChatMessageListener(
        (username, chatMessage) -> {
          usernameFuture.complete(username);
          chatMessageFuture.complete(chatMessage);
        });

    String message = "private message";

    User user = mock(User.class);
    when(user.getNick()).thenReturn(chatUser1.getUsername());

    Channel channel = mock(Channel.class);
    when(channel.getName()).thenReturn(DEFAULT_CHANNEL_NAME);

    UserHostmask userHostMask = mock(UserHostmask.class);
    instance.onEvent(new PrivateMessageEvent(pircBotX, userHostMask, user, message));

    assertThat(chatMessageFuture.get().getMessage(), is(message));
    assertThat(chatMessageFuture.get().getUsername(), is(chatUser1.getUsername()));
    assertThat(
        chatMessageFuture.get().getTime(),
        is(greaterThan(Instant.ofEpochMilli(System.currentTimeMillis() - 1000))));
    assertThat(chatMessageFuture.get().isAction(), is(false));
  }
Exemplo n.º 3
0
  public void addKick(Channel channel, User target, String reason, User kicker, long time) {
    this.reconnect();

    PreparedStatement statement = null;

    try {
      connection.setAutoCommit(false);
      statement =
          connection.prepareStatement(
              "INSERT INTO kicks (channel, target, hostmask, reason, kicker, kick_time) VALUES (?, ?, ?, ?, ?, ?);");
      statement.setString(1, channel.getName());
      statement.setString(2, target.getNick());
      statement.setString(3, target.getHostmask());
      statement.setString(4, reason);
      statement.setString(5, kicker.getNick());
      statement.setLong(6, time);
      statement.executeUpdate();
      connection.commit();
    } catch (SQLException ex) {
      Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (statement != null) {
          statement.close();
        }
        if (connection != null) {
          connection.close();
          connection = null;
        }
      } catch (SQLException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemplo n.º 4
0
  @Override
  public String run(String[] params, Event<SlyBot> event) {
    int max = 100;
    int min = 0;
    long num;
    Random r = new Random();

    try {
      switch (params.length) {
        case 1:
          break;
        case 2:
          if (params[1] != null && params[1] != "null") {
            max = Integer.parseInt(params[1]);
          }
          break;
        case 3:
          if (params[1] != null && params[2] != null) {
            min = Integer.parseInt(params[1]);
            max = Integer.parseInt(params[2]);
          }
          break;
        default:
          return randomizeList(event, params);
      }
    } catch (NumberFormatException e) {
      return randomizeList(event, params);
    }

    // Fix wrong order
    if (max < min) {
      int tempMax = max;
      max = min;
      min = tempMax;
    }

    num = r.nextInt(max - min) + min + 1;

    User user = null;
    if (event instanceof MessageEvent) user = ((MessageEvent) event).getUser();
    if (event instanceof PrivateMessageEvent) user = ((PrivateMessageEvent) event).getUser();

    event
        .getBot()
        .reply(
            event,
            user.getNick()
                + " rolls the dice ("
                + (max - min)
                + " side"
                + (max - min == 1 ? "" : "s")
                + ") and got... "
                + num
                + "!");

    return num + "";
  }
Exemplo n.º 5
0
  public void onMessage(MessageEvent<ShockyBot> event) {
    if (Data.isBlacklisted(event.getUser())) return;
    String msg = event.getMessage();
    if (!pattern.matcher(msg).find()) return;

    String chan = event.getChannel().getName();
    Long time = timers.get(chan);
    User s = started.get(chan);

    if (s != null && time != null && time < System.currentTimeMillis()) {
      started.remove(chan);
      timers.remove(chan);
      s = null;
    }

    if (s == null) {
      time = System.currentTimeMillis() + Data.forChannel(event.getChannel()).getInt("hf-maxtime");
      // event.respond(String.format("Will expired at %s",
      // DateFormat.getDateTimeInstance().format(new Date(time))));
      started.put(chan, event.getUser());
      timers.put(chan, time);
    } else {
      int stat = changeStat(s.getNick(), event.getUser().getNick(), 1);
      if (stat != 0) {
        if (event.getChannel().isOp(event.getBot().getUserBot())
            && stat >= Data.forChannel(event.getChannel()).getInt("hf-kickat")) {
          stat = changeStat(s.getNick(), event.getUser().getNick(), -stat);
          msg = s.getNick() + " o/ * \\o " + event.getUser().getNick() + " - have been kicked!";
          event.getBot().kick(event.getChannel(), s);
          event.getBot().kick(event.getChannel(), event.getUser());
          if (Data.forChannel(event.getChannel()).getBoolean("hf-announce"))
            Shocky.sendChannel(event.getBot(), event.getChannel(), msg);
          else {
            Shocky.sendNotice(event.getBot(), event.getUser(), msg);
            Shocky.sendNotice(event.getBot(), s, msg);
          }
        } else {
          msg =
              s.getNick()
                  + " o/ * \\o "
                  + event.getUser().getNick()
                  + " - "
                  + getOrderNumber(stat)
                  + " time";
          if (Data.forChannel(event.getChannel()).getBoolean("hf-announce"))
            Shocky.sendChannel(event.getBot(), event.getChannel(), msg);
          else {
            Shocky.sendNotice(event.getBot(), event.getUser(), msg);
            Shocky.sendNotice(event.getBot(), s, msg);
          }
        }

        started.remove(chan);
        timers.remove(chan);
      }
    }
  }
Exemplo n.º 6
0
  /** @param event */
  @Override
  public void onMode(ModeEvent event) {
    Channel channel = event.getChannel();
    String mode = event.getMode();
    User user = event.getUser();

    if (!ircBot.isValidChannel(channel.getName())) {
      ircBot.broadcastIRCMode(user.getNick(), mode, channel.getName());
    }
  }
Exemplo n.º 7
0
  public String randomizeList(Event<SlyBot> event, String[] params) {
    Random r = new Random();

    String result = params[r.nextInt(params.length - 1) + 1];

    User user = null;
    if (event instanceof MessageEvent) user = ((MessageEvent) event).getUser();
    if (event instanceof PrivateMessageEvent) user = ((PrivateMessageEvent) event).getUser();

    event
        .getBot()
        .reply(event, user.getNick() + " rolls a very special dice.. It shows \"" + result + "\"");
    return result;
  }
Exemplo n.º 8
0
 private static boolean hasPermission(PermissionLevel level, User user, Channel channel) {
   if (level == PermissionLevel.REGULAR) return true;
   else if (level == PermissionLevel.VOICE
       && channel != null
       && (channel.hasVoice(user) || channel.isOp(user) || channel.isSuperOp(user))) return true;
   else if (level == PermissionLevel.OPERATOR
       && channel != null
       && (channel.isOp(user) || channel.isSuperOp(user))) return true;
   else if (level == PermissionLevel.SUPER_OPERATOR
       && channel != null
       && (channel.isSuperOp(user))) return true;
   else if (level == PermissionLevel.BOT_ADMIN)
     return Arrays.asList(Config.admins).contains(user.getNick()) && user.isVerified();
   return false;
 }
Exemplo n.º 9
0
 @Override
 public void run() {
   for (User user : KGBot.getBot().getUsers(KGBot.getMainChannel())) {
     if (Users.isUser(user.getNick())) {
       Database.execute(
           "UPDATE "
               + Database.TABLE_USERS
               + " SET money = "
               + new SQLValue(MoneyMethods.getMoney(user.getNick()) + PAYDAY_RATE).getValue()
               + " WHERE username = "******"Payday! " + MoneyMethods.format(PAYDAY_RATE) + " added to everyone's account.");
 }
Exemplo n.º 10
0
  @Override
  public void execute(final MessageEvent event, final String[] args) {
    User sender = event.getUser();

    if (args.length == 1) {
      if (args[0].equalsIgnoreCase("list")) {
        List<String> tells = foxbot.getDatabase().getTells(sender.getNick(), true);

        if (!tells.isEmpty()) {
          for (String tell : tells) {
            foxbot.sendNotice(sender, Utils.colourise(tell));
          }
          return;
        }
        foxbot.sendNotice(sender, "No messages for you :<");
        return;
      }

      if (args[0].equalsIgnoreCase("clean")) {
        foxbot.getDatabase().cleanTells(sender.getNick());
        foxbot.sendNotice(sender, "Deleted all of your read messages.");
        return;
      }
    }

    if (args.length > 1) {
      String nick = args[0];

      StringBuilder message = new StringBuilder(args[1]);

      for (int arg = 2; arg < args.length; arg++) {
        message.append(" ").append(args[arg]);
      }

      foxbot.getDatabase().addTell(sender.getNick(), nick, message.toString());
      foxbot.sendNotice(sender, String.format("Tell added for %s", nick));
      return;
    }
    foxbot.sendNotice(
        sender,
        String.format(
            "Wrong number of args! Use %stell <nick> <message> or %stell list",
            foxbot.getConfig().getCommandPrefix(), foxbot.getConfig().getCommandPrefix()));
  }
  @Test
  public void testAddOnUserListListener() throws Exception {
    CompletableFuture<String> channelNameFuture = new CompletableFuture<>();
    CompletableFuture<Map<String, ChatUser>> usersFuture = new CompletableFuture<>();
    instance.addOnUserListListener(
        (channelName, users) -> {
          channelNameFuture.complete(channelName);
          usersFuture.complete(users);
        });
    when(chatPrefs.getChatColorMode()).thenReturn(chatColorMode.get());
    when(chatPrefs.getUserToColor()).thenReturn(userToColorProperty);

    when(user2.compareTo(user1)).thenReturn(1);
    ImmutableSortedSet<User> users = ImmutableSortedSet.of(user1, user2);
    instance.onEvent(new UserListEvent(pircBotX, defaultChannel, users, true));

    assertThat(channelNameFuture.get(TIMEOUT, TIMEOUT_UNIT), is(DEFAULT_CHANNEL_NAME));

    Map<String, ChatUser> userMap = usersFuture.get(TIMEOUT, TIMEOUT_UNIT);
    assertThat(userMap.values(), hasSize(2));
    assertThat(userMap.get(chatUser1.getUsername()), is(chatUser1));
    assertThat(userMap.get(chatUser2.getUsername()), is(chatUser2));
  }
Exemplo n.º 12
0
 public void sendAction(User target, String action) {
   sendAction(target.getNick(), action);
 }
Exemplo n.º 13
0
  @Override
  public void execute(MessageEvent event, String[] args) {
    User sender = event.getUser();
    Channel channel = event.getChannel();

    if (args.length > 0) {
      StringBuilder command = new StringBuilder();
      boolean verbose = args[0].equals("-v");

      for (int i = verbose ? 1 : 0; i < args.length; i++) {
        command.append(args[i]).append(" ");
      }

      try {
        Process proc = runtime.exec(command.toString());
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        // Prevent spam on long results
        int count = 0;
        String line;

        while ((line = stdInput.readLine()) != null) {
          if (!verbose && count >= 3) {
            channel.send().message("Max output reached. Use -v to show full output.");
            break;
          }

          if (!line.isEmpty()) {
            channel.send().message(line);
            count++;
          }
        }

        stdInput.close();

        while ((line = stdError.readLine()) != null) {
          if (!verbose && count >= 3) {
            channel.send().message("Max output reached. Use -v to show full output.");
            break;
          }

          if (!line.isEmpty()) {
            channel.send().message(line);
            count++;
          }
        }

        stdError.close();
        proc.destroy();
      } catch (IOException ex) {
        foxbot.getLogger().error("Error occurred while executing system command", ex);
      }

      return;
    }

    sender
        .send()
        .notice(
            String.format(
                "Wrong number of args! Use %ssystem [-v] <command>",
                foxbot.getConfig().getCommandPrefix()));
  }
Exemplo n.º 14
0
  @Override
  public void execute(MessageEvent event, String[] args) {
    User sender = event.getUser();
    Channel channel = event.getChannel();

    if (args.length > 0) {
      String plugin = args[0].toLowerCase();
      String url =
          String.format(
              "http://api.bukget.org/3/search/plugin_name/like/%s%s",
              plugin, (args.length) == 1 ? "" : ("?size=" + args[1]));

      Connection conn =
          Jsoup.connect(url).timeout(500).followRedirects(true).ignoreContentType(true);
      String json;

      try {
        json = conn.get().text();
      } catch (IOException ex) {
        foxbot.log(ex);
        channel
            .send()
            .message(
                Utils.colourise(
                    String.format(
                        "(%s) &cAn error occurred while querying the Bukget API!",
                        Utils.munge(sender.getNick()))));
        return;
      }

      if (json.equals("[]")) {
        channel
            .send()
            .message(
                Utils.colourise(
                    String.format("(%s) &cNo results found!", Utils.munge(sender.getNick()))));
        return;
      }

      JSONArray jsonArray = new JSONArray(json);
      JSONObject found = null;

      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        String name = jsonObject.getString("plugin_name");

        if (name.equalsIgnoreCase(plugin)) {
          found = jsonObject;
          break;
        }
      }

      if (found == null) {
        found = jsonArray.getJSONObject(0);
      }

      String name = found.getString("plugin_name");
      String description = found.getString("description");
      String pluginUrl =
          String.format("http://dev.bukkit.org/bukkit-plugins/%s/", found.getString("slug"));

      if (description.isEmpty()) {
        description = "No description";
      }

      channel
          .send()
          .message(
              Utils.colourise(
                  String.format(
                      "(%s) &2Name:&r %s &2Description:&r %s &2URL:&r %s",
                      Utils.munge(sender.getNick()), name, description, pluginUrl)));
      return;
    }
    foxbot.sendNotice(
        sender,
        String.format(
            "Wrong number of args! Use %sbukkitsearch <plugin>",
            foxbot.getConfig().getCommandPrefix()));
  }
  @Before
  public void setUp() throws Exception {
    instance = new PircBotXChatService();
    instance.fafService = fafService;
    instance.userService = userService;
    instance.taskService = taskService;
    instance.i18n = i18n;
    instance.pircBotXFactory = pircBotXFactory;
    instance.preferencesService = preferencesService;
    instance.executorService = executorService;

    chatUser1 = new ChatUser("chatUser1", null);
    chatUser2 = new ChatUser("chatUser2", null);
    loggedInProperty = new SimpleBooleanProperty();

    botShutdownLatch = new CountDownLatch(1);

    userToColorProperty = new SimpleMapProperty<>(FXCollections.observableHashMap());
    chatColorMode = new SimpleObjectProperty<>(CUSTOM);

    when(userService.getUsername()).thenReturn(CHAT_USER_NAME);
    when(userService.getPassword()).thenReturn(CHAT_PASSWORD);
    when(userService.loggedInProperty()).thenReturn(loggedInProperty);

    when(user1.getNick()).thenReturn(chatUser1.getUsername());
    when(user1.getChannels()).thenReturn(ImmutableSortedSet.of(defaultChannel));
    when(user1.getUserLevels(defaultChannel)).thenReturn(ImmutableSortedSet.of(UserLevel.VOICE));

    when(user2.getNick()).thenReturn(chatUser2.getUsername());
    when(user2.getChannels()).thenReturn(ImmutableSortedSet.of(defaultChannel));
    when(user2.getUserLevels(defaultChannel)).thenReturn(ImmutableSortedSet.of(UserLevel.VOICE));

    when(defaultChannel.getName()).thenReturn(DEFAULT_CHANNEL_NAME);
    when(pircBotX.getConfiguration()).thenReturn(configuration);
    when(pircBotX.sendIRC()).thenReturn(outputIrc);
    when(pircBotX.getUserChannelDao()).thenReturn(userChannelDao);

    doAnswer(
            invocation -> {
              CompletableFuture<Object> future = new CompletableFuture<>();
              WaitForAsyncUtils.async(
                  () -> {
                    invocation.getArgumentAt(0, Task.class).run();
                    future.complete(null);
                  });
              return future;
            })
        .when(executorService)
        .submit(any(Task.class));

    botStartedFuture = new CompletableFuture<>();
    doAnswer(
            invocation -> {
              botStartedFuture.complete(true);
              botShutdownLatch.await();
              return null;
            })
        .when(pircBotX)
        .startBot();

    when(pircBotXFactory.createPircBotX(any())).thenReturn(pircBotX);
    when(configuration.getListenerManager()).thenReturn(listenerManager);

    instance.ircHost = LOOPBACK_ADDRESS.getHostAddress();
    instance.ircPort = IRC_SERVER_PORT;
    instance.defaultChannelName = DEFAULT_CHANNEL_NAME;
    instance.reconnectDelay = 100;

    when(preferencesService.getPreferences()).thenReturn(preferences);
    when(preferences.getChat()).thenReturn(chatPrefs);

    when(chatPrefs.userToColorProperty()).thenReturn(userToColorProperty);
    when(chatPrefs.chatColorModeProperty()).thenReturn(chatColorMode);

    instance.postConstruct();
  }
Exemplo n.º 16
0
 public void sendNotice(User target, String action) {
   sendNotice(target.getNick(), action);
 }
Exemplo n.º 17
0
 public void sendMessage(Channel target, User user, String message) {
   sendMessage(target.getName(), user.getNick() + ": " + message);
 }
Exemplo n.º 18
0
 public void sendMessage(User target, String message) {
   sendMessage(target.getNick(), message);
 }