Skip to content

Commit

Permalink
Move telegram and discord bot config to mysql (#242)
Browse files Browse the repository at this point in the history
* Add server config cache support

* move bot config to MySQL
  • Loading branch information
yuanmomo authored May 2, 2024
1 parent 01cca4e commit e6086f9
Show file tree
Hide file tree
Showing 19 changed files with 230 additions and 214 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
@ToString
@Service
@Slf4j
public class ActivityConfig implements Configurable {
public class ActivityConfig{
private static long taskCount;
private AnnualActivityConfig annualActivityConfig;

Expand Down
13 changes: 5 additions & 8 deletions src/main/java/com/dl/officialsite/bot/BaseBotService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,16 @@

import com.dl.officialsite.bot.constant.ChannelEnum;
import com.dl.officialsite.bot.constant.GroupNameEnum;
import com.dl.officialsite.bot.model.BaseBotConfig;
import com.dl.officialsite.bot.model.Message;
import lombok.Data;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;


@Data
public abstract class BaseBotService<T extends BaseBotConfig> {
@Autowired private T botConfig;
public interface BaseBotService {

public abstract Pair<Boolean, String> sendMessage(GroupNameEnum groupNameEnum, ChannelEnum channelEnum, Message text);
boolean isBotInitialized();

public abstract boolean isUserInChannel(String channelId, String userId);
Pair<Boolean, String> sendMessage(GroupNameEnum groupNameEnum, ChannelEnum channelEnum, Message text);

boolean isUserInChannel(String channelId, String userId);

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.dl.officialsite.bot.model;
package com.dl.officialsite.bot.config;

import com.dl.officialsite.bot.constant.GroupNameEnum;
import lombok.Data;
Expand All @@ -7,8 +7,8 @@
import java.util.List;

@Data
public class BotGroup<G, T> {
private G groupId;
public class BotGroup{
private String groupId;
private GroupNameEnum groupName;
private List<BotTopic<T>> topicOrChannelList = new ArrayList<>();
}
private List<BotTopic> topicOrChannelList = new ArrayList<>();
}
13 changes: 13 additions & 0 deletions src/main/java/com/dl/officialsite/bot/config/BotServerConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.dl.officialsite.bot.config;

import com.dl.officialsite.config.bean.Configurable;
import lombok.Data;

import java.util.List;

@Data
public class BotServerConfig implements Configurable {
List<BotGroup> groupList;
String botToken;
String timeoutInSeconds;
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package com.dl.officialsite.bot.model;
package com.dl.officialsite.bot.config;

import com.dl.officialsite.bot.constant.ChannelEnum;
import lombok.Data;

@Data
public class BotTopic<T> {
public class BotTopic {
private ChannelEnum name;
private T threadOrTopicId;
private String threadOrTopicId;

public static <T> BotTopic<T> build(ChannelEnum channelEnum, T threadOrTopicId){
public static BotTopic build(ChannelEnum channelEnum, String threadOrTopicId) {
BotTopic botTopic = new BotTopic();
botTopic.setName(channelEnum);
botTopic.setThreadOrTopicId(threadOrTopicId);
return botTopic;
}
}
}
4 changes: 3 additions & 1 deletion src/main/java/com/dl/officialsite/bot/constant/BotEnum.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.dl.officialsite.bot.constant;

import lombok.Getter;

@Getter
public enum BotEnum {
ALL, TELEGRAM, DISCORD;

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

@Getter
public enum ChannelEnum {
GENERAL("general-chat"),
GENERAL("general-chat", "general"),
HIRING("hiring", "job", "hiring-and-applying", "applying"),
SHARING("sharing", "sharing_team"),
BUILDER("builder"),
Expand All @@ -32,6 +32,5 @@ public static ChannelEnum of(String channelNameOrTopicName) {
.findFirst().orElse(null);
}

private Set<String> channelNameKeyWordsSet;

private final Set<String> channelNameKeyWordsSet;
}
80 changes: 80 additions & 0 deletions src/main/java/com/dl/officialsite/bot/discord/DiscordBot.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.dl.officialsite.bot.discord;

import com.dl.officialsite.bot.config.BotServerConfig;
import com.dl.officialsite.bot.config.BotTopic;
import com.dl.officialsite.bot.constant.BotEnum;
import com.dl.officialsite.bot.constant.ChannelEnum;
import com.dl.officialsite.bot.model.BaseBot;
import com.dl.officialsite.config.constant.ConfigEnum;
import com.dl.officialsite.config.service.ServerConfigCacheService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Data
@EqualsAndHashCode(callSuper = false)
@Service
public class DiscordBot extends BaseBot<JDA> {
@Autowired
private ServerConfigCacheService serverConfigCacheService;

@EventListener(ApplicationReadyEvent.class)
public void startUp() {
this.botEnum = BotEnum.DISCORD;
this.botServerConfig = serverConfigCacheService.get(ConfigEnum.DISCORD_BOT_CONFIG, BotServerConfig.class);
Optional.ofNullable(this.botServerConfig).ifPresent(config -> {
this.init();
});
}

@Override
public void initBot() {
try {
bot = JDABuilder.createDefault(this.botServerConfig.getBotToken()).build().awaitReady();
log.info("Init Guild(server) and threads map...");
this.botServerConfig.getGroupList().forEach(guildConfig -> {
Guild guild = bot.getGuildById(guildConfig.getGroupId());
if (guild == null) {
log.error("Cannot find Guild for id:[{}]", guildConfig.getGroupId());
return;
}
List<TextChannel> textChannels = guild.getTextChannels();
if (CollectionUtils.isEmpty(textChannels)) {
log.error("Cannot find any text channel for id:[{}]", guildConfig.getGroupId());
return;
}
List<BotTopic> botTopicList = textChannels.stream()
.map(textChannel -> BotTopic.build(ChannelEnum.of(textChannel.getName()), textChannel.getId()))
.filter(botTopic -> Objects.nonNull(botTopic.getName()))
.collect(Collectors.toList());
guildConfig.setTopicOrChannelList(botTopicList);
});
} catch (InterruptedException e) {
log.error("Init Discord bot error.", e);
}
}

@Override
public String toString() {
return new ToStringBuilder(this)
.append("botServerConfig", botServerConfig)
.append("bot", bot)
.toString();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,35 @@
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service
public class DiscordBotService extends BaseBotService<DiscordBotConfig> {
public class DiscordBotService implements BaseBotService {
private static final String IS_USER_IN_CHANNEL_API = "https://discord.com/api/v9/guilds/%s/members/%s";

@Autowired
private DiscordBot discordBot;

@Override
public boolean isBotInitialized() {
return discordBot.getBot() != null;
}

@Override
public Pair<Boolean, String> sendMessage(GroupNameEnum groupNameEnum, ChannelEnum channelEnum, Message msg) {
Pair<String, String> channelIdByName = this.getBotConfig().getGroupIdAndChannelIdByName(groupNameEnum, channelEnum);
return DiscordBotUtil.sendMessageToChannel(this.getBotConfig().getBot(), channelIdByName.getValue(), msg);
Pair<String, String> channelIdByName = this.discordBot.getGroupIdAndChannelIdByName(groupNameEnum, channelEnum);
return DiscordBotUtil.sendMessageToChannel(this.discordBot.getBot(), channelIdByName.getValue(), msg);
}

@Override
public boolean isUserInChannel(String channelId, String userId) {
HttpGet httpGet = new HttpGet(String.format(IS_USER_IN_CHANNEL_API, channelId, userId));
httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bot " + this.getBotConfig().getBotToken());
httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bot " + this.discordBot.getBotServerConfig().getBotToken());

try {
HttpResponse response = HttpUtil.client().execute(httpGet);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,14 @@ private void sendMessage(BotEnum botEnum, GroupNameEnum group, ChannelEnum chann

switch (botEnum) {
case DISCORD:
Optional.ofNullable(discordBotService.getBotConfig().getBot()).ifPresent(service ->
discordBotService.sendMessage(group, channelEnum, message));
if (discordBotService.isBotInitialized()) {
discordBotService.sendMessage(group, channelEnum, message);
}
break;
case TELEGRAM:
Optional.ofNullable(telegramBotService.getBotConfig().getBot()).ifPresent(service ->
telegramBotService.sendMessage(group, channelEnum, message));
if (telegramBotService.isBotInitialized()) {
telegramBotService.sendMessage(group, channelEnum, message);
}
break;
default:
break;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,53 +1,41 @@
package com.dl.officialsite.bot.model;

import com.dl.officialsite.bot.config.BotServerConfig;
import com.dl.officialsite.bot.config.BotTopic;
import com.dl.officialsite.bot.constant.BotEnum;
import com.dl.officialsite.bot.constant.ChannelEnum;
import com.dl.officialsite.bot.constant.GroupNameEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@Slf4j
public abstract class BaseBotConfig<B, G, T> {
BotEnum botEnum;
protected String botToken;
@Getter
public abstract class BaseBot<B> {
protected BotEnum botEnum;
protected BotServerConfig botServerConfig;

protected B bot;
protected int timeoutInSeconds = 10;

public BaseBotConfig(BotEnum botEnum) {
this.botEnum = botEnum;
}

protected List<BotGroup<G, T>> groupList = new ArrayList<>();

public abstract B initBot() throws InterruptedException;
public abstract void initBot();

@PostConstruct
public void init() throws InterruptedException {
public void init() {
log.info("Start to init bot:[{}] ...", botEnum);

if (StringUtils.containsIgnoreCase(botToken, "BOT_TOKEN")) {
if (StringUtils.containsIgnoreCase(botServerConfig.getBotToken(), "BOT_TOKEN")) {
log.warn("Bot:[{}] is not configured properly!!!", botEnum);
} else {
bot = initBot();
initBot();
}
log.info("The {} Bot is initialized and ready with detail:[{}]!!!", botEnum, this.toString());
}

public Pair<G, T> getGroupIdAndChannelIdByName(GroupNameEnum groupNameEnum, ChannelEnum channelEnum) {
public Pair<String, String> getGroupIdAndChannelIdByName(GroupNameEnum groupNameEnum, ChannelEnum channelEnum) {
final GroupNameEnum groupName = groupNameEnum == null ? GroupNameEnum.DAPP_LEARNING : groupNameEnum;
final ChannelEnum channel = channelEnum == null ? ChannelEnum.GENERAL : channelEnum;

return groupList.stream().filter(group -> group.getGroupName() == groupName)
return botServerConfig.getGroupList().stream().filter(group -> group.getGroupName() == groupName)
.map(group -> Pair.of(group.getGroupId(),
group.getTopicOrChannelList().stream().filter(topic -> topic.getName() == channel)
.map(BotTopic::getThreadOrTopicId)
Expand Down
Loading

0 comments on commit e6086f9

Please sign in to comment.