Skip to content

Instantly share code, notes, and snippets.

@YuriFontella
Created May 14, 2019 20:20
Show Gist options
  • Save YuriFontella/5a651d5a75370a82a4dc4e8386d9f2bc to your computer and use it in GitHub Desktop.
Save YuriFontella/5a651d5a75370a82a4dc4e8386d9f2bc to your computer and use it in GitHub Desktop.
integração dois workspaces slackbots
'use strict'
const { RTMClient } = require('@slack/rtm-api')
const { WebClient } = require('@slack/web-api');
const { sleep } = require('sleep')
const web = new WebClient()
const _ = require('lodash')
const model = require('../models')
const slacks = []
const client = async (token) => {
let old_i = await _.find(slacks, { webClient: { token: token } })
if (old_i) {
return old_i
}
let new_i = new RTMClient(token, { autoReconnect: true, useRtmConnect: true })
slacks.push(new_i)
return new_i
}
const users = []
const user = async (token, user) => {
let u = await _.find(users, { user: { id: user } })
if (u) {
return u
}
let response = await web.users.info({
token: token,
user: user
})
users.push(response)
return response
}
const channels = []
const channel = async (token, channel) => {
let c = await _.find(channels, { channel: { id: channel } })
if (c) {
return c
}
let response = await web.channels.info({
token: token,
channel: channel
})
channels.push(response)
return response
}
const up = async () => {
let tokens = await model.integrations.findAll({
attributes: ['bot_access_token']
})
_.map(tokens, async (response) => {
let rtm = await client(response.bot_access_token)
rtm.on('message', async (event) => {
await sleep(2)
console.log(event)
if (event.subtype) {
return
}
let team = '' // astronauts -> Mudar para team metro
let from_token = null
let to_token = null
if (event.team !== team) {
to_token = '' // astronauts -> Mudar para o bot_access_token metro
let result = await model.integrations.findOne({
attributes: ['bot_access_token'],
where: { team_id: event.team }
})
from_token = result.bot_access_token
} else {
from_token = '' // astronauts -> Mudar para o bot_access_token metro
let c = await channel(from_token, event.channel)
let result = await model.integrations.findOne({
attributes: ['bot_access_token'],
include: [{
attributes: [],
model: model.channels, as: 'channels',
where: { name: c.channel.name },
}]
})
to_token = result.bot_access_token
}
let c = await channel(from_token, event.channel)
let u = await user(from_token, event.user)
// let rtm_tmp = await client(token)
// console.log(u)
// console.log(c)
// await rtm_tmp.sendMessage(event.text, 'CJR4QGQHL')
await web.chat.postMessage({
token: to_token,
channel: c.channel.name,
text: event.text,
icon_url: u.user.profile.image_24,
username: u.user.real_name
})
})
let self = await rtm.start()
console.log(self)
})
}
up()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment