Jump to content

Recommended Posts

Posted (edited)

Hey guys i was fooling arround with this one and decided to share it with you , i didnt test it on live server.  It might have some issues feel free to point them out so i can fix them.

 

It shows the 5 latest news posts, on every restart it clears the oldests and it keeps the 5 recent.

 

Requirements : Your own .menu + custom menu command handlers <-- i made a share for that.

 

If you don't have custom menu command handlers you can either trigger it with another custom command handler like .news or use the on enter server show news html that is included on acis (i dont know about other projects).

 

credits : me

 

58d65eb051901cb03abdf89eb226eadc.png.7294587b352e71efe3a711054d37e3fb.png

 

9fe144a6390f4fe92af8ff96de90b580.png.6ff178bc31ad28970a8b14c97142b07b.png

 

AdminNews.java

package net.sf.l2j.gameserver.handler.admincommandhandlers;

import net.sf.l2j.gameserver.custom.usermenu.menuhandlers.NewsHandler;
import net.sf.l2j.gameserver.handler.IAdminCommandHandler;
import net.sf.l2j.gameserver.model.actor.instance.Player;

/**
 * @author LordPanic
 *
 */
public class AdminNews implements IAdminCommandHandler
{

	private static final String[] ADMIN_COMMANDS =
	{
		"admin_news"
	};
	
	@Override
	public boolean useAdminCommand(String command, Player activeChar)
	{
		if (command.equals("admin_news"))
	       {
				NewsHandler.adminNewsWindow(activeChar);
	       }
		return false;
	}

	
	
	
	@Override
	public String[] getAdminCommandList()
	{
		
		return ADMIN_COMMANDS;
	}
	
}

 

AdminCommandHandler.java

+registerAdminCommandHandler(new AdminNews());

 

NewsHandler.java

package net.sf.l2j.gameserver.custom.usermenu.menuhandlers;
 
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
 
 
import net.sf.l2j.L2DatabaseFactory;
import net.sf.l2j.gameserver.model.WorldObject;
import net.sf.l2j.gameserver.model.actor.instance.Player;
import net.sf.l2j.gameserver.network.clientpackets.Say2;
import net.sf.l2j.gameserver.network.serverpackets.CreatureSay;
import net.sf.l2j.gameserver.network.serverpackets.NpcHtmlMessage;
import net.sf.l2j.gameserver.util.Broadcast;


 
/**
 * @author LordPanic
 * 
 */
public class NewsHandler
{	

private final List<NewsInfo> _list = new ArrayList<>();	
String clcDB = "DELETE FROM news_server WHERE char_id NOT IN ( SELECT char_id FROM ( SELECT char_id FROM news_server ORDER BY char_id DESC LIMIT 5 ) foo )";
String loadDt = "SELECT charname,content,content_date,categ FROM news_server ORDER BY content_date DESC LIMIT 5";
static String insertDt = "INSERT INTO news_server (charname,content,content_date,categ) VALUES (?,?,?,?)";
private static final Logger _log = Logger.getLogger(WorldObject.class.getName());
 
public static NewsHandler getInstance()
{
	return SingletonHolder._instance;
}

public class NewsInfo{
	public String name;
	public String content;
	public Long date;
	public String category;
}


public void parseCmd(String command, Player activeChar)
{
	StringTokenizer st = new StringTokenizer(command, " ");
	String actualCommand = st.nextToken();
 
	if(activeChar.isGM()) 
		activeChar.sendMessage("[CMD]: "+command);
 
	if(actualCommand.startsWith("_menuNewsPage")) {
					
		showNews(activeChar);
		
	}else if(actualCommand.startsWith("_menuNewsPost")) {
		String cntpost =  "";
		String nameOFchar = activeChar.getName();
		Long currentTime = Calendar.getInstance().getTimeInMillis();
		String catgPost = "";
 
		if (st.hasMoreTokens())
			catgPost = st.nextToken();
		
		int cmdPst = actualCommand.length();
		int lnPst = catgPost.length();		
		int ttlSb = cmdPst + lnPst;
		cntpost = command.substring(ttlSb);
		
		adminWriteToDB(nameOFchar,cntpost.substring(2),currentTime,catgPost);
		Broadcast.toAllOnlinePlayers(new CreatureSay(0, Say2.CRITICAL_ANNOUNCE, "", "["+nameOFchar+"] made a new post. Check your .menu -> News"));
		_list.clear();
		reloadData();

	}
}
 
public void reloadData() {
	 
	try (Connection con = L2DatabaseFactory.getInstance().getConnection();Statement statement = con.createStatement();
		ResultSet rset = statement.executeQuery(loadDt);)
	{			
		while (rset.next())
		{			
			NewsInfo nf = new NewsInfo();
			nf.name = rset.getString("charname");
			nf.content = rset.getString("content");
			nf.date = rset.getLong("content_date");
			nf.category = rset.getString("categ");
			
			_list.add(nf);	
		}		
		_log.info("NewsHandler: Loaded : ["+_list.size()+"] posts");
	}
	catch (SQLException e)
	{
		_log.info("NewsHandler: Couldn't load NewsList.");
	}
}

public void cleanNewsdb() {
	
	try (Connection con = L2DatabaseFactory.getInstance().getConnection();Statement statement = con.createStatement();)
	{
		statement.execute(clcDB);		
		
		_log.info("NewsHandler: Older posts got deleted.");
	}catch (SQLException e) {
		_log.info("NewsHandler: Error while deleting excess data.");
	}
	
}

public void showNews(Player player) {
final StringBuilder sb = new StringBuilder();
for(NewsInfo tempInfo : _list) {
	if(tempInfo == null)
		break;

String cnvHolder = 	ctgConv(tempInfo.name,tempInfo.date,tempInfo.category);	

sb.append(cnvHolder);
sb.append("<img src=L2UI.SquareGray width=260 height=1>");
sb.append("<table width=260 bgcolor=\"000000\">");
sb.append("<tr><td><font color=b09979>"+tempInfo.content.replaceAll("\\s+"," ")+"</font></td></tr>");					
sb.append("</table>");
sb.append("<img src=L2UI.SquareGray width=260 height=1><br>");

}
NpcHtmlMessage html = new NpcHtmlMessage(0);
html.setFile("data/html/mods/user/news_menu.htm");
html.replace("%newslist%", sb.toString());
player.sendPacket(html);	

}


public static void adminNewsWindow(Player player) {
	final NpcHtmlMessage html = new NpcHtmlMessage(0);
	html.setFile("data/html/mods/user/adminnews_menu.htm");
	player.sendPacket(html);
}
 
private static void adminWriteToDB(String charName,String cont,long dateposted,String catg) {
	try (Connection con = L2DatabaseFactory.getInstance().getConnection();PreparedStatement statement = con.prepareStatement(insertDt);)
	{						
		statement.setString(1, charName);
		statement.setString(2, cont);
		statement.setLong(3, dateposted);
		statement.setString(4, catg);
		statement.execute();
	}
	catch (SQLException e)
	{
		_log.info("NewsHandler: couldn't insert data to DB.");
	}
 
}

private static String ctgConv(String nm,long dt,String ctgr) {
	String otpVl = "";
	switch(ctgr) {
		case "Important":
			 otpVl = "<br><font color=F33B3B>"+ctgr+"</font>&nbsp;&nbsp;&nbsp;"+"<font color=b09979>By</font>&nbsp;&nbsp;<font color=F2F5A9>"+nm+"</font>&nbsp;&nbsp;&nbsp;&nbsp;"+"<font color=AB40A0>"+new SimpleDateFormat("dd MMMM HH:mm").format(dt)+"</font><br1>";
			return otpVl;
		case "Patch":
			 otpVl = "<br><font color=6CDA4B>"+ctgr+"</font>&nbsp;&nbsp;&nbsp;"+"<font color=b09979>By</font>&nbsp;&nbsp;<font color=F2F5A9>"+nm+"</font>&nbsp;&nbsp;&nbsp;&nbsp;"+"<font color=AB40A0>"+new SimpleDateFormat("dd MMMM HH:mm").format(dt)+"</font><br1>"; 
			 return otpVl;
		case "Event":
			 otpVl = "<br><font color=26BEF5>"+ctgr+"</font>&nbsp;&nbsp;&nbsp;"+"<font color=b09979>By</font>&nbsp;&nbsp;<font color=F2F5A9>"+nm+"</font>&nbsp;&nbsp;&nbsp;&nbsp;"+"<font color=AB40A0>"+new SimpleDateFormat("dd MMMM HH:mm").format(dt)+"</font><br1>";  
			return otpVl;
	}	
	return "";	
}
 
 
private static class SingletonHolder
{
	protected static final NewsHandler _instance = new NewsHandler();
}
}

 

GameServer.java

StringUtil.printSection("News");
NewsHandler.getInstance().cleanNewsdb();
NewsHandler.getInstance().reloadData();

 

Html loc -> \gameserver\data\html\mods\user

adminnews_menu.htm

<html><title>Admin - News</title><body><center>
<center>
	<table width=260>
		<tr>
			<td><button value="Main" action="bypass -h admin_admin" width=65 height=19 back="L2UI_ch3.smallbutton2_over" fore="L2UI_ch3.smallbutton2"></td>
			<td><button value="Game" action="bypass -h admin_admin2" width=65 height=19 back="L2UI_ch3.smallbutton2_over" fore="L2UI_ch3.smallbutton2"></td>
			<td><button value="Effects" action="bypass -h admin_admin3" width=65 height=19 back="L2UI_ch3.smallbutton2_over" fore="L2UI_ch3.smallbutton2"></td>
			<td><button value="Server" action="bypass -h admin_admin4" width=65 height=19 back="L2UI_ch3.smallbutton2_over" fore="L2UI_ch3.smallbutton2"></td>
		</tr>
	</table>
		<br>
<img src=L2UI.SquareGray width=260 height=1>

<br><img src="L2UI_CH3.herotower_deco" width=256 height=32><br>
<img src=L2UI.SquareGray width=260 height=1>
<br>New post:<combobox width=120 height=10 var="cat" list=Important;Patch;Event;
<table width=240>
		<tr><td align=center FIXWIDTH=666><MultiEdit var ="cntpost" width=256 height=100></td></tr>	

		<tr><td align=center><button value="confirm" action="bypass -h _menuNewsPost $cat $cntpost" width=55 height=15 back="sek.cbui94" fore="sek.cbui92"></td></tr>
	</table>
	<br>

</center></body></html>

 

news_menu.html

<html><title>User Menu - News</title><body><center>
<center>
	<table width=260>
		<tr>
			<td><button value="Home" action="bypass -h _menuHomePage" width=65 height=19 back="L2UI_ch3.smallbutton2_over" fore="L2UI_ch3.smallbutton2"></td>
			<td><button value="Premium" action="bypass -h _menuVipPage" width=65 height=19 back="L2UI_ch3.smallbutton2_over" fore="L2UI_ch3.smallbutton2"></td>
			<td><button value="Buffs" action="bypass -h _menuBuffsPage" width=65 height=19 back="L2UI_ch3.smallbutton2_over" fore="L2UI_ch3.smallbutton2"></td>
			<td><button value="News" action="bypass -h _menuNewsPage" width=65 height=19 back="L2UI_ch3.smallbutton2_over" fore="L2UI_ch3.smallbutton2"></td>
		</tr>
	</table>
		<br>
<img src=L2UI.SquareGray width=260 height=1>

<br><img src="L2UI_CH3.herotower_deco" width=256 height=32><br>
<img src=L2UI.SquareGray width=260 height=1>
<table width=260 height=27 bgcolor="000000">
	<tr>
	<td align=center width=260><font color=b09979>Latest News</font></td>
</tr>
</table>
<img src=L2UI.SquareGray width=260 height=1>
<br><br>
</center>

%newslist%

</body></html>

 

html loc -> \gameserver\data\html\admin

main_menu.html

<td><button value="Get Buffs" action="bypass -h admin_getbuffs $menu_command" width=55 height=15 back="sek.cbui94" fore="sek.cbui92"></td>
+<td><button value="News" action="bypass -h admin_news" width=55 height=15 back="sek.cbui94" fore="sek.cbui92"></td>

 

adminCommands.xml

+<aCar name="admin_news" accessLevel="7"/>

 

SQL

CREATE TABLE IF NOT EXISTS `news_server` (
  `char_id` int(11) NOT NULL AUTO_INCREMENT,
  `charname` varchar(20) DEFAULT NULL,
  `content` text DEFAULT NULL,
  `content_date` bigint(20) DEFAULT NULL,
  `categ` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`char_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

y i know, char_id doesnt make sense post_id would be the ideal name. Too lazy to change it.

Edited by LordPanic
  • Like 1
Posted
13 hours ago, LordPanic said:

DELETE FROM news_server WHERE char_id NOT IN ( SELECT char_id FROM ( SELECT char_id FROM news_server ORDER BY char_id DESC LIMIT 5 ) foo )

foo :kappa:

 

13 hours ago, LordPanic said:

PreparedStatement statement = con.prepareStatement("INSERT INTO news_server (charname,content,content_date) VALUES (?,?,?)");

 

13 hours ago, LordPanic said:

statement.close();

 

13 hours ago, LordPanic said:

PreparedStatement statement = con.prepareStatement("SELECT charname,content,content_date FROM news_server ORDER BY content_date DESC LIMIT 5"); ResultSet rset = statement.executeQuery();

 

13 hours ago, LordPanic said:

Broadcast.toAllOnlinePlayers(new CreatureSay(0, Say2.CRITICAL_ANNOUNCE, "", "["+nameOFchar+"] made a new post. Check your .menu -> News"));

:notbadn:spam connections and stress testing the database on live servers :anarchy:

 

13 hours ago, LordPanic said:

rset.close(); statement.close();

:serious: time travel back in 2009, thank you for bringing back memories.

 

@Kara you cant write better queries, change my mind.

 

find the differences

https://stackoverflow.com/a/8066594

https://stackoverflow.com/q/22671697

Posted
2 hours ago, Rootware said:

Not sure, but bypass string have limitation in 255 symbols. Isn't it? Maybe better to use WriteBBS command and have ability to input large texts?

True, menu window is small compared to community board so it's better to keep it with 255 char limit otherwise it would be too much.

Posted (edited)
1 hour ago, LordPanic said:

True, menu window is small compared to community board so it's better to keep it with 255 char limit otherwise it would be too much.

So, in your current version it's looks like Server Twitter.

Edited by Rootware
Posted (edited)

Updated: Added 3 categories [Important,Patch,Event], u can add as many u want it's up to you.

Char limit is 255 - (length of command + length of category).

 

58d65eb051901cb03abdf89eb226eadc.png.7294587b352e71efe3a711054d37e3fb.png

 

I also decided to share custom command menu handlers

 

 

Queries got fixed thanks to @Nightwolf.

 

 

Edited by LordPanic

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Posts

    • Server owners, Top.MaxCheaters.com is now live and accepting Lineage 2 server listings. There is no voting, no rankings manipulation, and no paid advantages. Visibility is clean and equal, and early listings naturally appear at the top while the platform grows. If your server is active, it should already be listed. Submit here https://Top.MaxCheaters.com This platform is part of the MaxCheaters.com network and is being built as a long-term reference point for the Lineage 2 community. — MaxCheaters.com Team
    • ⚙️ General Changed “No Carrier” title to “Disconnected” to avoid confusion after abnormal DC. On-screen Clan War kill notifications will no longer appear during Sieges, Epics, or Events. Bladedancer or SwordSinger classes can now log in even when Max Clients (2) is reached, you cannot have both at the same time. The max is 3 clients. Duels will now be aborted if a monster aggros players during a duel (retail-like behavior). Players can no longer send party requests to blocked players (retail-like). Fixed Researcher Euclie NPC dialogue HTML error. Changed Clan leave/kick penalty from 12 hours to 3 hours. 🧙 Skills Adjusted Decrease Atk. Spd. & Decrease Speed land rates in Varka & FoG. Fixed augmented weapons not getting cooldown when entering Olympiad. 🎉 Events New Team vs Team map added. New Save the King map added (old TvT map). Mounts disabled during Events. Letter Collector Event enabled Monsters drop letters until Feb. 13th Louie the Cat in Giran until Feb. 16th Inventory slots +10 during event period 📜 Quests Fixed “Possessor of a Precious Soul Part 1” rare stuck issue when exceeding max quest items. Fixed Seven Signs applying Strife buff/debuff every Monday until restart. 🏆 Milestones New milestone: “Defeat 700 Monsters in Varka” 🎁 Rewards: 200 Varka’s Mane + Daily Coin 🌍 NEW EXP Bonus Zones Hot Springs added Varka Silenos added (hidden spots excluded) As always, thank you for your support! L2Elixir keeps evolving, improving, and growing every day 💙   Website: https://l2elixir.org/ Discord: https://discord.gg/5ydPHvhbxs
    • https://sms.pro/ — we are an SMS activation platform  seeking partners  mobile number providers  mobile number owners  owners of GSM modems  SIM card owners We process 1,000,000 activations every day.  寻找合作伙伴  手机号码提供商  手机号码持有者  GSM调制解调器持有者  SIM卡持有者 我们每天处理1,000,000次激活。  Ищем партнеров  Владельцы сим карт  провайдеров  владельцев мобильных номеров  владельцев модемов  Обрабатываем от 1 000 000 активаций в день ⚡️ Fast. Reliable.   https://sms.pro/ Support: https://t.me/alismsorg_bot
    • "WHAT I WILL SEE ON NEW SEASON ? *More easy farm and augment than ever before ! *Free VIP characters for everyone for first 2 days after opening ! Improved olympiad engine to work more correctly. 3 New skins / outfits. Fixed raid boss spawns. Fixed olympiad crit errors. New farming Ivory Tower area. Fixed augmentation rate. Increased all mob drops rate by +20%. And much more..."   1. I have clicked VIP 23.01.2026 20:00 a few second after open server. 2 Days is 48h. Now 24.01.2026 I have 17 hours left, so my VIP will expire 08:00 25.01.2026. Where is 12h? SCAM.   2. Where is ivory tower area?   3. When next wipe?   
  • Topics

×
×
  • Create New...

Important Information

This community uses essential cookies to function properly. Non-essential cookies and third-party services are used only with your consent. Read our Privacy Policy and We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue..