Skip to content

Instantly share code, notes, and snippets.

@msklywenn
Created July 19, 2019 13:04
Show Gist options
  • Save msklywenn/86e2d1d76dd7c9ce01bee3cf1dc474e5 to your computer and use it in GitHub Desktop.
Save msklywenn/86e2d1d76dd7c9ce01bee3cf1dc474e5 to your computer and use it in GitHub Desktop.
const Twitch = require("twitch").default;
const Discord = require("discord.js");
const ChatClient = require("twitch-chat-client").default;
// environment variables to be set for script to run properly
const {
CODE, // generate code with authorization code flow
// see: https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-authorization-code-flow
CLIENT_ID, // client id of twitch app
CLIENT_SECRET, // client secret of twitch app (for token renewal)
USERNAME, // twitch username
GAME, // name of the game to host
DISCORD, // discord app token
DISCORD_CHANNEL // discord channel ID to put messages on
} = process.env;
const UPDATE_DELAY = 60000; // milliseconds, 60000 = every minute
const BETTER_RATIO = 1.5; // how much more many viewers a streamer must have to cut currently hosted streamer
const AutoGameHoster =
{
lastNbHosts: Date.now(),
hostsLeft: 5,
knownStreams: [],
async update()
{
// reconnect if necessary
if (this.token.isExpired)
{
this.token = await Twitch.refreshAccessToken(CLIENT_ID, CLIENT_SECRET, token.refreshToken);
await connect();
}
// find the streamer with most views on target game
var streams = await this.client.helix.streams.getStreams({game: this.game.id});
streams = await streams.getAll();
if (streams !== null && streams.length > 0)
{
streams.forEach(stream => {
if (!this.knownStreams.includes(stream))
{
this.discordChannel.send(`${bestUser.displayName} is streaming ${GAME} <3 ${channel.url}`);
array_push(this.knownStreams, stream);
}
});
this.knownStreams = this.knownStreams.filter(stream => streams.includes(stream));
}
else
{
this.knownStreams = [];
}
},
async init()
{
this.token = await Twitch.getAccessToken(CLIENT_ID, CLIENT_SECRET, CODE, "http://localhost");
await this.connect();
this.discord = new Discord.Client();
var that = this;
this.discord.on("ready", () => { that.discordChannel = that.discord.channels.get(DISCORD_CHANNEL);});
this.discord.login(DISCORD);
setInterval(() => this.update().catch(console.error), UPDATE_DELAY);
},
async connect()
{
this.client = await Twitch.withCredentials(CLIENT_ID, this.token.accessToken);
this.game = await this.client.helix.games.getGameByName(GAME);
if (this.game != null)
{
this.chatClient = await ChatClient.forTwitchClient(this.client);
await this.chatClient.connect();
await this.chatClient.waitForRegistration();
await this.chatClient.join(`#${USERNAME}`);
await this.update();
}
}
};
AutoGameHoster.init().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment