Skip to content

Commit

Permalink
ban control
Browse files Browse the repository at this point in the history
  • Loading branch information
lluisd committed Oct 18, 2024
1 parent 0bf965c commit fc6bb55
Show file tree
Hide file tree
Showing 9 changed files with 271 additions and 14 deletions.
75 changes: 72 additions & 3 deletions handlers/ban.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const config = require("../config")
const TwitchService = require('../services/twitch')
const moment = require('moment')
require('mathjs')

class Ban {
async getUnbanRequests(target, bot) {
const result = await TwitchService.getUnbanRequests()
if (result !== null) {
const text = result.length > 0 ? `Hay ${result.length} solicitudes de desbaneo pendientes de revisar (${this._getUserNames(result)})` : 'No hay solicitudes de desbaneo pendientes de revisar.'
const text = result.length > 0 ? `Hay ${result.length} solicitud/es de desbaneo pendientes de revisar (${this._getUserNames(result)})` : 'No hay solicitudes de desbaneo pendientes de revisar.'
await bot.say(target, text)
}
}
Expand All @@ -30,12 +32,79 @@ class Ban {
}
}

async updateBansList(target, bot) {
const bansList = await TwitchService.updateBannedUsers().catch((e) => {
console.error(e +'getBannedUsers on getBannedUsers')}
)
if (bansList && bansList.length > 0) {
const text = `Actualizados ${bansList.length} bans`
await bot.say(target, text)
}
}

async getTimeouts(target, bot) {
const timeouts = await TwitchService.getTimeouts()
if (timeouts) {
const count = Math.min(timeouts.length, 5)
const text = timeouts.length > 0 ? `Último/s ${count} timeouts: ${this._getUserNames(timeouts.slice(0,count))}` : 'Ho hay timeouts.'
await bot.say(target, text)
}
}

async getTimeoutsCount(target, bot) {
const timeouts = await TwitchService.getTimeouts()
if (timeouts) {
const text = `${timeouts.length} timeouts total`
await bot.say(target, text)
}
}

async getTodayBansCount(target, bot) {
const bans = await TwitchService.getBannedUsersCountByDate(moment().startOf('day').toDate())
if (bans) {
const text = `${bans.length} bans hoy`
await bot.say(target, text)
}
}

async getWeeklyBansCount(target, bot) {
const bans = await TwitchService.getBannedUsersCountByDate(moment().startOf('week').toDate())
if (bans) {
const text = `${bans.length} bans esta semana`
await bot.say(target, text)
}
}

async getMonthlyBansCount(target, bot) {
const bans = await TwitchService.getBannedUsersCountByDate(moment().startOf('month').toDate())
if (bans) {
const text = `${bans.length} bans este mes`
await bot.say(target, text)
}
}

async getYearlyBansCount(target, bot) {
const bans = await TwitchService.getBannedUsersCountByDate(moment().startOf('year').toDate())
if (bans) {
const text = `${bans.length} bans este año`
await bot.say(target, text)
}
}

async getTotalBansCount(target, bot) {
const bans = await TwitchService.getBannedUsersCountByDate(moment().subtract(10, 'years').startOf('year').toDate())
if (bans) {
const text = `${bans.length} bans totales`
await bot.say(target, text)
}
}

_getUserNames (unbanRequests) {
let text
if (unbanRequests.length === 1){
text = this._maskUserName(unbanRequests[0].user_name)
text = this._maskUserName(unbanRequests[0].user_name || unbanRequests[0].userName)
} else if (unbanRequests.length > 1) {
text = unbanRequests.map(ur => this._maskUserName(ur.user_name)).join(', ').replace(/, ([^,]*)$/, ' y $1')
text = unbanRequests.map(ur => this._maskUserName(ur.user_name || ur.userName)).join(', ').replace(/, ([^,]*)$/, ' y $1')
}
return text
}
Expand Down
34 changes: 33 additions & 1 deletion helpers/dbmanager.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const Token = require('../models/token')
const Muncipio = require('../models/municipio')
const Channel = require('../models/channel')
const Birthday = require('../models/birthday')
const Ban = require('../models/ban')
const Screenshot = require('../models/screenshot')
const tempsDeFlors = require('../models/tempsDeFlors')
const logConn = require('../db.openai')
Expand Down Expand Up @@ -88,6 +89,31 @@ async function addTitleLogLine (roomId, title, date) {
return conn.model('titleLog').insertMany({roomId: roomId, title: title, date: date})
}

async function addBan (roomId, userName, moderatorName, reason, creationDate, expiryDate) {
return Ban.insertMany({roomId: parseInt(roomId), userName: userName, moderatorName: moderatorName,
reason: reason, creationDate: creationDate, expiryDate: expiryDate})
}

async function removeBan (roomId, userName) {
return Ban.deleteOne({roomId: parseInt(roomId), userName: userName})
}

async function addBans (bans) {
return Ban.insertMany(bans)
}

async function clearBans (roomId) {
return Ban.deleteMany({roomId: parseInt(roomId)});
}

async function getPermanentBans(roomId) {
return Ban.find({roomId: parseInt(roomId), expiryDate: null,moderatorName: { $ne: "sery_bot" }}).lean()
}

async function getTimeouts(roomId) {
return Ban.find({roomId: parseInt(roomId), expiryDate: { $ne: null }}).lean()
}


module.exports = {
getToken,
Expand All @@ -107,5 +133,11 @@ module.exports = {
getTFSpots,
setTFSpot,
addTitleLogLine,
addChatLogLine
addChatLogLine,
addBan,
clearBans,
addBans,
getPermanentBans,
getTimeouts,
removeBan
}
18 changes: 13 additions & 5 deletions lib/eventSub.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const {EventSubMiddleware} = require("@twurple/eventsub-http");
const config = require("../config");
const broadcasterApiClient = require('../broadcasterApiClient')
const TwitchService = require("../services/twitch");

class EventSub {
constructor() {}
Expand Down Expand Up @@ -58,13 +59,20 @@ class EventSub {
this.bot.say(`#${config.twitch.channels}`, `Raid a @${event.raidedBroadcasterDisplayName}!`)
})

this.middleware.onChannelBan(channelId, event => {
this.middleware.onChannelBan(channelId, async event => {
console.log(`${event.moderatorDisplayName} banned ${event.userDisplayName}!`);
if (event.isPermanent) {
this.bot.say(`#${config.twitch.channels}`, `@${event.userDisplayName} ha mordido el polvo!`)
} else {
this.bot.say(`#${config.twitch.channels}`, `Timeout para que @${event.userDisplayName} se calme!`)
if (event.moderatorId !== "402337290") {
if (event.isPermanent) {
this.bot.say(`#${config.twitch.channels}`, `@${event.userDisplayName} ha mordido el polvo!`)
} else {
this.bot.say(`#${config.twitch.channels}`, `Timeout para que @${event.userDisplayName} se calme!`)
}
}
await TwitchService.addBan(channelId, event.userName, event.moderatorName, event.reason, event.startDate, event.endDate)
})

this.middleware.onChannelUnban(channelId, async event => {
await TwitchService.removeBan(channelId, event.userName)
})

this.middleware.onChannelPollBegin(channelId, event => {
Expand Down
38 changes: 37 additions & 1 deletion lib/inputParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,38 @@ class InputParser {
return words.some(word => text.toLowerCase().startsWith(`!${word}`))
}

isAskingUpdateBansList(text) {
return text.toLowerCase().startsWith('!updatebans')
}

isAskingTodayBansCount(text) {
return text.toLowerCase().startsWith('!banshoy')
}

isAskingWeeklyBansCount(text) {
return text.toLowerCase().startsWith('!banssemana')
}

isAskingMonthlyBansCount(text) {
return text.toLowerCase().startsWith('!bansmes')
}

isAskingYearlyBansCount(text) {
return text.toLowerCase().startsWith('!bansaño')
}

isAskingTotalBansCount(text) {
return text.toLowerCase().startsWith('!banstotal')
}

isAskingTimeoutsCount(text) {
return text.toLowerCase().startsWith('!timeoutstotal')
}

isAskingLastTimeouts(text) {
return text.toLowerCase().startsWith('!timeouts')
}

isAskingToSetTitle (text) {
return text.toLowerCase().startsWith('!titulo')
}
Expand All @@ -107,9 +139,13 @@ class InputParser {
return words.some(word => text.toLowerCase().startsWith(`!${word}`))
}

isAskingOpenAI (text) {
isAskingBotOpenAI (text) {
return text.toLowerCase().includes(config.twitch.username)
}

isAskingOpenAI (text) {
return text.toLowerCase().startsWith('!chat')
}
}

module.exports = InputParser
32 changes: 31 additions & 1 deletion lib/messenger.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,30 @@ class Messenger {


// Bans
if (textSplit.length > 0 && inputParser.isAskingTodayBansCount(textSplit[0]) && (isAdmin(context) || isMod(context) || isBroadcaster(context)))
return handlers.ban.getTodayBansCount(target, this.bot)

if (textSplit.length > 0 && inputParser.isAskingWeeklyBansCount(textSplit[0]) && (isAdmin(context) || isMod(context) || isBroadcaster(context)))
return handlers.ban.getWeeklyBansCount(target, this.bot)

if (textSplit.length > 0 && inputParser.isAskingMonthlyBansCount(textSplit[0]) && (isAdmin(context) || isMod(context) || isBroadcaster(context)))
return handlers.ban.getMonthlyBansCount(target, this.bot)

if (textSplit.length > 0 && inputParser.isAskingYearlyBansCount(textSplit[0]) && (isAdmin(context) || isMod(context) || isBroadcaster(context)))
return handlers.ban.getYearlyBansCount(target, this.bot)

if (textSplit.length > 0 && inputParser.isAskingTotalBansCount(textSplit[0]) && (isAdmin(context) || isMod(context) || isBroadcaster(context)))
return handlers.ban.getTotalBansCount(target, this.bot)

if (textSplit.length > 0 && inputParser.isAskingTimeoutsCount(textSplit[0]) && (isAdmin(context) || isMod(context) || isBroadcaster(context)))
return handlers.ban.getTimeoutsCount(target, this.bot)

if (textSplit.length > 0 && inputParser.isAskingLastTimeouts(textSplit[0]) && (isAdmin(context) || isMod(context) || isBroadcaster(context)))
return handlers.ban.getTimeouts(target, this.bot)




if (textSplit.length > 0 && inputParser.isAskingForPendingUnbanRequests(textSplit[0]) &&
this._isNotCooldown('bans', 30) &&
(isVip(context) || isMod(context) || isBroadcaster(context)))
Expand All @@ -161,13 +185,19 @@ class Messenger {
if (textSplit.length > 1 && inputParser.isAskingTOUnbanUser(textSplit[0]) && isAdmin(context))
return handlers.ban.unban(target, textSplit[1], this.bot)

if (textSplit.length > 0 && inputParser.isAskingUpdateBansList(textSplit[0]) && isAdmin(context))
return handlers.ban.updateBansList(target, this.bot)

// Events
if (textSplit.length > 0 && inputParser.isAskingForTarracoMangaEvent(textSplit[0]))
return handlers.events.sendTarracoMangaEvent()

// OPEN AI
if (textSplit.length > 1 && inputParser.isAskingOpenAI(text) && this._isNotCooldown('openai',10)) {
if (textSplit.length > 1 && inputParser.isAskingOpenAI(textSplit[0]) && this._isNotCooldown('openai',15)) {
return handlers.openAI.askOpenAI(target, textSplit[1], context['display-name'], this.bot)
}

if (textSplit.length > 1 && inputParser.isAskingBotOpenAI(text) && this._isNotCooldown('openai',15)) {
const regex = new RegExp(`@?${config.twitch.username}`, 'gi')
const textWithoutMention = text.replace(regex, '').trim()
return handlers.openAI.askOpenAI(target, textWithoutMention, context['display-name'], this.bot)
Expand Down
9 changes: 7 additions & 2 deletions lib/notifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const TelegramBot = require('node-telegram-bot-api')
const config = require('../config')
const cron = require('node-cron')
const handlers = require('../handlers')
const TwitchService = require("../services/twitch");

class Notifier {
constructor (twitchBot) {
Expand All @@ -15,18 +16,22 @@ class Notifier {
await handlers.stream.catchStream(this.bot, this.twitchBot, this.target)
})

cron.schedule('0/15 * * * *', async () => {
cron.schedule('5 * * * *', async () => {
await handlers.stream.sendTodayBirthday(this.twitchBot, this.target)
})

cron.schedule('0/30 * * * *', async () => {
await handlers.stream.refreshPage()
})

cron.schedule('0/15 * * * *', async () => {
cron.schedule('0 * * * *', async () => {
await handlers.events.sendTarracoMangaEvent()
})

cron.schedule('0 4 * * *', async () => {
await handlers.ban.updateBansList()
})

return Promise.resolve()
}

Expand Down
32 changes: 32 additions & 0 deletions models/ban.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const mongoose = require('mongoose')
const Schema = mongoose.Schema

/* Ban Schema */
const BanSchema = new Schema({
roomId: {
type: Number,
required: true
},
userName: {
type: String,
required: true
},
moderatorName: {
type: String,
required: false
},
reason: {
type: String,
required: false
},
creationDate: {
type: Date,
required: true
},
expiryDate: {
type: Date,
required: false
}
})

module.exports = mongoose.model('ban', BanSchema, 'bans')
5 changes: 5 additions & 0 deletions services/openAI.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ async function askAssistant(message) {
assistantThread.id
);
result = messagesResponse.data[0].content[0].text.value;
result = cleanAssistantText(result)
} else {
console.log(`Run status is ${runStatus}, unable to fetch messages.`);
}
Expand All @@ -104,6 +105,10 @@ async function askAssistant(message) {
return result
}

function cleanAssistantText(text) {
return text.replaceAll(/.*?/g, "")
}


async function _getHeaders () {
return {
Expand Down
Loading

0 comments on commit fc6bb55

Please sign in to comment.