Skip to content

Instantly share code, notes, and snippets.

@JaciBrunning
Created April 7, 2015 17:21
Show Gist options
  • Save JaciBrunning/7d4d22c652ecf10c1021 to your computer and use it in GitHub Desktop.
Save JaciBrunning/7d4d22c652ecf10c1021 to your computer and use it in GitHub Desktop.
How2Sed
import jaci.irc.gipsy.*
import org.jibble.pircbot.Colors
import java.util.regex.*
class SedRegex extends BotModule {
static class Message {
public String message;
public String sender;
}
static final Pattern sedPattern = Pattern.compile("^([sm])/(.*?(?<!\\\\))/(?:(.*?(?<!\\\\))/)?(.*)");
static HashMap<String, EvictingQueue<Message>> history = new HashMap<>();
@Override
void initModule() {
}
void onMessage(String channel, UserContainer user, String message, IRCBot bot) {
Matcher match = sedPattern.matcher(message)
history.putIfAbsent(channel, new EvictingQueue<Message>(40));
if (match.matches()) {
String pattern = match.group(2);
String replace = match.group(3);
String args = match.group(4);
boolean singleRun = true;
if (pattern != null && args != null) {
int replaceArgs = 0;
for (int i = 0; i < args.length(); ++i) {
switch (args.charAt(i)) {
case 'g':
singleRun = false;
break;
case 'd':
replaceArgs |= Pattern.UNIX_LINES;
break;
case 'i':
replaceArgs |= Pattern.CASE_INSENSITIVE;
break;
case 'm':
replaceArgs |= Pattern.MULTILINE;
break;
case 's':
replaceArgs |= Pattern.DOTALL;
break;
case 'u':
replaceArgs |= Pattern.UNICODE_CASE;
break;
case 'x':
replaceArgs |= Pattern.COMMENTS;
break;
}
}
replace = replace == null ? args : replace;
replace = Colors.BOLD + replace + Colors.BOLD
Pattern replacePattern = Pattern.compile(pattern, replaceArgs);
for (Message s : history.get(channel).toArray(new Message[0])) {
String text = s.message;
String newText = singleRun ? text.replaceFirst(replacePattern.pattern(), replace) : text.replaceAll(replacePattern.pattern(), replace);
if (!text.equals(newText)) {
bot.sendMessage(channel, String.format("(%s) <%s> %s%s", user.getNick(), s.sender, Colors.PURPLE, newText));
Message m = new Message();
m.message = newText; m.sender = user.getNick();
history.get(channel).add(m);
return;
}
}
}
return;
}
Message m = new Message();
m.message = message; m.sender = user.getNick();
history.get(channel).add(m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment