Skip to content

Commit

Permalink
add notifier to telegram bot
Browse files Browse the repository at this point in the history
  • Loading branch information
lluisd committed Feb 2, 2024
1 parent 535362a commit f3f59ef
Show file tree
Hide file tree
Showing 12 changed files with 595 additions and 9 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/main_twitch-mz-bot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ jobs:
envKey_AEMET_API_KEY: ${{ secrets.AEMET_API_KEY }}
envKey_SQL_CONNECTION: ${{ secrets.SQL_CONNECTION }}
envkey_PORT: 3000
envkey_TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }}
envKey_TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}

- name: Set up Node.js version
uses: actions/setup-node@v4
Expand Down
3 changes: 3 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const Messenger = require('./lib/messenger')
const mongoose = require('mongoose')
const config = require('./config')
const express = require("express")
const Notifier = require('./lib/notifier')

mongoose.connect(config.database).then(() => {
const messenger = new Messenger()
Expand All @@ -15,6 +16,8 @@ mongoose.connect(config.database).then(() => {
app.get('/', (req, res) => res.send('Hello World!'))
})
})
const notifier = new Notifier()
notifier.notify()
})


Expand Down
4 changes: 4 additions & 0 deletions config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,9 @@ module.exports = {
},
sql : {
connectionString: process.env.SQL_CONNECTION
},
telegram: {
apiKey: process.env.TELEGRAM_TOKEN,
chatId: process.env.TELEGRAM_CHAT_ID
}
}
4 changes: 3 additions & 1 deletion handlers/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
const Generic = require('./generic')
const Weather = require('./Weather')
const Train = require('./Train')
const Stream = require('./Stream')

module.exports = {
generic: new Generic(),
weather: new Weather(),
train: new Train()
train: new Train(),
stream: new Stream()
}
52 changes: 52 additions & 0 deletions handlers/stream.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const TwitchService = require('../services/twitch')
const config = require("../config");

const twitchUrl = 'https://www.twitch.tv/'

class Stream {
async catchStream (bot) {
const result = await TwitchService.getStream()

if (result) {
const image = `[\u200c](${result.thumbnail_url.replace('{width}', '400').replace('{height}', '300')})`
const link = `[${twitchUrl}${result.user_name}](${twitchUrl}${result.user_name})`
const directo = `*¡EN DIRECTO!*`
const text = `${image} ${directo} ${link}`

const options = {
parse_mode: 'markdown'
}

bot.sendMessage(config.telegram.chatId, text, options)
}

// {
// "id": "40400588869",
// "user_id": "779563374",
// "user_login": "manzana_oscura",
// "user_name": "manzana_oscura",
// "game_id": "516575",
// "game_name": "VALORANT",
// "type": "live",
// "title": "aver si veo por donde me matan",
// "viewer_count": 8,
// "started_at": "2024-02-02T12:05:37Z",
// "language": "es",
// "thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_manzana_oscura-{width}x{height}.jpg",
// "tag_ids": [],
// "tags": [
// "PequeñaGranComunidad",
// "PreguntaYRespondo",
// "lectura",
// "ASMR",
// "Relajacion",
// "Meditacion",
// "Español",
// "English"
// ],
// "is_mature": false
// }
}
}

module.exports = Stream
14 changes: 13 additions & 1 deletion helpers/dbmanager.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const Token = require('../models/token')
const Muncipio = require('../models/municipio')
const Channel = require('../models/channel')

function getToken (userId) {
return Token.findOne({userId: userId})
Expand All @@ -9,6 +10,15 @@ function updateToken (userId, update) {
return Token.updateOne({userId: userId}, update)
}

function getChannel (name) {
return Channel.findOne({name: name})
}

function updateChannel (name, isLive) {
return Channel.updateOne({name: name}, { live: isLive })

}

async function getMuncipioStartsWith (name) {
return Muncipio.findOne({nombre: { "$regex": "^" + name , "$options": "i"}}).lean()
}
Expand All @@ -31,5 +41,7 @@ module.exports = {
getMunicipio,
getMuncipioStartsWith,
getMuncipioEndsWith,
getMuncipioContains
getMuncipioContains,
getChannel,
updateChannel
}
10 changes: 10 additions & 0 deletions lib/messenger.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ class Messenger {
listen () {
this.bot.on('message', this.handleText.bind(this));
this.bot.on('connected', this.handleConnect.bind(this));
this.bot.on('unhost', this.handleUnhost.bind(this));
this.bot.on('hosting', this.handleHosting.bind(this));

return this.bot.connect().catch(console.error)
}
Expand Down Expand Up @@ -72,6 +74,14 @@ class Messenger {
}
}

handleHosting (channel, target, viewers) {
console.log(`* Hosting ${channel} to ${target} with ${viewers} viewers`);
}

handleUnhost (channel, viewers) {
console.log(`* Unhosting ${channel} with ${viewers} viewers`);
}

handleConnect (addr, port) {
console.log(`* Connected to ${addr}:${port}`);
}
Expand Down
20 changes: 20 additions & 0 deletions lib/notifier.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const TelegramBot = require('node-telegram-bot-api')
const config = require('../config')
const cron = require('node-cron')
const handlers = require('../handlers')

class Notifier {
constructor () {
this.bot = new TelegramBot(config.telegram.apiKey)
}

notify () {
cron.schedule('*/1 * * * *', () => {
handlers.stream.catchStream(this.bot)
})

return Promise.resolve()
}
}

module.exports = Notifier
16 changes: 16 additions & 0 deletions models/channel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const mongoose = require('mongoose')
const Schema = mongoose.Schema

/* Channel Schema */
const ChannelSchema = new Schema({
name: {
type: String,
required: true
},
live: {
type: Boolean,
required: true
}
})

module.exports = mongoose.model('channel', ChannelSchema, 'channels')
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
"express": "^4.18.2",
"mongoose": "^8.1.1",
"mssql": "^10.0.2",
"node-cron": "^3.0.3",
"node-telegram-bot-api": "^0.64.0",
"tmi.js": "^1.8.5"
},
"scripts": {
Expand Down
34 changes: 34 additions & 0 deletions services/twitch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const config = require('../config')
const dbManager = require('../helpers/dbmanager')

const endpointPrefix = 'https://api.twitch.tv/helix/streams'

async function getStream() {
let result = null

const token = await dbManager.getToken(parseInt(config.twitch.userId)).lean()
const endpoint = endpointPrefix + '?user_login=' + config.twitch.channels
const options = {
headers: {
'Client-Id': config.twitch.clientId,
'Authorization': 'Bearer ' + token.accessToken
}
}
const response = await fetch(endpoint, options)
const data = await response.json()
const liveData = data?.data?.[0] ?? null

const channel = await dbManager.getChannel(config.twitch.channels).lean()
if (liveData && !channel.live) {
await dbManager.updateChannel(config.twitch.channels, true)
result = liveData
} else if (!liveData && channel.live) {
await dbManager.updateChannel(config.twitch.channels, false)
}

return result
}

module.exports = {
getStream
}
Loading

0 comments on commit f3f59ef

Please sign in to comment.