Skip to content

Instantly share code, notes, and snippets.

@jagrosh
Last active June 17, 2022 21:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jagrosh/ae10c82f6a822a72f60aae398fdf722e to your computer and use it in GitHub Desktop.
Save jagrosh/ae10c82f6a822a72f60aae398fdf722e to your computer and use it in GitHub Desktop.
Bot to give a role only when a member is live
/*
* Copyright 2018 John Grosh (jagrosh).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.Game;
import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.events.user.UserGameUpdateEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author John Grosh (john.a.grosh@gmail.com)
*/
public class StreamRoleBot extends ListenerAdapter
{
private final static String FILENAME = "stream-roles.txt";
private final static Logger LOG = LoggerFactory.getLogger(StreamRoleBot.class);
private final List<Long> list;
public StreamRoleBot() throws Exception
{
list = new ArrayList<>();
Files.readAllLines(Paths.get(FILENAME), StandardCharsets.UTF_8).forEach(line ->
{
try
{
list.add(Long.parseLong(line.replace("\uFEFF", "")));
}
catch(Exception e)
{
LOG.warn("Could not parse: "+line);
}
});
}
@Override
public void onUserGameUpdate(UserGameUpdateEvent event)
{
if(event.getMember()==null)
return;
Role role = list.stream().map(id -> event.getMember().getGuild().getRoleById(id)).filter(r -> r!=null).findFirst().orElse(null);
if(role==null)
return;
if(event.getMember().getGame().getType()==Game.GameType.STREAMING)
event.getGuild().getController().addSingleRoleToMember(event.getMember(), role).queue();
else
event.getGuild().getController().removeSingleRoleFromMember(event.getMember(), role).queue();
}
public static void main(String[] args) throws Exception
{
new JDABuilder(AccountType.BOT)
.setToken(Files.readAllLines(Paths.get("config.txt")).get(0))
.addEventListener(new StreamRoleBot())
.buildAsync();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment